NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

Redis 8.12: Give Each Set Member Its Own TTL

Redis 8.12 lets every member of a set expire on its own. Build a who's-online list and a webhook dedupe window with SADDEX, with no cleanup job.

Updated Dec 1, 20268 min readIntermediateredis 8.12.0 · node-redis 6.4.0 · node 22.22.3

A "who's online" list sounds like a job for a Redis set: add a user when they show up, remove them when they leave. The problem is the leaving. Users close tabs without saying goodbye, so you end up with timestamps in a sorted set and a cleanup job that trims old entries.

Redis 8.12 removes that work. Each member of a set can now have its own TTL, and Redis drops the member when it runs out. This guide covers the new commands in redis-cli, then builds two small Node.js examples: a presence list and a webhook dedupe window.

What changed in Redis 8.12

Redis 8.12 added per-member expiration to sets. It works like hash field expiration, which arrived in Redis 7.4, and the command names follow the same pattern.

CommandWhat it does
SADDEXAdd members and set their TTL in one call
SEXPIRE / SPEXPIRESet a TTL in seconds or milliseconds
SEXPIREAT / SPEXPIREATExpire at a Unix timestamp
STTL / SPTTLRead the remaining TTL
SEXPIRETIME / SPEXPIRETIMERead the expiry as a timestamp
SPERSISTRemove a member's TTL

Every command except SADDEX takes members as MEMBERS count member [member ...], so one call can update many members. The full list is in the set member expiration docs.

1. Start Redis 8.12

The official Docker image has an 8.12 tag. This maps it to port 6381 so it won't clash with a Redis you already run on 6379:

terminal
docker run --rm -d --name redis-812 -p 6381:6379 redis:8.12
docker exec redis-812 redis-server --version
text
Redis server v=8.12.0 sha=00000000:1 malloc=jemalloc-5.3.0 bits=64 build=fd830cb91781c231

Open a shell with docker exec -it redis-812 redis-cli.

2. Give members a TTL

Add two users with a 30-second TTL, add a third with plain SADD, then check the TTL of each, including one who isn't in the set:

text
> SADDEX online EX 30 MEMBERS 2 alice bob
(integer) 1
> SADD online carol
(integer) 1
> STTL online MEMBERS 4 alice bob carol dave
1) (integer) 30
2) (integer) 30
3) (integer) -1
4) (integer) -2

-1 means the member has no TTL. -2 means it isn't in the set. These are the same codes TTL uses for keys.

Now give bob 1.5 seconds and wait two seconds:

text
> SPEXPIRE online 1500 MEMBERS 1 bob
1) (integer) 1
> SMEMBERS online
1) "alice"
2) "carol"
> SISMEMBER online bob
(integer) 0

bob is gone, and the rest of the set wasn't touched. With a key-level EXPIRE, the whole set would have expired.

3. Learn the refresh rules

Presence lists and dedupe windows both depend on what happens when you touch a member that already has a TTL. These are the rules, starting from an empty online set:

text
> DEL online
(integer) 1
> SADDEX online EX 30 MEMBERS 1 alice
(integer) 1
> SADD online alice
(integer) 0
> STTL online MEMBERS 1 alice
1) (integer) 30
> SEXPIRE online 10 GT MEMBERS 1 alice
1) (integer) 0
> SEXPIRE online 60 GT MEMBERS 1 alice
1) (integer) 1
> SADDEX online MEMBERS 1 alice
(integer) 1
> STTL online MEMBERS 1 alice
1) (integer) -1

What happened, line by line:

  • SADD never changes a TTL. Adding alice again left her 30 seconds in place.
  • GT only extends. A 10-second TTL was refused (0) because 30 is longer. The 60-second TTL was applied (1). NX, XX and LT work the same way they do for keys.
  • SADDEX with no expiry option clears the TTL. alice is now permanent.

Two more rules: SPERSIST removes a TTL, and a TTL of 0 deletes the member right away. If that empties the set, the key goes too. This gives alice a TTL again, removes it, then deletes her:

text
> SEXPIRE online 30 MEMBERS 1 alice
1) (integer) 1
> SPERSIST online MEMBERS 2 alice zed
1) (integer) 1
2) (integer) -2
> SEXPIRE online 0 MEMBERS 1 alice
1) (integer) 2
> EXISTS online
(integer) 0

The reply 2 means "removed because the TTL was 0", as listed in the SEXPIRE docs.

4. Build a who's-online list in Node.js

node-redis 6.4.0 has all the new commands. The camelCase names are sAddEx, sExpire, sTTL, spTTL and sPersist.

terminal
npm init -y
npm install [email protected]

Each heartbeat re-adds the user with a fresh TTL. A user who stops sending heartbeats drops out of the set by themselves. The TTL is 2 seconds so the demo is quick:

presence.mjs
import { createClient } from 'redis';

const redis = await createClient({ url: 'redis://localhost:6381' }).connect();

const KEY = 'online';
const TTL_MS = 2000; // short so the demo is quick; use 30–60 s in production

// Call this on every request or websocket ping from a user.
async function heartbeat(userId) {
  await redis.sAddEx(KEY, userId, { expiration: { type: 'PX', value: TTL_MS } });
}

async function whoIsOnline() {
  return (await redis.sMembers(KEY)).sort();
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

await redis.del(KEY);
await heartbeat('alice');
await heartbeat('bob');
console.log('t=0.0s', await whoIsOnline());

await sleep(1500);
await heartbeat('alice'); // alice is still active, bob went quiet
await sleep(1000);

console.log('t=2.5s', await whoIsOnline());
console.log('ms left', await redis.spTTL(KEY, ['alice', 'bob']));

await redis.close();
terminal
node presence.mjs
text
t=0.0s [ 'alice', 'bob' ]
t=2.5s [ 'alice' ]
ms left [ 995, -2 ]

Nothing in this code removes bob. Redis did it when his TTL ran out. alice stayed because her second heartbeat reset her TTL. There's no cron job and no ZREMRANGEBYSCORE call, and SMEMBERS returns only live users.

5. Deduplicate webhooks with MNX

Webhook providers retry, so the same event can arrive twice. With MNX, SADDEX adds the members only if none of them are already in the set. Combined with a TTL, that gives you a dedupe window in one round trip:

dedupe.mjs
import { createClient } from 'redis';

const redis = await createClient({ url: 'redis://localhost:6381' }).connect();

// True the first time an event ID is seen in the last 10 minutes.
async function isFirstDelivery(eventId) {
  const added = await redis.sAddEx('webhooks:seen', eventId, {
    mode: 'MNX',
    expiration: { type: 'EX', value: 600 },
  });
  return added === 1;
}

await redis.del('webhooks:seen');
for (const id of ['evt_1', 'evt_2', 'evt_1']) {
  console.log(id, (await isFirstDelivery(id)) ? 'process' : 'skip (duplicate)');
}
console.log('ttl', await redis.sTTL('webhooks:seen', ['evt_1', 'evt_2']));

await redis.close();
terminal
node dedupe.mjs
text
evt_1 process
evt_2 process
evt_1 skip (duplicate)
ttl [ 600, 600 ]

Check one ID per call. MNX applies to the whole group: if any listed member already exists, nothing is added and the reply is 0. SADDEX seen MNX EX 600 MEMBERS 2 evt-42 evt-43 adds neither ID when evt-42 is already there.

Before 8.12, the usual way to do this was one key per event (SET webhook:evt_1 1 NX EX 600). That still works. The set version keeps all IDs under one key, so you can count, scan or clear them together.

What this replaces

The old pattern for presence stored a timestamp as each member's score and trimmed old members before every read:

text
> ZADD online:z 1764583200 alice 1764583230 bob
(integer) 2
> ZREMRANGEBYSCORE online:z -inf 1764583215
(integer) 1
> ZRANGE online:z 0 -1
1) "bob"

It works, but every reader has to trim first, or a job has to do it on a timer. If one code path forgets, it shows stale users. With member TTLs, Redis does the removal, and every read is correct without the extra step.

Keep the sorted set if you need ordering, such as "most recently active first", or the last-seen time itself. A set with TTLs tells you who is online, not when they were last seen.

Caveats

  • SCARD can over-count. Other set commands treat an expired member as missing right away. SCARD can still count members that have expired but haven't been reclaimed yet, according to the SEXPIRE docs. If an exact count matters, count the SMEMBERS or SSCAN results instead.

  • Sorted set commands reject these sets. ZUNION, ZINTER and other sorted set commands that accept plain sets as input return an error for a set with member TTLs. Here a was created with SADDEX a EX 100 MEMBERS 2 x y and b with a plain SADD:

    text
    > ZUNION 2 a b
    (error) ERR operation not supported on a set with member expirations
  • Store commands copy TTLs. SINTERSTORE, SUNIONSTORE and SDIFFSTORE copy member TTLs into the destination set, and SMOVE moves a member together with its TTL. A snapshot made with SUNIONSTORE will lose members over time.

  • Managed Redis may not have it yet. The command docs list member expiration as not supported on Redis Software or Redis Cloud at the time of writing. Check your provider's version before relying on it.

  • Notifications report the key, not the member. With set events enabled (CONFIG SET notify-keyspace-events Es), Redis publishes a sexpired event on __keyevent@0__:sexpired with the key name online. It doesn't say which member expired. See keyspace notifications.

When you're done, stop the container with docker stop redis-812. Because it was started with --rm, stopping it also deletes it.

Next steps

  • Read the SADDEX reference for EXAT, PXAT and MXX.
  • Use SPERSIST (docs) to make a member permanent, for example when a trial user upgrades.
  • Look through the Redis 8.12 release notes for the other additions: compressed bitmaps, the new sorted set encoding and ZMOVE.

Related tutorials