TExcelTAD
Home › Redis › Redis Queues

Redis Queues

A job queue decouples the part of your application that asks for work (a web request: "send a welcome email", "resize this photo") from the part that does it (background workers). The request returns immediately, and workers process jobs at their own pace. Redis offers three good building blocks: lists, sorted sets and streams.

A simple list queue

Producers RPUSH jobs to the tail; workers pop from the head. Jobs are usually JSON strings:

redis · try it yourself
RPUSH queue:email "{\"id\":1,\"to\":\"ada@example.com\",\"template\":\"welcome\"}"
RPUSH queue:email "{\"id\":2,\"to\":\"linus@example.com\",\"template\":\"reset\"}"
LLEN queue:email
LPOP queue:email
LLEN queue:email
redis> RPUSH queue:email "{\"id\":1,\"to\":\"ada@example.com\",\"template\":\"welcome\"}"
(integer) 1
redis> RPUSH queue:email "{\"id\":2,\"to\":\"linus@example.com\",\"template\":\"reset\"}"
(integer) 2
redis> LLEN queue:email
(integer) 2
redis> LPOP queue:email
"{\"id\":1,\"to\":\"ada@example.com\",\"template\":\"welcome\"}"
redis> LLEN queue:email
(integer) 1

Real workers use the blocking BLPOP queue:email 5, which waits up to 5 seconds for a job instead of polling in a busy loop.

The weakness: once LPOP returns, the job exists only in the worker's memory. If the worker crashes, the job is gone.

Reliable queue with LMOVE

To survive crashes, a worker atomically moves the job to its own processing list, does the work, and only then removes it:

redis · try it yourself
RPUSH queue:jobs job:1 job:2 job:3
LMOVE queue:jobs processing:worker-a LEFT RIGHT
LMOVE queue:jobs processing:worker-a LEFT RIGHT
LREM processing:worker-a 1 job:1
LRANGE processing:worker-a 0 -1
LRANGE queue:jobs 0 -1
redis> RPUSH queue:jobs job:1 job:2 job:3
(integer) 3
redis> LMOVE queue:jobs processing:worker-a LEFT RIGHT
"job:1"
redis> LMOVE queue:jobs processing:worker-a LEFT RIGHT
"job:2"
redis> LREM processing:worker-a 1 job:1
(integer) 1
redis> LRANGE processing:worker-a 0 -1
1) "job:2"
redis> LRANGE queue:jobs 0 -1
1) "job:3"

Worker A finished job:1 and removed it, but then crashed while working on job:2. A supervisor (or the restarted worker) finds job:2 still in processing:worker-a and pushes it back to the queue:

redis · try it yourself
RPUSH queue:jobs job:3
RPUSH processing:worker-a job:2
LMOVE processing:worker-a queue:jobs RIGHT LEFT
LRANGE queue:jobs 0 -1
redis> RPUSH queue:jobs job:3
(integer) 1
redis> RPUSH processing:worker-a job:2
(integer) 1
redis> LMOVE processing:worker-a queue:jobs RIGHT LEFT
"job:2"
redis> LRANGE queue:jobs 0 -1
1) "job:2"
2) "job:3"

The blocking version, BLMOVE, is what workers call in their main loop.

Delayed jobs with a sorted set

"Send a reminder in 24 hours" or "retry in 30 seconds" needs a scheduled queue. Use a sorted set scored by the time the job is due. A scheduler moves due jobs into the normal queue:

redis · try it yourself
ZADD queue:delayed 1760700300 reminder:7 1760700060 retry:job:42 1760786400 report:weekly
ZRANGE queue:delayed -inf 1760700100 BYSCORE
ZRANGE queue:delayed -inf 1760700400 BYSCORE
ZREM queue:delayed retry:job:42 reminder:7
RPUSH queue:jobs retry:job:42 reminder:7
ZRANGE queue:delayed 0 -1 WITHSCORES
redis> ZADD queue:delayed 1760700300 reminder:7 1760700060 retry:job:42 1760786400 report:weekly
(integer) 3
redis> ZRANGE queue:delayed -inf 1760700100 BYSCORE
1) "retry:job:42"
redis> ZRANGE queue:delayed -inf 1760700400 BYSCORE
1) "retry:job:42"
2) "reminder:7"
redis> ZREM queue:delayed retry:job:42 reminder:7
(integer) 2
redis> RPUSH queue:jobs retry:job:42 reminder:7
(integer) 2
redis> ZRANGE queue:delayed 0 -1 WITHSCORES
1) "report:weekly"
2) "1760786400"

With several schedulers, two could pick the same job. Do the "find due jobs, remove them and push them" step in a Lua script so it is atomic, or check ZREM's return value: only the scheduler whose ZREM returns 1 enqueues the job.

Priority queues

Two simple options:

  • One list per priority and LMPOP (or BLMPOP) with the high-priority list first: it always drains high before low.
  • A sorted set with the priority as score and ZPOPMIN, if priorities are numbers.
redis · try it yourself
RPUSH q:high page-oncall
RPUSH q:low send-newsletter rebuild-sitemap
LMPOP 2 q:high q:low LEFT COUNT 5
LMPOP 2 q:high q:low LEFT COUNT 5
redis> RPUSH q:high page-oncall
(integer) 1
redis> RPUSH q:low send-newsletter rebuild-sitemap
(integer) 2
redis> LMPOP 2 q:high q:low LEFT COUNT 5
1) "q:high"
2) 1) "page-oncall"
redis> LMPOP 2 q:high q:low LEFT COUNT 5
1) "q:low"
2) 1) "send-newsletter"
   2) "rebuild-sitemap"

COUNT 5 takes up to five jobs, but only from one list per call.

Simulating workers

This Python model runs a reliable queue with two workers, one of which crashes mid-job, and a recovery step:

python · try it yourself
from collections import deque

queue = deque(["resize:1", "resize:2", "email:3", "email:4"])
processing = {"w1": deque(), "w2": deque()}
done = []

def lmove(src, dst):
    if src:
        job = src.popleft()
        dst.append(job)
        return job

def work(worker, crash=False):
    job = lmove(queue, processing[worker])
    if job is None:
        return
    if crash:
        print(f"{worker} crashed while running {job}")
        return
    processing[worker].remove(job)      # LREM after success
    done.append(job)
    print(f"{worker} finished {job}")

work("w1")
work("w2", crash=True)
work("w1")
# recovery: push the crashed worker's jobs back to the head of the queue
while processing["w2"]:
    queue.appendleft(processing["w2"].pop())
print("recovered queue:", list(queue))
work("w1")
work("w1")
print("done:", done)
w1 finished resize:1
w2 crashed while running resize:2
w1 finished email:3
recovered queue: ['resize:2', 'email:4']
w1 finished resize:2
w1 finished email:4
done: ['resize:1', 'email:3', 'resize:2', 'email:4']

Lists, sorted sets or streams?

Need Best fit
Simple FIFO, one consumer type list (RPUSH + BLMOVE)
Delayed or scheduled jobs sorted set scored by due time
Many workers, acknowledgements, retries, history stream with consumer groups
Several services must each see every job stream (one consumer group per service)

Mature libraries implement these patterns for you, with retries, dead-letter queues and dashboards: BullMQ (Node.js), RQ, Celery and Dramatiq (Python), Sidekiq (Ruby).

Test yourself

What is the risk of a worker using plain LPOP to take a job?

  1. Jobs come out in the wrong order
  2. If the worker crashes after popping, the job is lost
  3. LPOP is slow
  4. Two workers get the same job

Which structure is best for jobs that must run at a specific future time?

  1. A list
  2. A set
  3. A sorted set scored by the due timestamp
  4. A HyperLogLog

With LMPOP 2 q:high q:low LEFT, when are jobs taken from q:low?

  1. Always first
  2. Alternately with q:high
  3. Only when q:high is empty
  4. Never