Popping from Sorted Sets

Difficulty: Intermediate

Question

How do you atomically remove and return the member with the highest score from a Sorted Set, and how do you wait for one if the set is empty?

Answer

Use ZPOPMAX key [count]. It removes and returns the member (and its score) with the highest score in one atomic step; ZPOPMIN does the same for the lowest score. Both were added in Redis 5.0. To wait for an element when the set is empty, use the blocking versions BZPOPMAX / BZPOPMIN with a timeout, and in Redis 7.0+ ZMPOP / BZMPOP can pop from the first non-empty of several sets.

Why not ZRANGE then ZREM?

Reading the top member with ZRANGE key 0 0 REV and then deleting it with ZREM is two commands. Two workers can read the same top member before either removes it, and both process the same job. ZPOPMAX does read-and-remove as one command, so each member goes to exactly one caller.

The command family

CommandBehaviour
ZPOPMAX key [count]Pop up to count highest-scored members
ZPOPMIN key [count]Pop up to count lowest-scored members
BZPOPMAX key [key ...] timeoutBlock until one of the keys has a member, then pop the highest
BZPOPMIN key [key ...] timeoutSame for the lowest
ZMPOP numkeys key ... MIN or MAX [COUNT n]Pop from the first non-empty key (7.0+)
BZMPOP timeout numkeys key ... MIN or MAX [COUNT n]Blocking version (7.0+)

The timeout is in seconds and can be fractional since Redis 6.0; 0 means wait forever. Non-blocking pops on an empty or missing key return an empty array. Complexity is O(log N) per popped member.

Typical uses

  • Priority queue. Score = priority. Workers BZPOPMAX jobs:priority 5 to always take the most urgent job first, for example premium-customer refunds before regular ones.
  • Top-N extraction. ZPOPMAX leaderboard:daily 3 when awarding the day's top three and resetting.
  • Earliest deadline first. Score = due timestamp, ZPOPMIN gives the job that is due soonest.
  • Matchmaking. Pop the closest rating bucket from several queues with ZMPOP.

Gotchas

  • Delayed jobs. ZPOPMIN pops the smallest timestamp even if it is in the future. For "due now" semantics, check the score and put it back, or use a Lua script that pops only when score <= now.
  • At-most-once delivery. Once popped, the member is gone. If the worker crashes before finishing, the job is lost. For reliable processing, move the job to an in-progress set with a timestamp (in a script) or use Redis Streams with consumer groups and acknowledgements.
  • Ties. Members with equal scores pop in lexicographic order (ZPOPMAX takes the lexicographically greatest), so add a tiebreaker into the score if order matters.
  • Cluster. Multi-key BZPOPMAX and ZMPOP need all keys in the same slot.
Two workers sharing a priority queue. Each pop is atomic, so a job is never handed to two workers.
  1. Worker 1 → Redis: BZPOPMAX jobs:priority 5
  2. Worker 2 → Redis: BZPOPMAX jobs:priority 5
  3. Redis → Worker 1: refund:771, score 90
  4. Redis → Worker 2: refund:402, score 40
  5. Worker 1 → Redis: BZPOPMAX again (blocks if empty)

Code examples

Popping from redis-cli

ZADD jobs:priority 40 refund:402 90 refund:771 10 email:55

ZPOPMAX jobs:priority          # highest
ZPOPMIN jobs:priority          # lowest
ZPOPMAX jobs:priority 5        # up to 5 more

# Block up to 2.5 seconds on two queues (checked in order)
BZPOPMAX jobs:urgent jobs:priority 2.5

# Redis 7.0+: pop 2 from the first non-empty queue
ZMPOP 2 jobs:urgent jobs:priority MAX COUNT 2

After three pops the set is empty, so the blocking call times out with nil and ZMPOP also returns nil.

Priority worker loop (Node.js, ioredis)

import Redis from 'ioredis';
// Use a dedicated connection: blocking commands hold it
const redis = new Redis();

async function workLoop() {
  for (;;) {
    const res = await redis.bzpopmax('jobs:priority', 5);
    if (!res) continue; // timed out, loop again
    const [, jobId, score] = res;
    console.log(`Processing ${jobId} (priority ${score})`);
    // await handle(jobId);
  }
}
workLoop();

BZPOPMAX returns [key, member, score]. A short timeout lets the loop check for shutdown signals instead of blocking forever.

Key points

  • ZPOPMAX and ZPOPMIN (5.0+) atomically remove and return extreme members
  • BZPOPMAX/BZPOPMIN block with a timeout in seconds; 0 waits forever
  • ZMPOP and BZMPOP (7.0+) pop from the first non-empty of several keys
  • ZRANGE plus ZREM is racy; the pop commands are not
  • Popped items are gone; use a processing set or Streams for reliable queues

Common follow-up questions

  • How would you build a delayed job queue that pops only jobs that are due?
  • How do you make a sorted-set queue survive worker crashes?
  • When would you choose Redis Streams over a sorted set?
  • Why should blocking commands use a dedicated connection?

Interview tips

  • Explain why the atomic pop matters versus ZRANGE plus ZREM
  • Mention the blocking variants and a real use case like a priority queue
  • Raise the at-most-once problem and offer Streams as the reliable alternative

Concepts covered

ZPOPMAX, ZPOPMIN, BZPOPMAX, ZMPOP, Priority queue

More Redis & Caching questions