Redis Streams & Pub/Sub
"Redis' Pub/Sub exhibits at-most-once message delivery semantics." — Redis documentation, Redis Pub/sub
Summary: Redis gives you three messaging primitives with three different contracts: Pub/Sub (broadcast, nothing stored), lists (a queue that forgets on pop) and Streams (a log with consumer groups, acks and claiming). Focus: Every command and knob you meet in production (PUBLISH/SSUBSCRIBE, BLMOVE, XADD/XREADGROUP/XACK/XAUTOCLAIM, trimming, XINFO), what Laravel's redis queue driver really stores, and where Redis stops being enough compared with RabbitMQ and Kafka. Learning goal: Pick the right Redis primitive for a job, run a stream consumer group that survives crashes, size and trim it, and know the failure modes (failover, eviction, Cluster) that lose messages.
This page is the complete reference for using Redis as a message channel. It covers the three primitives (Pub/Sub, lists as queues, Streams), the Streams command set in depth, what Laravel's built-in redis queue driver and Horizon actually do with lists and sorted sets, Go (go-redis v9) and Laravel 13 code for every mechanism, and how Redis Streams compares with RabbitMQ and Kafka. It deliberately does not re-teach Redis the data store: the event loop, persistence, replication, Sentinel and Cluster basics live in Redis: Data Structures, Commands & Patterns; this page states only what those mean for messages. The general concepts have their own owners and are linked, not repeated: ack semantics in Message Acknowledgment, parking poison messages in Dead Letter Queue, backoff schedules in Retry, Backoff & Delayed Delivery, per-key order in Ordering & Partitioning, worker scaling in Competing Consumers, and the whole Laravel queue architecture in Laravel Queue Internals. The side-by-side decision table for all three brokers is Redis vs RabbitMQ vs Kafka.
Page map
| If you are looking for | Go to |
|---|---|
| The three primitives and their guarantees in one table | Everything in one minute |
| Why Redis has three primitives, and the trade-off | Why three primitives |
| Versions: Pub/Sub, Streams 5.0, XAUTOCLAIM 6.2, sharded Pub/Sub 7.0, Redis 8.x additions | Where it comes from |
| Pub/Sub, sharded Pub/Sub, keyspace notifications | Pub/Sub, Sharded Pub/Sub, Keyspace notifications |
LPUSH/BRPOP, BLMOVE reliable queue | Lists as queues, Reliable list queue |
What queue:work on the redis driver really stores | Laravel's redis queue driver |
XADD, ids, XRANGE, XREAD | Entries and ids, Reading without groups |
Consumer groups, $ vs 0 vs >, PEL, XACK | Consumer groups, PEL and XACK |
Dead consumers: XPENDING, XCLAIM, XAUTOCLAIM, XNACK | Claiming |
MAXLEN, MINID, KEEPREF/DELREF/ACKED, XINFO, lag, IDMP | Trimming, Observability, Idempotent XADD |
| AOF/RDB, failover losing acks, memory, ordering, Cluster, errors | Mechanics |
| Work queue, fan-out, event log, CDC feed, sharding, poison messages | Solving the classic problems |
| Go and Laravel code | Go, Laravel |
| Redis Streams vs RabbitMQ and Kafka | Compared with the others |
| When Redis is the wrong broker | Choosing, When not to use Redis |
| Monolith to distributed system | In architecture |
A crashed consumer recovered by XAUTOCLAIM | Lab |
| Wrong beliefs, cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The three primitives. Each row is unpacked in the primitives section and Streams in depth.
| Primitive | In plain words | Stored? | Delivery | Each message goes to | Use it for |
|---|---|---|---|---|---|
Pub/Sub (PUBLISH/SUBSCRIBE) | A loudspeaker: whoever is connected hears it | No | At-most-once | Every connected subscriber | Cache invalidation, presence, live UI, keyspace notifications |
Sharded Pub/Sub (SPUBLISH/SSUBSCRIBE, 7.0+) | The same loudspeaker, but only inside one Cluster shard | No | At-most-once | Every subscriber of that shard channel | Pub/Sub at Cluster scale |
List (LPUSH + BRPOP) | A pile of tickets; taking one removes it | Until popped | At-most-once (a crash after pop loses it) | Exactly one consumer | Simple job queue where a lost job is acceptable |
List (LPUSH + BLMOVE + LREM) | Take a ticket and clip it to your own board until done | Until removed | At-least-once with your own requeuer | Exactly one consumer | Reliable job queue (Laravel's driver does a variant of this) |
Stream (XADD + XREAD) | A log everyone can read from any position | Until trimmed | Reader decides | Every reader (fan-out) | Event log, replay, time-range reads |
Stream + consumer group (XREADGROUP + XACK) | A log plus a shared cursor and a list of unfinished tickets | Until trimmed | At-least-once (or at-most-once with NOACK) | One consumer per group; every group | Work queue with ack, fan-out to several services |
The stream commands you will use daily.
| Command | What it does | Since |
|---|---|---|
XADD key [MAXLEN ~ n] * f v | Append; returns the id ms-seq | 5.0.0 (MINID, LIMIT, NOMKSTREAM 6.2.0) |
XGROUP CREATE key g $ MKSTREAM | Create a group starting after the current last entry | 5.0.0 |
XREADGROUP GROUP g c COUNT n BLOCK ms STREAMS key > | Get new entries for consumer c, record them in the PEL | 5.0.0 (CLAIM option 8.4) |
XACK key g id | Mark processed; removes from the PEL | 5.0.0 |
XPENDING key g [IDLE ms] - + n | Inspect unacked entries: owner, idle time, delivery count | 5.0.0 |
XAUTOCLAIM key g c min-idle 0-0 | Take over entries idle longer than min-idle | 6.2.0 |
XINFO GROUPS key | last-delivered-id, entries-read, lag, pending | 5.0.0 |
XTRIM key MINID ~ id / MAXLEN ~ n | Cap the stream by age (via id) or by count | 5.0.0 (MINID 6.2.0; KEEPREF/DELREF/ACKED 8.2) |
XNACK key g FAIL IDS 1 id | Release your own entry back to the group now | 8.8.0 |
The three things to do.
| Situation | Do this |
|---|---|
| Signal that may be lost (invalidate a cache) | Pub/Sub, and make every receiver recover on its own (TTL, re-read on reconnect) |
| Work that must not be lost | A stream with a consumer group, XACK after success, an XAUTOCLAIM reaper, idempotent handlers, appendfsync set deliberately, noeviction on that instance |
| Data you cannot lose even on failover, backlog bigger than RAM, long replay | Not Redis: a database outbox plus RabbitMQ quorum queues or Kafka (choosing) |
Why Redis has three messaging primitives
Redis is an in-memory data structure server, and every data structure that can wait for data can carry messages. Pub/Sub came first: a server-side fan-out of whatever is published to connected clients, with no storage at all. Lists became the classic job queue because LPUSH and the blocking pops (BRPOP, later BLMOVE) give you "one item, one worker" for free. Both have hard limits: Pub/Sub forgets, and a list forgets the moment an item is popped. Streams were added to give Redis a real log: entries stay until you trim them, any number of readers can read from any position, and consumer groups add server-side tracking of who has what and what is unfinished.
The fundamental trade-off is the same as everywhere in messaging: the less the server remembers, the cheaper and simpler it is, and the more work moves to your code.
Fire-and-forget (Pub/Sub, BRPOP) | Remembered (Streams + groups, BLMOVE) |
|---|---|
| Nothing to trim, no memory growth | Memory grows until you trim; you must size it |
| A crash or disconnect loses messages | A crash leaves entries pending; you must reclaim them |
| No ack protocol to get wrong | Ack after success, reaper, delivery counter, poison handling |
| Lowest latency, no state per consumer | Small per-entry state in the PEL per group |
| No replay | Replay from any id with XRANGE/XREAD |
The analogy we reuse on this page: a restaurant. Pub/Sub is the dining-room loudspeaker: "table 12, your order is ready" reaches whoever is in the room right now; someone in the washroom misses it forever. A list is a spike of order tickets: a cook pulls the top ticket off and it is gone from the spike; if the cook faints, the ticket is in his pocket. BLMOVE is the cook clipping the ticket onto his own board while cooking, so the manager can see it. A stream with a consumer group is a ticket rail with a carbon copy: every ticket stays on the rail in order; the kitchen (a group) has a marker for "next ticket nobody has taken"; each cook's taken tickets are listed on a whiteboard (the PEL) until he shouts "done" (XACK); a manager walking past sees tickets that have hung too long and hands them to another cook (XAUTOCLAIM). The bar (another group) reads the same rail for drinks with its own marker.
Three common misunderstandings, up front
- "Pub/Sub plus a worker is a queue." Pub/Sub stores nothing, has no ack, and gives every subscriber every message. A restart loses messages; two workers do the work twice.
PUBLISHreturning0is not an error. - "
XACKgives exactly-once." Streams give at-least-once. A crash between doing the work andXACKredelivers the entry; the reaper can also redeliver an entry whose first attempt actually finished. Handlers must be idempotent (inbox pattern). - "Laravel's redis queue uses Redis Streams." It uses a list for ready jobs, a list of notification tokens, and two sorted sets for delayed and reserved jobs, driven by Lua scripts. Streams need your own consumer through the
Redisfacade.
Where it comes from
Redis Pub/Sub predates Streams by years; the Pub/Sub page still points to Streams when you need more: Streams retain entries and can support either delivery model, depending on how consumers acknowledge them. Streams arrived in Redis 5.0: the command table on the Streams page lists XADD, XREADGROUP, XACK, XPENDING, XCLAIM, XINFO and XTRIM with "Since 5.0.0". The Streams page describes the type this way:
"A Redis stream is a data structure that acts like an append-only log" — Redis documentation, Redis Streams
It also explains why the terminology looks like Kafka's: The vocabulary was inspired by Kafka, but the implementation and assignment rules are different.
The later additions, each with the version the command metadata states:
| Version | Addition | Why it matters for messaging |
|---|---|---|
| 6.2.0 | XAUTOCLAIM, XADD ... MINID, LIMIT, NOMKSTREAM; LMOVE/BLMOVE replace RPOPLPUSH/BRPOPLPUSH | One-command reaper; trimming by id (time); clearer reliable list queue |
| 7.0.0 | Sharded Pub/Sub (SPUBLISH, SSUBSCRIBE, SUNSUBSCRIBE); XCLAIM/XAUTOCLAIM delete dangling PEL ids | Pub/Sub that scales in Cluster; trimmed-but-pending entries are cleaned up |
| 8.2.0 | XACKDEL, XDELEX, KEEPREF/DELREF/ACKED on XADD/XTRIM | Trim or delete only what every group has acknowledged |
| 8.4 | XREADGROUP ... CLAIM min-idle-time | Read new entries and reclaim idle ones in one call |
| 8.6.0 | XADD ... IDMP/IDMPAUTO, XCFGSET | Server-side deduplication of producer retries |
| 8.8.0 | XNACK with SILENT/FAIL/FATAL | Give entries back on shutdown without waiting for idle time; mark poison |
Check the Redis version you actually run (and whether your provider or a fork such as Valkey has the 8.x commands) before relying on the last four rows; check the minimum version in the first two rows too.
The primitives, one by one
Each block follows the same order: plain words, the usual wrong belief, the definition, a timeline, real scenarios, what it gives and does not give, and the code.
Pub/Sub Must-know
In plain words: PUBLISH channel msg pushes msg to every client that is subscribed to channel at that instant, and Redis forgets it. Nothing is stored for later.
Common misunderstanding: "If my subscriber reconnects quickly it will catch up." It will not. There is no history to catch up from; anything published while it was away is gone, and PUBLISH told the publisher only how many clients received it.
Definition: SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE (glob patterns such as news.*), PUNSUBSCRIBE and PUBLISH. The reply of PUBLISH is the number of clients that received the message. In RESP2 a subscribed connection can only run (P)SUBSCRIBE/(P)UNSUBSCRIBE, PING and a few others; the docs note that RESP3 permits ordinary commands on a subscribed connection. Pub/Sub ignores database numbers (channel names are independent of the selected database). A client subscribed to a channel and to a matching pattern receives the message twice. Delivery is push: if a subscriber reads slower than the publisher writes, its output buffer grows until client-output-buffer-limit pubsub 32mb 8mb 60 (the redis.conf default) disconnects it.
Publisher Redis Subscriber A Subscriber B
1 PUBLISH orders:new 42 -> 2 clients subscribed -> receives 42 receives 42
2 (B restarts)
3 PUBLISH orders:new 43 -> 1 client subscribed -> receives 43 -- lost forever
4 PUBLISH orders:new 44 -> returns 1
5 SUBSCRIBE again
6 PUBLISH orders:new 45 -> returns 2 -> receives 45 receives 45
-- B never sees 43 or 44; nobody reported an errorReal scenarios: invalidating a per-process in-memory cache on every app node when a product changes (a missed invalidation is repaired by the cache TTL); "user is typing" and presence indicators; pushing live dashboard updates to WebSocket gateways; reacting to key expiry via keyspace notifications.
| Property | Pub/Sub |
|---|---|
| Persistence | None; not in AOF/RDB, not replayable |
| Delivery | At-most-once (Redis docs) |
| Fan-out | Every subscriber gets every message |
| Competing consumers | Impossible; two subscribers both process |
| Backpressure | None; slow subscriber is disconnected at the output-buffer limit |
| Cluster | Classic Pub/Sub is broadcast to every node over the cluster bus; use sharded Pub/Sub at scale |
Fix / how to use it: use it only where a lost message is harmless or self-healing. The Go subscriber with a bounded channel and the Laravel listener are in Go and Laravel. If you need the message after a restart, use a stream.
Sharded Pub/Sub Important
In plain words: in Redis Cluster, SPUBLISH sends a message only to the shard (primary plus replicas) that owns the channel's hash slot, instead of to every node.
Common misunderstanding: "Sharded Pub/Sub makes Pub/Sub durable or reliable." It changes only where the message travels. It is still fire-and-forget.
Definition: Redis 7.0 maps shard channels to hash slots; publishers send to the slot owner. Clients subscribe with SSUBSCRIBE through the slot primary or one of its replicas. The docs give the reason: shard-local propagation reduces cluster-bus traffic compared with cluster-wide broadcast Hash tags work for shard channels exactly as for keys: {tenant-42}:cache-invalidate.
6-node cluster, classic PUBLISH Same cluster, SPUBLISH
1 client -> node A: PUBLISH chan msg client -> owner of slot(chan): SPUBLISH chan msg
2 A forwards msg to B, C, D, E, F over the bus owner forwards to its replicas only
3 every node delivers to its local subscribers subscribers connected to that shard receive it
-- bus traffic grows with nodes x messages -- bus traffic stays inside one shardReal scenarios: per-tenant invalidation channels in a large cluster; chat-room fan-out where each room is a shard channel. Fix: in go-redis, ClusterClient.SSubscribe and SPublish; Laravel's Redis::subscribe uses classic SUBSCRIBE, so call the underlying phpredis ssubscribe through a raw connection if you need it (phpredis declares ssubscribe(array $channels, callable $cb)).
Keyspace notifications Good to know
In plain words: Redis can publish a Pub/Sub message whenever a key is changed, deleted or expires, on channels named __keyspace@0__:mykey and __keyevent@0__:del.
Common misunderstanding: "I can build a reliable delayed-job system on expired events." The docs say expired events are generated on actual deletion, rather than precisely when the TTL reaches zero, with possibly "a significant delay", and like all Pub/Sub, events emitted during disconnection cannot be recovered through Pub/Sub
Definition: disabled by default (notify-keyspace-events "" in redis.conf); enable with flags, for example CONFIG SET notify-keyspace-events Ex for expired key-event notifications or KEA for everything. In Cluster, a Cluster listener must subscribe to every relevant node to observe its local key events Streams generate events too (xadd, xdel, xtrim, xgroup-*).
Client Redis (notify-keyspace-events Ex) Listener
1 SET hold:seat:12 1 EX 600
2 ... 600 s pass, nobody reads the key
3 active expiry cycle finds the key later
4 deletes it, PUBLISH __keyevent@0__:expired -> receives "hold:seat:12"
-- the event comes when Redis deletes the key, possibly well after 600 s,
-- and only to listeners connected at that momentReal scenarios: cache-warming triggers, debugging which code touches a key, best-effort "session ended" signals. For timed work use a sorted-set scheduler or a stream (retry and delayed delivery).
Lists as queues: LPUSH and BRPOP Must-know
In plain words: producers push to one end of a list and workers block-pop from the other end. Each item goes to exactly one worker, and popping removes it.
Common misunderstanding: "Redis lists are a reliable queue because the data is persisted." The list is persisted; the item you popped is not anywhere any more. The LMOVE page says it plainly: a worker or network failure after removal can lose the item before processing
Definition: LPUSH queue job (or RPUSH) to produce; BRPOP queue timeout (or BLPOP) to consume, blocking up to timeout seconds (0 = forever). Several blocked clients on one list are each served a different item. A list has no per-item metadata: no delivery count, no timestamp, no ack.
Producer Redis list "jobs" Worker W1
1 LPUSH jobs J1 [J1]
2 BRPOP jobs 5 -> J1 (removed from Redis)
3 [] starts sending the e-mail ...
4 process killed (OOM, deploy, SIGKILL)
-- J1 exists nowhere: not in Redis, not in W1. No error anywhere.Real scenarios: thumbnail generation that a nightly sweep would redo anyway; metrics or log shipping where a lost batch is acceptable; the simplest "background job" in a small app.
Fix: if a lost job matters, use BLMOVE with a processing list (next block) or a stream with a consumer group.
Reliable list queue: BLMOVE and a processing list Important
In plain words: instead of popping a job into the void, the worker atomically moves it to its own "processing" list, and deletes it from there only after the job succeeded.
Common misunderstanding: "BLMOVE gives me redelivery." It gives you a place where unfinished jobs stay visible. Someone still has to notice a stale job and push it back; the docs: an application sweeper must detect abandoned processing items and put them back on the ready queue The list does not tell you how long an item has been there; you store that yourself.
Definition: LMOVE/BLMOVE source destination LEFT|RIGHT LEFT|RIGHT [timeout] (6.2.0) pops from one end of source and pushes to one end of destination atomically. It replaces BRPOPLPUSH when used with RIGHT LEFT After success the worker calls LREM processing 1 job. In Redis Cluster both keys must hash to the same slot (use a hash tag such as {mail}:queue and {mail}:processing:w1), or the command fails with CROSSSLOT.
Producer "jobs" "jobs:processing:w1" Worker W1 Requeuer
1 LPUSH jobs J1 [J1] []
2 [] [J1] BLMOVE jobs ... RIGHT LEFT 5 -> J1
3 crashes mid-job
4 (restart) LMOVE processing -> jobs
5 [J1] [] (or: a sweeper does it)
6 [J1] BLMOVE -> J1, sends e-mail
7 [] LREM jobs:processing:w1 1 J1
-- J1 was delivered twice (step 2 and 6): the handler must be idempotentReal scenarios: e-mail and SMS sending, webhook delivery, any job queue built directly on lists in Go or Node; it is also the idea behind Laravel's :reserved sorted set.
| Need | BRPOP | BLMOVE + LREM | Stream + group |
|---|---|---|---|
| Job survives a worker crash | No | Yes (in processing list) | Yes (in PEL) |
| Know how long a job has been in progress | No | Only if you store it | Yes (idle in XPENDING) |
| Delivery counter for poison detection | No | Only if you store it | Yes (built in) |
| Find stuck jobs of a dead worker | No | Scan each worker's list | XAUTOCLAIM over the whole group |
| Fan-out to several independent consumers | No | No (copy to N lists) | Yes (one group each) |
Fix: Go worker with startup requeue in Go; Laravel command in Laravel.
What Laravel's redis queue driver actually does Must-know
In plain words: php artisan queue:work redis uses four keys per queue: a list of ready jobs, a list of notification tokens, a sorted set of delayed jobs and a sorted set of reserved (in-progress) jobs. Every operation is a Lua script, so each step is atomic. No streams are involved.
Common misunderstanding: "A job is removed from Redis when a worker takes it." It is moved into queues:<name>:reserved, scored by "now + retry_after". If the worker dies, the job is not lost: the next pop by any worker migrates expired reserved jobs back onto the list. That is also why a job that runs longer than retry_after gets processed twice.
Definition (from Illuminate/Queue/LuaScripts.php and RedisQueue.php, Laravel 13.x):
| Operation | Lua script / call | Keys touched |
|---|---|---|
dispatch($job) | push: rpush payload, rpush a 1 token | queues:default, queues:default:notify |
dispatch($job)->delay(60) | later: zadd with score = available-at timestamp | queues:default:delayed |
Worker pop | first migrateExpiredJobs for :delayed and (if retry_after is not null) :reserved, then pop: lpop job, increment attempts, zadd to :reserved with score = now + retry_after, lpop one token | all four |
block_for set | if the list was empty, blpop on :notify up to block_for seconds, then try pop once more | queues:default:notify |
| Job succeeds | deleteReserved: zrem from :reserved | queues:default:reserved |
| Job throws, attempts left | release: zrem from :reserved, zadd to :delayed with the backoff time | :reserved, :delayed |
Queue::size() | llen + zcard + zcard | list + both sorted sets |
On Redis Cluster, getQueueRedisKey() wraps the queue name in a hash tag (queues:{default}) unless the name already has one, so all four keys share a slot; the Laravel docs say that on Cluster queue names need hash tags. The connection options are retry_after (default 90 in the shipped config), block_for (default null; zero waits indefinitely and can postpone signal handling until a job arrives) and after_commit.
Worker A (queue:work, retry_after=90) Redis Worker B
1 pop: lpop queues:default -> J (attempts 1) :reserved = {J: now+90}
2 handle() ... hangs on a slow API
3 t = now+91: J's score is in the past
4 pop: migrateExpiredJobs
5 :reserved -> queues:default (J, attempts 1)
6 lpop J (attempts 2), runs it
7 handle() finally returns, deleteReserved
-- J ran twice. Laravel docs: keep --timeout several seconds below
-- retry_after, so a frozen worker is killed before its job is retriedReal scenarios: every Laravel app on the redis driver; the "job ran twice" incident after someone raised --timeout above retry_after; Horizon dashboards showing "pending", "reserved" and "delayed" counts, which are exactly these keys. The full architecture (failed jobs, batches, uniqueness) is in Laravel Queue Internals.
Fix: keep retry_after above the longest job, --timeout a few seconds below it, set block_for to a few seconds (not 0), turn on after_commit, and make jobs idempotent. The config excerpt is in Laravel.
Streams in depth
A stream is one key holding an append-only sequence of entries; each entry is a small map of field-value pairs with a unique, increasing id. Internally it is a radix tree of "macro nodes", each packing many entries (the redis.conf knobs stream-node-max-bytes 4096 and stream-node-max-entries 100 bound one node). Reading never removes anything; consumer groups add a cursor and a pending list per group on top of the same entries.
Entries, ids and XADD Must-know
In plain words: XADD orders * type placed id 42 appends an entry and returns its id, such as 1700000000123-0: the server's millisecond clock plus a sequence number.
Common misunderstanding: "The id is a wall-clock timestamp I can trust across servers." It is the local clock of the Redis primary, forced monotonic: Redis reuses the previous time component when the clock moves backward, keeping IDs increasing It is good for ranges and age-based trimming, not as a business timestamp; put your own occurred_at field in the entry.
Definition: ids have the form <millisecondsTime>-<sequenceNumber>; * lets Redis generate one. An explicit id must be greater than the last one, otherwise: ERR The ID specified in XADD is equal or smaller than the target stream top item. Full syntax (8.6):
XADD key [NOMKSTREAM] [KEEPREF | DELREF | ACKED]
[IDMPAUTO producer-id | IDMP producer-id idempotent-id]
[<MAXLEN | MINID> [= | ~] threshold [LIMIT count]] <* | id>
field value [field value ...]NOMKSTREAM (6.2.0) refuses to create a missing stream; MAXLEN/MINID trim in the same call (Trimming); IDMP deduplicates producer retries (Idempotent XADD). Complexity is constant work for an append, plus work proportional to removed entries during trimming XADD is flagged denyoom: when maxmemory is reached under noeviction, it fails with OOM command not allowed when used memory > 'maxmemory'.
Producer P1 Redis stream "orders"
1 XADD orders * type placed id 42 -> 1700000000123-0
2 XADD orders * type paid id 42 -> 1700000000123-1 (same ms: sequence +1)
3 (primary clock jumps back 2 s)
4 XADD orders * type shipped id 42 -> 1700000000123-2 (previous time reused)
5 XADD orders 5-0 x 1 -> ERR The ID specified in XADD is equal or smaller than the target stream top itemReal scenarios: an order-events log per bounded context; IoT readings appended per device; audit trails kept for a few days; a notification feed per user (one stream per user, small MAXLEN).
Reading without groups: XRANGE, XREVRANGE, XREAD Important
In plain words: XRANGE reads a slice by id range (time range, effectively); XREAD reads entries after an id you remember and can block for new ones. Every reader sees every entry, and Redis remembers nothing about readers.
Common misunderstanding: "XREAD BLOCK ... $ in a loop is a durable subscription." Each call with $ means "only entries added after this call starts", so entries added between two calls are skipped. Pass the last id you received to the next call; only use $ for the very first call.
Definition: XRANGE key start end [COUNT n] (inclusive; - and + are the smallest and greatest possible ids; an exclusive start is written with (); XREVRANGE key end start; XREAD [COUNT n] [BLOCK ms] STREAMS key [key ...] id [id ...]. The Streams page contrasts the consumption models: with XREAD independent XREAD callers can each receive the same entries; blocking list consumers divide the items
Reader R (no group) Stream
1 XREAD BLOCK 5000 STREAMS orders $ (waits) entries: ... 100-0
2 <- 101-0 arrives, R gets 101-0
3 R processes 101-0 for 2 s 102-0, 103-0 added meanwhile
4 WRONG: XREAD BLOCK 5000 STREAMS orders $ -> waits for 104-0; 102-0 and 103-0 skipped
4' RIGHT: XREAD BLOCK 5000 STREAMS orders 101-0 -> returns 102-0, 103-0 immediatelyReal scenarios: a projector that rebuilds a read model by replaying XRANGE orders - + in pages; a "tail -f" debugging tool; a WebSocket gateway that fans out every entry to connected browsers and stores its last id per browser; a time-window query ("entries between 10:00 and 10:05") using ids built from timestamps.
Consumer groups: XGROUP, XREADGROUP and $ vs 0 vs > Must-know
In plain words: a consumer group is a named cursor on a stream plus a list of entries handed out but not yet acknowledged. Consumers in the same group share the work; different groups each get every entry.
Common misunderstanding: "Each consumer in a group gets its own partition, so order per key is kept." Redis assigns new entries to whichever consumer asks first. The docs: consumer readiness determines assignment rather than partition ownership Entries about the same order can be processed in parallel by two consumers, out of order.
Definition: XGROUP CREATE key group <id | $> [MKSTREAM] [ENTRIESREAD n] creates the group with last-delivered-id set to the id you give. XREADGROUP GROUP group consumer [COUNT n] [BLOCK ms] [CLAIM min-idle] [NOACK] STREAMS key id reads. The special ids:
| Id | Where | Meaning |
|---|---|---|
$ | XGROUP CREATE, XGROUP SETID, XREAD | The current last entry: start with new entries only |
0 (or 0-0) | XGROUP CREATE | Start from the beginning: the group will receive the existing history |
0 | XREADGROUP | Not "new": return this consumer's own pending entries (its PEL), for recovery after a restart; BLOCK, NOACK and CLAIM are ignored |
> | XREADGROUP only | Entries never delivered to anyone in this group; advances last-delivered-id |
* | XADD only | Generate the id |
- / + | XRANGE, XPENDING | Smallest / greatest possible id |
Group guarantees, in the docs' words: new entries are assigned once within a group; retries and claims can still repeat processing; consumers are identified by name, so the server retains group state across client reconnects. Consumers are created implicitly by the first XREADGROUP (or XGROUP CREATECONSUMER, 6.2.0) and removed only by XGROUP DELCONSUMER; the group by XGROUP DESTROY. XGROUP SETID moves the cursor (rewind for replay, or skip ahead). Reading a missing group fails with NOGROUP No such key 'orders' or consumer group 'billing' in XREADGROUP with GROUP option; creating an existing one fails with BUSYGROUP Consumer Group name already exists, which start-up code treats as success.
Consumer C1 (group billing) Redis Consumer C2
1 XGROUP CREATE orders billing $ MKSTREAM last-delivered-id = 0-0 (empty stream)
2 XADD x3 -> 1-0, 2-0, 3-0
3 XREADGROUP ... COUNT 2 STREAMS orders > -> 1-0, 2-0 ; PEL: 1-0 C1, 2-0 C1
4 XREADGROUP ... STREAMS orders > -> 3-0 ; PEL += 3-0 C2
5 process 1-0, XACK orders billing 1-0 PEL: 2-0 C1, 3-0 C2
6 (C1 restarts with the same name)
7 XREADGROUP ... STREAMS orders 0 -> 2-0 (its own pending entry)
8 process 2-0, XACK PEL: 3-0 C2
9 XREADGROUP ... STREAMS orders 0 -> empty: switch to >Real scenarios: a billing group and an email group both reading orders (fan-out); ten billing consumers sharing load; a new analytics group created with 0 to backfill the whole retained history; XGROUP SETID billing 1700000000000-0 to reprocess after a bug fix.
The PEL, XACK and the delivery counter Must-know
In plain words: every entry handed out by XREADGROUP ... > is written in the group's Pending Entries List with its owner, delivery time and a delivery counter. XACK removes it. Whatever stays in the PEL is your unfinished work.
Common misunderstanding: "XACK deletes the entry from the stream." It removes the id from this group's PEL only; the entry stays in the stream for other groups and for replay until it is trimmed. XACKDEL (8.2) acknowledges and deletes in one step.
Definition: the XREADGROUP page: the PEL records which entries were delivered but remain unacknowledged XACK key group id [id ...] returns how many ids were actually removed (0 for an id already acked). The delivery counter increases on a successful claim or a reread of pending history NOACK on XREADGROUP skips the PEL (acknowledged upon receipt), turning the group into at-most-once.
Consumer C1 PEL of group billing
1 XREADGROUP ... > -> 7-0 7-0 | C1 | idle 0 | deliveries 1
2 charge card OK
3 -- crash before XACK --
4 (restart) XREADGROUP ... 0 -> 7-0 7-0 | C1 | idle 0 | deliveries 2
5 charge card AGAIN unless the handler checks an idempotency key
6 XACK orders billing 7-0 -> (integer) 1 (empty)
7 XACK orders billing 7-0 -> (integer) 0 -- already acked: harmlessReal scenarios: payment capture, where step 5 must be guarded by the payment provider's idempotency key or a dedup table; a PEL growing for hours because a consumer swallows exceptions without XACK and without parking. The ack timing rules (ack after side effects, never before) are owned by Message Acknowledgment.
Recovering from dead consumers: XPENDING, XCLAIM, XAUTOCLAIM, XNACK Must-know
In plain words: if a consumer dies for good, its pending entries sit in the PEL forever. Another process must look for entries idle too long and take them over. Redis never does this on its own.
Common misunderstanding: "Redis redelivers unacked messages after a timeout, like SQS visibility or RabbitMQ on channel close." It does not. The docs: recovery requires an explicit claim request; elapsed time alone does not move ownership
Definition:
| Command | Since | What it does |
|---|---|---|
XPENDING key group | 5.0.0 | Summary: count, smallest id, greatest id, pending per consumer. read-only inspection |
XPENDING key group [IDLE ms] start end count [consumer] | 5.0.0 (IDLE 6.2) | Per entry: id, owner, ms since last delivery, delivery count |
XCLAIM key group consumer min-idle id ... [JUSTID] [FORCE] [RETRYCOUNT n] [IDLE ms] | 5.0.0 | Take specific ids if idle at least min-idle; resets idle; increments the counter unless JUSTID |
XAUTOCLAIM key group consumer min-idle start [COUNT n] [JUSTID] | 6.2.0 | Scan the PEL from start, claim idle entries, return a cursor (0-0 = scanned all), the entries, and ids deleted because they were no longer in the stream (7.0+) |
XREADGROUP ... CLAIM min-idle ... > | 8.4 | Claim idle entries first, then read new ones, in one call |
XNACK key group SILENT|FAIL|FATAL IDS n id ... | 8.8.0 | Give your own entries back now; SILENT decrements the counter, FAIL keeps it, FATAL sets it to the maximum "for dead letter processing" |
XGROUP DELCONSUMER key group consumer | 5.0.0 | Remove a consumer; the docs warn its pending messages "will become unclaimable after it was deleted", so claim them first |
XCLAIM with min-idle is a compare-and-set: because claiming resets idle time, competing claimers with a positive minimum idle threshold cannot both win. Since 7.0, if a pending id was trimmed or XDELeted, XCLAIM/XAUTOCLAIM do not return it and delete it from the PEL.
C1 (dies) PEL (group billing) Reaper R (every 15 s)
1 reads 7-0, 8-0 7-0 C1 d=1, 8-0 C1 d=1
2 -- killed --
3 XAUTOCLAIM orders billing R 60000 0-0 COUNT 50
4 (idle 20 s) -> "0-0", [], [] (too young)
5 (idle 65 s) XAUTOCLAIM ... -> "0-0", [7-0, 8-0], []
6 7-0 R d=2, 8-0 R d=2 R processes, XACK 7-0
7 8-0 R d=2 (handler failed) next rounds: d=3, 4, 5 ...
8 d > 5: XADD orders:dead ..., XACK 8-0Real scenarios: a Kubernetes pod OOM-killed with 10 entries in flight; scale-down that removes consumer names forever (claim, then XGROUP DELCONSUMER); poison messages that crash every consumer (counter grows, park them in a dead stream, see Dead Letter Queue); graceful shutdown on 8.8+ with XNACK SILENT so others take the work at once.
Fix: the Go reaper (reaper.go) and the Laravel reports:reap command (Laravel) implement exactly the timeline above. Choose min-idle above your slowest normal processing time, or you will steal entries that are still being worked on.
Trimming and deleting: MAXLEN, MINID, XDEL, KEEPREF/DELREF/ACKED Important
In plain words: a stream grows until you trim it. You cap it by count (MAXLEN) or by id, which means by age (MINID). Redis has no background retention policy; trimming happens only when a command asks for it.
Common misunderstanding: "Trimming is safe because consumers have acked." By default (KEEPREF) trimming looks at neither the PELs nor last-delivered-id: a slow group can lose entries it has not read yet, and pending entries can be trimmed under a consumer's feet (they then become dangling ids that XAUTOCLAIM cleans up).
Definition: XTRIM key <MAXLEN | MINID> [= | ~] threshold [LIMIT count] [KEEPREF | DELREF | ACKED], or the same options on XADD. MINID (6.2.0) removes entries below the chosen ID; since ids start with milliseconds, MINID ~ <now - 72 h in ms>-0 is time-based retention you run yourself. ~ is a cheaper whole-node trim that may retain more than the target: Redis removes only whole macro nodes. LIMIT caps the work per call (default 100 times the macro-node entry capacity). Since 8.2: KEEPREF (default) keeps PEL references, DELREF removes them from all groups, ACKED requires acknowledgment by every group before removal. XDEL key id ... deletes single entries (GDPR erasure); XDELEX and XACKDEL (8.2) take the same three modes. A stream is not deleted when it becomes empty, because group state must survive.
Producer (XADD ... MAXLEN ~ 1000) Stream Group "analytics" (slow, last-delivered 200-0)
1 XADD -> 1500-0 entries 400-0 .. 1500-0 kept (~1100)
-- entries 201-0 .. 399-0 were trimmed before analytics read them: silently skipped
2 with ACKED (8.2+): XTRIM orders MAXLEN ~ 1000 ACKED
trims only entries every group has acked
-- analytics keeps its unread entries; memory grows instead: alert on it| Strategy | Command | Good for | Risk |
|---|---|---|---|
| By count on every write | XADD ... MAXLEN ~ 100000 * | Bounded memory, work queues | Slow group loses unread entries |
| By age, periodic | XTRIM key MINID ~ <ms>-0 from a scheduler | "Keep 3 days" event logs | Memory unbounded under a burst |
| Only what all groups acked (8.2+) | XTRIM key MAXLEN ~ n ACKED | Fan-out where no group may miss data | A dead group blocks trimming forever |
| Archive then trim | XRANGE to object storage or a DB, then MINID | Long history | Two systems to operate |
Observability: XINFO and lag Important
In plain words: XINFO tells you how long the stream is, which groups exist, how far behind each group is, and how long each consumer has been idle.
Common misunderstanding: "Pending count is my backlog." Pending entries were already handed out. The backlog not yet delivered is the group's lag; the full picture is lag + pending.
Definition: XINFO STREAM key [FULL [COUNT n]] (length, first and last entry, entries-added, groups); XINFO GROUPS key gives per group consumers, pending, last-delivered-id, entries-read (logical delivery progress) and lag (undelivered entries, or NULL if Redis cannot determine the count). Lag becomes NULL after XGROUP CREATE/SETID at an arbitrary id or when entries between last-delivered-id and the stream's end were deleted or trimmed. XINFO CONSUMERS key group gives per consumer pending, idle (since last attempted interaction) and inactive (since last successful read or claim).
| Metric | Source | Alert when |
|---|---|---|
| Group lag | XINFO GROUPS lag | Grows for minutes: add consumers or fix a slow handler |
| Pending count | XPENDING summary / XINFO GROUPS pending | Grows while lag is flat: consumers fail without ack |
| Oldest pending idle | XPENDING key g IDLE ms - + 1 | Above min-idle × 2: the reaper is not running |
| Max delivery count | XPENDING extended | Above your threshold: poison messages |
| Consumer inactive | XINFO CONSUMERS inactive | Hours: a dead name to claim and delete |
| Stream length and memory | XLEN, MEMORY USAGE key | Near the budget you sized |
Idempotent production: XADD IDMP (Redis 8.6) Good to know
In plain words: a producer that retries XADD after a timeout may append the same event twice. With IDMP producer-id idempotent-id, Redis remembers the pair and returns the original entry id for the retry instead of appending again.
Common misunderstanding: "IDMP makes consumers exactly-once." It removes duplicates on the way in. Consumers still see redeliveries after crashes and still need idempotent handlers. The docs call it producer-side deduplication.
Definition: IDMP reuses the original entry ID while the producer/token pair is still in the deduplication window. IDMPAUTO producer-id derives the id automatically. XCFGSET key IDMP-DURATION s IDMP-MAXSIZE n bounds how long and how many ids are remembered. go-redis v9.18 exposes XAddArgs.ProducerID, IdempotentID and IdempotentAuto; the outbox relay in Solving uses the outbox row id as the idempotent id.
Relay Redis 8.6
1 XADD events IDMP relay 981 * ... -> 1700-0 (new)
2 network timeout, relay retries
3 XADD events IDMP relay 981 * ... -> 1700-0 (same id, nothing appended)Operational limits: keep the producer ID stable across restarts and reuse the message token on retries. IDMPAUTO hashes message content, so distinct events with identical payloads need explicit IDs instead. Deduplication lasts only within its time and capacity bounds. The XCFGSET reference says calling it clears existing IDMP maps; do not reset configuration on every startup. The Redis 8.6 limitations page warns about IDMP with appendonly yes and aof-use-rdb-preamble no. Check the release notes for the exact deployed patch before using that combination; this is not a claim that every later patch retains the defect.
Per-primitive and per-broker behaviour
Guarantee matrix of the Redis primitives.
| Guarantee | Pub/Sub | List + BRPOP | List + BLMOVE | Stream + XREAD | Stream + group |
|---|---|---|---|---|---|
| Survives consumer restart | No | No (popped item lost) | Yes | Yes (reader keeps its id) | Yes (PEL) |
| Survives Redis restart | No | With AOF/RDB | With AOF/RDB | With AOF/RDB | With AOF/RDB, group state included |
| Survives failover | No | Async replication: recent writes may be lost | Same | Same | Same, plus acks and claims may be lost |
| Competing consumers | No | Yes | Yes | No (all readers see all) | Yes |
| Fan-out | Yes | No | No | Yes | Yes, one group per subscriber service |
| Replay | No | No | No | Yes | Yes (XGROUP SETID, new group at 0) |
| Delivery counter | No | No | No | No | Yes |
| Per-key order with parallel consumers | n/a | No | No | Single reader only | No (shard by key across streams) |
What each product really does for the same job.
| Concern | Redis Streams | RabbitMQ | Kafka |
|---|---|---|---|
| Unit of storage | One key in RAM (persisted by AOF/RDB) | Queue; quorum queues replicate with Raft | Partitioned, replicated log on disk |
| Unacked tracking | PEL per group | Per delivery, per channel | Committed offset per partition |
| Redelivery of a dead consumer's work | You run XAUTOCLAIM | Automatic: unacked deliveries are requeued when the channel or connection closes | Rebalance; the new owner restarts from the last committed offset |
| Dead-lettering | Build it (dead stream) | Dead-letter exchange | Build it (DLQ topic) |
| Retention by time | Only when you run MINID | Message and queue TTL | retention.ms (default 7 days) |
| Ordering at scale | Per stream; shard keys yourself | Per queue; consistent-hash exchange | Per partition, by key |
The two other deep dives are RabbitMQ in Depth and Kafka in Depth. NATS JetStream, Pulsar and Amazon SQS solve the same problems with their own primitives (ack-wait redelivery, per-subscription cursors, visibility timeouts); they are surveyed in Other Brokers and not compared here line by line.
Mechanics
Durability: AOF, RDB and what a crash loses Must-know
A stream, a list and a consumer group are ordinary Redis data, so they are exactly as durable as your persistence settings; Pub/Sub messages are never persisted. The Streams page: group metadata is included in persistence and replication, and message durability requires an appropriate AOF fsync policy. The persistence page lists the choices: appendfsync always ("Very very slow, very safe"), appendfsync everysec (the default; "you may lose 1 second of data if there is a disaster"), appendfsync no. RDB snapshots alone lose everything since the last save. Note that redis.conf ships with appendonly no, and many managed offerings configure persistence differently; check yours. Details of AOF rewrite and RDB forking are in Redis: persistence and the general theory in Durability, WAL & Crash Recovery.
Producer Redis primary (appendonly yes, appendfsync everysec)
1 XADD orders * ... -> 1700-0 (reply sent; AOF write buffered)
2 XADD orders * ... -> 1700-1
3 -- power loss 0.6 s later, before the background fsync --
4 restart: AOF replayed up to the last fsync -> 1700-0 and 1700-1 may both be missing
-- the producer got an ID; retain source records and reconcile downstream completion to recover thisReplication and failover: losing entries and acks Must-know
Replication is asynchronous: replication lag can leave the promoted replica without recent entries or group updates WAIT numreplicas timeout reduces the window, WAIT lowers the risk but Sentinel and Cluster failover still cannot promise preservation of every acknowledged write. The Cluster specification says the same for all writes: a partition can expose an acknowledged-write loss window For messaging this has three distinct effects: a lost XADD (message gone), a lost XACK (message redelivered: harmless with idempotent handlers), and a lost XGROUP CREATE/SETID or claim (cursor moves back: redelivery). See Redis: replication and Replication & Failover.
Consumer C1 Primary P Replica R
1 XADD -> 9-0 (replicates 9-0)
2 XREADGROUP > -> 9-0 PEL: 9-0 C1 (replicates PEL)
3 process 9-0, XACK 9-0 PEL: empty
4 -- P dies before sending XACK --
5 promoted; PEL still has 9-0 C1
6 (reconnects to R) XREADGROUP ... 0 -> 9-0 again
-- duplicate processing after failover: design for itMemory sizing Important
Everything lives in RAM, so a stuck consumer is a capacity incident, not just lag. Size by measurement, not by guess: append representative entries, then MEMORY USAGE orders SAMPLES 0 divided by XLEN orders gives bytes per entry for your payloads. Then:
budget = bytes_per_entry x (peak_rate_per_s x worst_outage_s you want to absorb) x (1 + safety)
example, with an assumed 250 B/entry measured on your data:
2,000 entries/s x 4 h (14,400 s) = 28.8 M entries x 250 B = 7.2 GB -> too big for a shared cache node
2,000 entries/s x 30 min = 3.6 M entries x 250 B = 0.9 GB -> MAXLEN ~ 4000000 is a sane capRules that follow from the docs: keep payloads small (an id and a type; claim-check large bodies, see Message Design); prefer ~ trimming (whole macro nodes are freed at once, per XTRIM's complexity note); the PEL costs memory per pending entry per group; and run messaging on an instance with maxmemory-policy noeviction. Under allkeys-lru or allkeys-lfu Redis may evict a whole stream or queue key like any cache key; with noeviction "keys are not evicted but the server will return an error" on writes, which your producer can see and handle. Eviction policies are explained in Redis: eviction.
Ordering Must-know
One stream is totally ordered by id. The Streams page summarises the consequences: one serial consumer preserves processing order; several streams permit parallelism, while several consumers on one stream can finish out of order Claiming also reorders: a reclaimed entry is processed after newer ones. A list queue has the same shape (one list, many workers = no per-key order). The general treatment of per-key ordering and head-of-line blocking is in Ordering & Partitioning; the Redis recipe is shard by key across streams.
Redis Cluster and streams Important
A key lives in exactly one of 16384 hash slots, so one stream lives on one primary: Redis does not split a stream key across primaries Throughput of one stream is bounded by one node; to scale, use several stream keys spread across slots. Multi-key commands (XREAD STREAMS a b, BLMOVE src dst, a Lua script touching a stream and a list) require all keys in one slot, otherwise CROSSSLOT Keys in request don't hash to the same slot; use hash tags ({orders}:events, {orders}:dead) when they must be together, and deliberately different tags when they must spread. There is no atomicity across streams on different slots: "append to orders and payments atomically" is impossible in Cluster. Laravel's queue driver puts each queue's four keys under one hash tag for this reason, and Horizon does not support Cluster at all (per Horizon requirements). Slots, MOVED/ASK and resharding: Redis: Cluster.
Blocking reads under the hood Good to know
Blocked clients (BRPOP, BLMOVE, XREAD BLOCK, XREADGROUP BLOCK) are kept in a table from key to waiting clients. When XADD runs it calls signalKeyAsReady(), and ready keys are served during event-loop processing, so the producer's reply and the consumers' new data leave in the same event-loop cycle. The docs call this model push-based with predictable latency, and report 99.9% of messages processed within 2 ms in their (old-hardware) test. Two practical consequences: a blocked connection is a connection your pool cannot reuse (give consumers their own connection or a client read timeout longer than BLOCK); and in go-redis a block timeout returns redis.Nil, not an empty slice.
Error replies you will catch
| Error (verbatim prefix) | When | What to do |
|---|---|---|
BUSYGROUP Consumer Group name already exists | XGROUP CREATE on an existing group | Treat as success at start-up |
NOGROUP No such key '...' or consumer group '...' | XREADGROUP/XCLAIM before the group exists, or after the key was deleted | Create with MKSTREAM; alert if a stream disappeared (eviction, DEL) |
ERR The ID specified in XADD is equal or smaller than the target stream top item | Explicit id not increasing | Use *, or fix the id source |
ERR The ID specified in XADD must be greater than 0-0 | XADD key 0-0 | Use * or a real id |
OOM command not allowed when used memory > 'maxmemory'. | XADD/LPUSH under noeviction at the limit | Back off the producer, trim, add memory; never switch to an evicting policy |
CROSSSLOT Keys in request don't hash to the same slot | Multi-key command across slots in Cluster | Hash tags, or one key per call |
MOVED / ASK | Cluster redirection | Cluster-aware client (go-redis ClusterClient, phpredis RedisCluster) |
READONLY You can't write against a read only replica. | Writing to a replica after failover with a stale address | Reconnect via Sentinel/Cluster discovery |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Work must survive worker crashes | Stream + group + reaper | XREADGROUP >, XACK, XAUTOCLAIM | Built-in PEL, counters | You run the reaper; idempotent handlers |
| Several services need every event | One group per service | XGROUP CREATE orders <service> $ | Independent cursors, no copies | Trimming must respect the slowest group |
| Monolith needs an event log without losing events | DB outbox + relay into a stream | Outbox row in the same transaction; relay XADD | DB stays the truth; replayable feed | Relay to operate; duplicates on relay crash |
| Feed other systems with row changes | Lightweight CDC | Outbox or triggers to a stream; Debezium for real CDC | Cheap, no Kafka | Not log-based; misses writes that bypass the app |
| Per-key order with more than one consumer | Shard by key across N streams | hash(key) % N, one consumer per stream | Order per key, parallel overall | Rebalancing N is manual |
| One message keeps failing | Delivery-count parking | XPENDING count > N → dead stream + XACK | Queue keeps moving | Someone must look at the dead stream |
| A lost signal is fine | Pub/Sub | PUBLISH / SUBSCRIBE | Zero storage | At-most-once |
Work queue with ack and crash recovery
The Go "after" program in Go is the reference implementation: ensureGroup (tolerates BUSYGROUP), consume (drains its own PEL with id 0, then reads >), reap (XAUTOCLAIM loop with a cursor until 0-0), settle (parks after five deliveries), and report (XPENDING, XINFO GROUPS, XINFO CONSUMERS). The Laravel equivalent is three Artisan commands (Laravel). Retry with backoff on top of this (instead of immediate re-claim) is in Retry, Backoff & Delayed Delivery.
Fan-out to several services via consumer groups
Create one group per consuming service on the same stream: billing, email, analytics. Each group has its own last-delivered-id and PEL; within a group, instances compete. A new service is added with XGROUP CREATE orders search 0 to backfill whatever is still retained, or $ to start fresh. Trim with ACKED (8.2+) if no group may miss an entry, and alert on the slowest group's lag, because it decides your memory. This is the Redis form of the publish-subscribe channel; with RabbitMQ you would bind one queue per service to a fanout or topic exchange (routing topologies).
Event log for a monolith: outbox into a stream
Writing to the database and then XADDing is a dual write: a crash in between loses the event, and the reverse order publishes events for rolled-back transactions. Write the event into an outbox table in the same transaction, and let a relay copy it to the stream (Outbox pattern):
-- PostgreSQL; the same shape works in MySQL with BIGINT AUTO_INCREMENT and DATETIME(6)
CREATE TABLE outbox (
id BIGSERIAL PRIMARY KEY,
aggregate_id TEXT NOT NULL,
type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
BEGIN;
UPDATE orders SET status = 'paid' WHERE id = 42;
INSERT INTO outbox (aggregate_id, type, payload)
VALUES ('42', 'OrderPaid', '{"order_id":42,"amount":1999}');
COMMIT;
-- reconciliation: anything older than 5 minutes and still unpublished means the relay is stuck
SELECT count(*), min(created_at) FROM outbox
WHERE published_at IS NULL AND created_at < now() - interval '5 minutes';The Go relay uses the outbox id as the IDMP idempotent id on Redis 8.6+ so a relay crash between XADD and UPDATE does not append twice; the Laravel relay relies on consumers deduplicating by outbox_id.
// Package main relays rows from a database outbox table into a Redis stream.
// The database stays the source of truth; the stream is the fast feed.
package main
import (
"context"
"database/sql"
"fmt"
"strconv"
"github.com/redis/go-redis/v9"
)
// relayBatch publishes unpublished outbox rows in id order, then marks them.
// A crash between XADD and UPDATE republishes a row on the next run; with
// Redis 8.6+ the IDMP option (ProducerID + IdempotentID) makes Redis return
// the original entry id instead of appending a duplicate. On older servers
// leave those two fields empty and let consumers deduplicate by outbox_id.
func relayBatch(ctx context.Context, db *sql.DB, rdb *redis.Client) (int, error) {
rows, err := db.QueryContext(ctx,
`SELECT id, aggregate_id, type, payload FROM outbox
WHERE published_at IS NULL ORDER BY id LIMIT 100`)
if err != nil {
return 0, err
}
defer rows.Close()
var done []int64
for rows.Next() {
var id int64
var agg, typ, payload string
if err := rows.Scan(&id, &agg, &typ, &payload); err != nil {
return 0, err
}
err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: "events:orders",
ProducerID: "outbox-relay",
IdempotentID: strconv.FormatInt(id, 10),
Values: map[string]any{
"outbox_id": id, "aggregate_id": agg, "type": typ, "payload": payload,
},
}).Err()
if err != nil {
return len(done), err
}
done = append(done, id)
}
if err := rows.Err(); err != nil {
return len(done), err
}
for _, id := range done {
if _, err := db.ExecContext(ctx,
`UPDATE outbox SET published_at = now() WHERE id = $1`, id); err != nil {
return len(done), err
}
}
return len(done), nil
}
func main() {
fmt.Println("integration example: call relayBatch with your application's configured sql.DB and Redis client")
}This is an integration function, not a complete database CLI: call relayBatch with your application’s configured *sql.DB and Redis client. Its main does not connect or relay rows; it only explains the required wiring.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* Event log for a monolith: the order is written together with an outbox row
* in one database transaction; this command copies outbox rows into a stream
* that other modules or services consume with their own consumer groups.
* A crash between XADD and the UPDATE republishes a row, so consumers dedupe
* by outbox_id (Redis 8.6+ can also dedupe on XADD with IDMP).
*/
class OutboxRelay extends Command
{
protected $signature = 'outbox:relay';
protected $description = 'Copy unpublished outbox rows into the events:orders stream';
public function handle(): int
{
$rows = DB::table('outbox')
->whereNull('published_at')
->orderBy('id')
->limit(100)
->get();
foreach ($rows as $row) {
Redis::xadd('events:orders', '*', [
'outbox_id' => (string) $row->id,
'aggregate_id' => (string) $row->aggregate_id,
'type' => $row->type,
'payload' => $row->payload,
], 1_000_000, true);
DB::table('outbox')->where('id', $row->id)->update(['published_at' => now()]);
}
$this->info("relayed {$rows->count()} rows");
return self::SUCCESS;
}
}Both relays are deliberately single-instance: it does not lock/claim rows. Multiple relays can duplicate publication and reorder an aggregate. Add transactional row claiming and per-aggregate ordering before parallelizing it. published_at records a Redis response, not irrevocable durability; a retained source archive and reconciliation are needed to recover a subsequently lost acknowledged write.
Lightweight CDC Good to know
"CDC" proper reads the database's own log (PostgreSQL logical decoding, MySQL binlog) with a tool such as Debezium, which by default targets Kafka; that is owned by Change Data Capture. The lightweight version for a small system is the outbox relay above, or a relay that polls updated_at > last_seen and appends changed rows to a stream per table. It is cheap and good enough for cache warming, search indexing and notifications. Its limits: it sees only changes made through paths that write the outbox (or bump updated_at), it does not capture deletes unless you write tombstones, and its durability is Redis durability. Keyspace notifications are not CDC: they are lossy and carry only the key name.
Per-key ordering at scale: shard by key across streams
To keep "all events of order 42 in order" while running several consumers, map each key to one of N streams and run exactly one active consumer per stream (a group with a single consumer, or plain XREAD with a stored id). In Cluster, give each shard its own hash tag so shards spread across nodes. Changing N later remaps keys; drain old streams first. This is what a Kafka topic with N partitions gives you natively.
// Package main spreads one logical event stream over N Redis streams by key,
// the Redis equivalent of Kafka partitions: per-key order holds inside one
// stream, and each stream gets exactly one active consumer for ordered work.
package main
import (
"context"
"fmt"
"hash/fnv"
"os"
"github.com/redis/go-redis/v9"
)
const shards = 8
// streamFor maps a key to one of N streams. The hash tag {orders-3} decides
// the cluster slot, so different shards can live on different nodes; never
// put all shards in one tag, or they all land on one node again.
func streamFor(key string) string {
h := fnv.New32a()
_, _ = h.Write([]byte(key))
return fmt.Sprintf("{orders-%d}:events", h.Sum32()%shards)
}
// publish appends an order event to the order's shard. Events of the same
// order are totally ordered by entry id; events of different orders on
// different shards have no order relative to each other.
func publish(ctx context.Context, rdb redis.UniversalClient, orderID, typ string) (string, error) {
return rdb.XAdd(ctx, &redis.XAddArgs{
Stream: streamFor(orderID),
MaxLen: 1_000_000,
Approx: true,
Values: map[string]any{"order_id": orderID, "type": typ},
}).Result()
}
func main() {
addrs := os.Getenv("REDIS_CLUSTER_ADDRS")
if addrs == "" {
for _, id := range []string{"o-1", "o-2", "o-3"} {
fmt.Println(id, "->", streamFor(id))
}
return
}
rdb := redis.NewUniversalClient(&redis.UniversalOptions{Addrs: []string{addrs}})
defer rdb.Close()
id, err := publish(context.Background(), rdb, "o-1", "OrderPlaced")
fmt.Println(id, err)
}Poison messages and parking
A message that crashes the handler every time will be claimed forever, each claim raising its delivery counter. Read the counter with extended XPENDING (or the XREADGROUP ... CLAIM reply on 8.4+), and above a threshold copy the entry to a dead stream (orders:dead, same hash tag in Cluster) and XACK it in the main group. On 8.8+, XNACK ... FATAL marks it permanently failed for your dead-letter processor. Replaying a parked entry is an XADD back to the main stream after the fix. The general DLQ design (alerting, replay tooling, Laravel failed_jobs) is owned by Dead Letter Queue.
| Failure | Retry? | Redis-side action |
|---|---|---|
| Handler threw a transient error (timeout, 503) | Yes, with backoff | Leave pending; reaper re-claims after min-idle |
| Handler threw a permanent error (validation) | No | Park in dead stream, XACK |
| Delivery count above threshold | No | Park, XACK, alert |
NOGROUP | After fixing | Recreate group; investigate the deleted key |
OOM on XADD | Yes, producer backoff | Trim, scale memory, check stuck groups |
Connection reset during XREADGROUP | Yes | Reconnect; entries read but not received are in the PEL |
Go
All Go code uses github.com/redis/go-redis/v9 (v9.18.0), compiles without a server, and exits early unless REDIS_ADDR is set.
Before
Pub/Sub used as a job queue. Publish succeeds with zero receivers, a restarting worker misses everything sent meanwhile, and two workers both process every job.
// Package main shows Pub/Sub misused as a job queue.
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/redis/go-redis/v9"
)
// enqueue "sends a job" by publishing it. Redis does not store the message:
// it pushes it to whoever is subscribed at this instant. With zero
// subscribers the job is dropped and the call still succeeds, returning 0.
func enqueue(ctx context.Context, rdb *redis.Client, payload string) error {
receivers, err := rdb.Publish(ctx, "jobs", payload).Result()
if err != nil {
return err
}
if receivers == 0 {
// Nobody was listening. The job is gone and nothing records that.
log.Printf("job lost: %s", payload)
}
return nil
}
// work subscribes and handles jobs. If this process is down, restarting,
// or its connection drops, every job published meanwhile is lost. If two
// workers run, both receive every job: it is fan-out, not a work queue.
func work(ctx context.Context, rdb *redis.Client) error {
sub := rdb.Subscribe(ctx, "jobs")
defer sub.Close()
for msg := range sub.Channel() {
fmt.Println("processing", msg.Payload)
// No ack exists. A crash here loses the job for good.
}
return nil
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
fmt.Println("set REDIS_ADDR to run this example")
return
}
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
if err := enqueue(ctx, rdb, `{"order_id":42}`); err != nil {
log.Fatal(err)
}
if err := work(ctx, rdb); err != nil {
log.Fatal(err)
}
}After: a stream work queue with a reaper
A producer with approximate MAXLEN trimming plus a MINID age trim, a consumer that first drains its own PEL (0) and then reads new entries (>), acknowledging after success, an XAUTOCLAIM reaper that parks poison entries in a dead stream, and a monitor reading XPENDING, XINFO GROUPS and XINFO CONSUMERS.
package main
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
const (
stream = "jobs"
deadStream = "jobs:dead"
group = "workers"
)
// enqueue appends a job to the stream. MaxLen with Approx set sends
// "MAXLEN ~ 100000": Redis trims whole internal nodes, which is much cheaper
// than an exact trim but may leave slightly more than 100000 entries.
// Trimming is by length, so size it above the backlog you can ever reach.
func enqueue(ctx context.Context, rdb *redis.Client, payload string) (string, error) {
return rdb.XAdd(ctx, &redis.XAddArgs{
Stream: stream,
MaxLen: 100_000,
Approx: true,
ID: "*", // let Redis generate <ms>-<seq>
Values: map[string]any{"payload": payload},
}).Result()
}
// trimOlderThan is time-based retention, which Redis does not do by itself:
// entry ids start with a millisecond timestamp, so "MINID ~ <now-age>-0"
// drops entries older than age. Run it from a ticker or a scheduler.
// With the default KEEPREF, trimmed entries that were still pending stay in
// the PEL as dangling ids until XAUTOCLAIM/XCLAIM removes them.
func trimOlderThan(ctx context.Context, rdb *redis.Client, age time.Duration) (int64, error) {
minID := fmt.Sprintf("%d-0", time.Now().Add(-age).UnixMilli())
return rdb.XTrimMinIDApprox(ctx, stream, minID, 0).Result()
}package main
import (
"context"
"errors"
"log"
"strings"
"time"
"github.com/redis/go-redis/v9"
)
// ensureGroup creates the stream and group if missing. Starting at "0" means
// the group sees entries added before it existed; "$" would skip them.
func ensureGroup(ctx context.Context, rdb *redis.Client) error {
err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err()
if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
return err
}
return nil
}
// handler must be idempotent: a message can be delivered more than once.
type handler func(ctx context.Context, msg redis.XMessage) error
// consume first re-reads this consumer's own pending entries (id "0"), which
// is what a restarted consumer with the same name must do, then switches to
// new entries (">"). Each entry is acknowledged only after the handler
// succeeded. A crash between handling and XACK leaves the entry in the PEL,
// where the reaper or the next start of this consumer will find it.
func consume(ctx context.Context, rdb *redis.Client, name string, h handler) error {
cursor := "0" // history of our own PEL first
for ctx.Err() == nil {
args := &redis.XReadGroupArgs{
Group: group,
Consumer: name,
Streams: []string{stream, cursor},
Count: 10,
// go-redis sends BLOCK whenever Block >= 0, so the zero value
// means "BLOCK 0" (forever). -1 omits it for the PEL pass.
Block: -1,
}
if cursor == ">" {
args.Block = 5 * time.Second
}
res, err := rdb.XReadGroup(ctx, args).Result()
if errors.Is(err, redis.Nil) {
if cursor != ">" {
cursor = ">" // no own pending entries remain
}
continue // block timeout, nothing new
}
if err != nil {
return err
}
n := 0
for _, s := range res {
for _, msg := range s.Messages {
n++
if cursor != ">" {
cursor = msg.ID // page through our PEL
}
if err := h(ctx, msg); err != nil {
// No XACK: the entry stays pending and is retried later.
log.Printf("handler failed for %s: %v", msg.ID, err)
continue
}
if err := rdb.XAck(ctx, stream, group, msg.ID).Err(); err != nil {
return err
}
}
}
if cursor != ">" && n == 0 {
cursor = ">" // own backlog drained: now take new entries
}
}
return ctx.Err()
}package main
import (
"context"
"log"
"time"
"github.com/redis/go-redis/v9"
)
const (
minIdle = 30 * time.Second
maxDeliveries = 5
)
// reap claims entries that have been pending longer than minIdle, whichever
// consumer owns them, and either re-handles them or parks them in a dead
// stream once they have been delivered too many times.
func reap(ctx context.Context, rdb *redis.Client, name string, h handler) error {
start := "0-0"
for {
msgs, next, err := rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: stream,
Group: group,
Consumer: name,
MinIdle: minIdle,
Start: start,
Count: 50,
}).Result()
if err != nil {
return err
}
for _, msg := range msgs {
if err := settle(ctx, rdb, msg, h); err != nil {
return err
}
}
if next == "0-0" {
return nil // scanned the whole PEL
}
start = next
}
}
func settle(ctx context.Context, rdb *redis.Client, msg redis.XMessage, h handler) error {
// Claiming increments the delivery counter; XPENDING exposes it.
ext, err := rdb.XPendingExt(ctx, &redis.XPendingExtArgs{
Stream: stream, Group: group, Start: msg.ID, End: msg.ID, Count: 1,
}).Result()
if err != nil {
return err
}
if len(ext) == 1 && ext[0].RetryCount > maxDeliveries {
// Preserve source identity: a crash after XADD can park a duplicate.
parked := make(map[string]interface{}, len(msg.Values)+2)
for key, value := range msg.Values {
parked[key] = value
}
parked["_source_stream"] = stream
parked["_source_id"] = msg.ID
if err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: deadStream,
MaxLen: 10_000,
Approx: true,
Values: parked,
}).Err(); err != nil {
return err
}
return rdb.XAck(ctx, stream, group, msg.ID).Err()
}
if err := h(ctx, msg); err != nil {
log.Printf("retry failed for %s: %v", msg.ID, err)
return nil // stays pending; claimed again after minIdle
}
return rdb.XAck(ctx, stream, group, msg.ID).Err()
}Parking uses separate XADD and XACK calls. A crash between them can create duplicate dead-stream entries; _source_stream and _source_id preserve the deduplication key. A same-slot Lua script can make these Redis mutations atomic, but business side effects still need idempotency.
package main
import (
"context"
"log"
"github.com/redis/go-redis/v9"
)
// report logs the group's backlog. XPENDING (summary form) gives the pending
// count, the smallest and largest pending ids and a per-consumer breakdown.
// XINFO GROUPS gives last-delivered-id, entries-read and lag (entries not yet
// delivered to the group). Alert on lag, on pending count and on idle consumers.
func report(ctx context.Context, rdb *redis.Client) error {
p, err := rdb.XPending(ctx, stream, group).Result()
if err != nil {
return err
}
log.Printf("pending=%d oldest=%s newest=%s consumers=%v",
p.Count, p.Lower, p.Higher, p.Consumers)
groups, err := rdb.XInfoGroups(ctx, stream).Result()
if err != nil {
return err
}
for _, g := range groups {
// Lag is -1 when Redis replies NULL: after XDEL/trim inside the unread
// range, or after XGROUP CREATE/SETID at an arbitrary id.
log.Printf("group=%s last-delivered=%s entries-read=%d lag=%d pending=%d",
g.Name, g.LastDeliveredID, g.EntriesRead, g.Lag, g.Pending)
}
consumers, err := rdb.XInfoConsumers(ctx, stream, group).Result()
if err != nil {
return err
}
for _, c := range consumers {
// Inactive is the time since the consumer's last successful read.
log.Printf("consumer=%s pending=%d idle=%s inactive=%s",
c.Name, c.Pending, c.Idle, c.Inactive)
}
// The stream length is the memory side of the same story.
n, err := rdb.XLen(ctx, stream).Result()
if err != nil {
return err
}
log.Printf("stream length=%d", n)
return nil
}// Package main is a Redis Streams work queue: producer, consumer group,
// reaper for stuck entries and a pending-list monitor, using go-redis v9.
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
fmt.Println("set REDIS_ADDR to run this example")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
if err := ensureGroup(ctx, rdb); err != nil {
log.Fatal(err)
}
if _, err := enqueue(ctx, rdb, `{"order_id":42}`); err != nil {
log.Fatal(err)
}
h := func(ctx context.Context, msg redis.XMessage) error {
fmt.Println("processing", msg.ID, msg.Values["payload"])
return nil
}
go func() {
t := time.NewTicker(15 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := reap(ctx, rdb, "reaper-1", h); err != nil {
log.Printf("reap: %v", err)
}
if err := report(ctx, rdb); err != nil {
log.Printf("report: %v", err)
}
if _, err := trimOlderThan(ctx, rdb, 72*time.Hour); err != nil {
log.Printf("trim: %v", err)
}
}
}
}()
if err := consume(ctx, rdb, "worker-1", h); err != nil && ctx.Err() == nil {
log.Fatal(err)
}
}Pub/Sub subscriber
Cache invalidation over Pub/Sub, with the go-redis channel buffer made explicit, and the sharded variant for Cluster.
// Package main shows Redis Pub/Sub for what it is good at: an ephemeral
// signal (cache invalidation) where a missed message is repaired by a TTL.
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"time"
"github.com/redis/go-redis/v9"
)
const channel = "cache-invalidate"
// invalidate publishes a signal. The reply is the number of clients that
// received it right now; 0 is not an error, the message is simply gone.
func invalidate(ctx context.Context, rdb *redis.Client, key string) error {
n, err := rdb.Publish(ctx, channel, key).Result()
if err != nil {
return err
}
if n == 0 {
log.Printf("no subscriber received %q (fine: local caches expire anyway)", key)
}
return nil
}
// listen subscribes and drops local cache entries. While this process is
// disconnected or restarting, every message is lost: at-most-once.
func listen(ctx context.Context, rdb *redis.Client, local map[string]string) error {
sub := rdb.Subscribe(ctx, channel)
defer sub.Close()
// Wait for the subscription confirmation before relying on it.
if _, err := sub.Receive(ctx); err != nil {
return err
}
// Channel() buffers 100 messages by default; if this loop is slower than
// the publisher for longer than the send timeout (60 s), go-redis drops
// messages, and Redis itself disconnects a subscriber whose output buffer
// exceeds client-output-buffer-limit pubsub (32mb hard, 8mb for 60 s).
ch := sub.Channel(redis.WithChannelSize(1000))
for {
select {
case <-ctx.Done():
return ctx.Err()
case msg, ok := <-ch:
if !ok {
return nil
}
delete(local, msg.Payload)
fmt.Println("invalidated", msg.Payload)
}
}
}
// listenSharded is the Redis Cluster variant (Redis 7.0+): SSUBSCRIBE and
// SPUBLISH keep the message inside the shard that owns the channel's slot
// instead of broadcasting it over the whole cluster bus.
func listenSharded(ctx context.Context, rc *redis.ClusterClient) error {
sub := rc.SSubscribe(ctx, "{tenant-42}:cache-invalidate")
defer sub.Close()
for msg := range sub.Channel() {
fmt.Println("shard message", msg.Channel, msg.Payload)
if ctx.Err() != nil {
return ctx.Err()
}
}
return nil
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
fmt.Println("set REDIS_ADDR to run this example")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
local := map[string]string{"product:42": "cached"}
go func() {
time.Sleep(500 * time.Millisecond)
if err := invalidate(ctx, rdb, "product:42"); err != nil {
log.Print(err)
}
}()
if err := listen(ctx, rdb, local); err != nil && ctx.Err() == nil {
log.Fatal(err)
}
_ = listenSharded // needs a cluster; shown for the API shape
}BLMOVE list worker
The reliable list queue: BLMove(..., "RIGHT", "LEFT", 5*time.Second), LRem after success, and a start-up requeue of the worker's processing list.
// Package main is the "reliable queue" pattern on Redis lists: BLMOVE moves
// a job atomically from the queue to a per-worker processing list, LREM
// removes it after success, and a requeuer returns stuck jobs.
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"time"
"github.com/redis/go-redis/v9"
)
const queue = "jobs:list"
func processing(worker string) string { return queue + ":processing:" + worker }
// produce appends to the head; workers take from the tail (FIFO).
func produce(ctx context.Context, rdb *redis.Client, job string) error {
return rdb.LPush(ctx, queue, job).Err()
}
// work is one worker loop. BLMOVE RIGHT LEFT is the non-deprecated form of
// BRPOPLPUSH: pop the oldest job and push it onto our processing list in one
// atomic step, so a crash after the pop cannot lose the job.
func work(ctx context.Context, rdb *redis.Client, worker string, h func(string) error) error {
for ctx.Err() == nil {
job, err := rdb.BLMove(ctx, queue, processing(worker), "RIGHT", "LEFT", 5*time.Second).Result()
if errors.Is(err, redis.Nil) {
continue // timeout, queue empty
}
if err != nil {
return err
}
if err := h(job); err != nil {
log.Printf("job failed, left in processing list: %v", err)
continue
}
// Remove exactly one copy of this payload from our processing list.
if err := rdb.LRem(ctx, processing(worker), 1, job).Err(); err != nil {
return err
}
}
return ctx.Err()
}
// requeue runs at start-up for a worker name that may have crashed: it moves
// every job still in that worker's processing list back to the queue. A list
// has no per-item delivery time or counter, so real systems store them
// next to the payload (a hash or a sorted set), which is what Laravel does.
func requeue(ctx context.Context, rdb *redis.Client, worker string) (int, error) {
n := 0
for {
_, err := rdb.LMove(ctx, processing(worker), queue, "RIGHT", "RIGHT").Result()
if errors.Is(err, redis.Nil) {
return n, nil
}
if err != nil {
return n, err
}
n++
}
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
fmt.Println("set REDIS_ADDR to run this example")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
if n, err := requeue(ctx, rdb, "w1"); err != nil {
log.Fatal(err)
} else if n > 0 {
log.Printf("requeued %d jobs left by a previous crash", n)
}
if err := produce(ctx, rdb, `{"email":"a@example.com"}`); err != nil {
log.Fatal(err)
}
err := work(ctx, rdb, "w1", func(job string) error {
fmt.Println("sending", job)
return nil
})
if err != nil && ctx.Err() == nil {
log.Fatal(err)
}
}The Go angle
go-redis exposes each command as a typed method: XAdd with XAddArgs (MaxLen, MinID, Approx, Limit, NoMkStream, and since v9.18 ProducerID/IdempotentID/IdempotentAuto for IDMP), XGroupCreateMkStream, XReadGroup with XReadGroupArgs (Block, Count, NoAck, Claim), XAck, XAckDel, XPending/XPendingExt, XClaim, XAutoClaim (returns the entries and the next cursor), XInfoGroups (with Lag, -1 when Redis replies NULL), XInfoConsumers, XTrimMaxLenApprox, XTrimMinIDApprox, BLMove, LRem. Four details bite in practice:
- A blocking read that times out returns
redis.Nil, not an empty result; loops must treat it as "try again". XReadGroupArgs.Blockis sent whenever it is>= 0, so the zero value meansBLOCK 0, block forever; set-1to omit it. A blocked command holds a pool connection for the whole block (go-redis raises the read timeout to match), so sizePoolSizefor one connection per concurrent blocking consumer.PubSub.Channel()buffers 100 messages by default and, per its own doc comment,WithChannelSendTimeoutis "the channel send timeout after which the message is dropped" (default 60 seconds): a slow Go handler loses Pub/Sub messages even before Redis' output-buffer limit does.BUSYGROUPis a plain error string; compare withstrings.HasPrefix. Pass a signal-awarecontext.Contextso shutdown stops the loop between reads; an in-flight entry that was not acked is left in the PEL for the next start or the reaper.
Use redis.NewClusterClient (or NewUniversalClient) in Cluster; it follows MOVED/ASK and routes SSubscribe to the right shard.
Laravel
Laravel 13's queue docs list the built-in drivers: "the database, Amazon SQS, Redis, and Beanstalkd drivers"; it also documents sync, null, deferred, background and failover drivers. The redis driver uses lists and sorted sets (internals above); Redis Streams and Pub/Sub are used through the Redis facade. The snippets target phpredis, Laravel's default client ('client' => env('REDIS_CLIENT', 'phpredis')), whose stream signatures are xadd($key, $id, $values, $maxlen, $approx, $nomkstream), xreadgroup($group, $consumer, $streams, $count, $block), xautoclaim($key, $group, $consumer, $min_idle, $start, $count, $justid). Predis orders arguments differently.
Before
Redis::publish used to hand work to workers: no subscriber means a lost job, and every subscriber receives every job.
<?php
namespace App\Services;
use Illuminate\Support\Facades\Redis;
/**
* Pub/Sub used to hand work to workers. publish() returns the number of
* subscribers that received the message; with no subscriber the job is
* silently dropped, and nothing is stored for a worker that starts later.
*/
class ReportDispatcher
{
public function dispatch(int $reportId): void
{
$receivers = Redis::publish('reports', json_encode(['report_id' => $reportId]));
if ($receivers === 0) {
// Nobody was listening: the job is gone and there is no record of it.
logger()->warning("report {$reportId} lost: no subscriber");
}
}
}
// Worker side, in an Artisan command. Every subscriber gets every message
// (fan-out, not competing consumers), and a crash loses the job: no ack.
//
// Redis::subscribe(['reports'], function (string $message): void {
// generateReport(json_decode($message, true)['report_id']);
// });After: a stream consumer command
The producer appends with an approximate MAXLEN:
<?php
namespace App\Services;
use Illuminate\Support\Facades\Redis;
/**
* Appends a job to a Redis stream. The Redis facade forwards calls to the
* configured client; this code targets phpredis (Laravel's default client),
* where the signature is xadd($key, $id, $values, $maxlen, $approx).
* Predis orders the arguments differently.
*/
class ProduceJob
{
public const STREAM = 'reports';
public function __invoke(int $reportId): string
{
// "*" lets Redis generate the entry id; maxlen 100000 with approx = true
// sends MAXLEN ~ 100000, a cheap trim that may keep slightly more entries.
$id = Redis::xadd(self::STREAM, '*', ['report_id' => (string) $reportId], 100_000, true);
if ($id === false) {
throw new \RuntimeException('XADD failed');
}
return $id;
}
}An Artisan command is the consumer: create the group (tolerating BUSYGROUP), loop on xreadgroup, xack after the work succeeds, stop on SIGTERM.
<?php
namespace App\Console\Commands;
use App\Services\ProcessReport;
use App\Services\ProduceJob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class ConsumeJobs extends Command
{
protected $signature = 'reports:consume {consumer=worker-1} {--group=report-workers}';
protected $description = 'Consume report jobs from a Redis stream consumer group';
private bool $stop = false;
public function handle(): int
{
$stream = ProduceJob::STREAM;
$group = $this->option('group');
$consumer = $this->argument('consumer');
// Create the group (and the stream) once; BUSYGROUP means it exists already.
try {
Redis::xgroup('CREATE', $stream, $group, '0', true);
} catch (\Throwable $e) {
if (! str_contains($e->getMessage(), 'BUSYGROUP')) {
throw $e;
}
}
pcntl_async_signals(true);
pcntl_signal(SIGTERM, fn () => $this->stop = true);
pcntl_signal(SIGINT, fn () => $this->stop = true);
while (! $this->stop) {
// ">" asks for entries never delivered to this group; block up to 5000 ms.
$batch = Redis::xreadgroup($group, $consumer, [$stream => '>'], 10, 5000);
if (! is_array($batch)) {
continue; // timeout, nothing new
}
// The reply is keyed by stream name. Iterate it instead of indexing
// by $stream: with Laravel's key prefix the returned key may be the
// prefixed one (e.g. "laravel-database-reports").
foreach ($batch as $entries) {
foreach ($entries as $id => $fields) {
try {
app(ProcessReport::class)((int) $fields['report_id']);
// Acknowledge only after the work is done.
Redis::xack($stream, $group, [$id]);
} catch (\Throwable $e) {
// No XACK: the entry stays in the PEL and the reaper retries it.
report($e);
}
}
}
}
return self::SUCCESS;
}
}<?php
namespace App\Services;
/**
* The job body, shared by the consumer and the reaper. It must be idempotent:
* a stream entry can be delivered more than once (at-least-once).
*/
class ProcessReport
{
public function __invoke(int $reportId): void
{
// ...generate the report, using an upsert or a dedup key...
}
}A second command is the reaper, scheduled every minute with the Laravel scheduler (Schedule::command('reports:reap')->everyMinute()->withoutOverlapping()) or run under a process supervisor; a third prints what to alert on.
<?php
namespace App\Console\Commands;
use App\Services\ProcessReport;
use App\Services\ProduceJob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class ReapJobs extends Command
{
protected $signature = 'reports:reap {--group=report-workers} {--idle=30000} {--max-deliveries=5}';
protected $description = 'Reclaim stuck stream entries, retry them or park them in a dead stream';
public function handle(): int
{
$stream = ProduceJob::STREAM;
$group = $this->option('group');
$idle = (int) $this->option('idle');
$maxDeliveries = (int) $this->option('max-deliveries');
$start = '0-0';
do {
// Entries pending longer than $idle ms are transferred to this consumer.
// phpredis returns [next-start-id, [id => fields, ...], ...].
$claimed = Redis::xautoclaim($stream, $group, 'reaper', $idle, $start, 50);
if (! is_array($claimed)) {
break;
}
[$start, $messages] = [$claimed[0], $claimed[1]];
foreach ($messages as $id => $fields) {
// Extended XPENDING for one id: [[id, consumer, idle ms, delivery count]].
$info = Redis::xpending($stream, $group, $id, $id, 1);
$deliveries = $info[0][3] ?? 0;
if ($deliveries > $maxDeliveries) {
// Retain identity so duplicate parking can be deduplicated.
$fields['_source_stream'] = $stream;
$fields['_source_id'] = $id;
Redis::xadd("{$stream}:dead", '*', $fields, 10_000, true);
Redis::xack($stream, $group, [$id]);
$this->warn("parked {$id} after {$deliveries} deliveries");
continue;
}
try {
// The reaper now owns the entry, so it does the work itself.
app(ProcessReport::class)((int) $fields['report_id']);
Redis::xack($stream, $group, [$id]);
} catch (\Throwable $e) {
// Still pending; claimed again once it has been idle long enough.
report($e);
}
}
} while ($start !== '0-0');
// Backlog summary: [count, smallest id, largest id, [[consumer, count], ...]].
$summary = Redis::xpending($stream, $group);
$this->info('pending='.($summary[0] ?? 0));
return self::SUCCESS;
}
}<?php
namespace App\Console\Commands;
use App\Services\ProduceJob;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
/**
* Prints what to alert on for a stream: length, per-group lag and pending
* count, and per-consumer idle time (XINFO STREAM / GROUPS / CONSUMERS).
*/
class StreamStats extends Command
{
protected $signature = 'reports:stats {--group=report-workers}';
protected $description = 'Show stream length, group lag, pending entries and consumer idle time';
public function handle(): int
{
$stream = ProduceJob::STREAM;
$this->line('length: '.Redis::xlen($stream));
foreach (Redis::xinfo('GROUPS', $stream) as $g) {
// lag is null when Redis cannot compute it (XDEL/trim, SETID).
$this->line(sprintf(
'group=%s pending=%d last-delivered-id=%s lag=%s',
$g['name'], $g['pending'], $g['last-delivered-id'], var_export($g['lag'] ?? null, true)
));
}
foreach (Redis::xinfo('CONSUMERS', $stream, $this->option('group')) as $c) {
$this->line(sprintf('consumer=%s pending=%d idle=%dms', $c['name'], $c['pending'], $c['idle']));
}
return self::SUCCESS;
}
}Pub/Sub listener
The Laravel docs place Redis::subscribe in an Artisan command because subscription runs as a persistent process; Redis::psubscribe takes glob patterns.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
/**
* Pub/Sub used correctly: an ephemeral signal. If this process is down, it
* misses messages, which is acceptable because cached entries also carry a TTL.
* Publisher side, anywhere in the app:
* Redis::publish('cache-invalidate', 'product:42');
*/
class CacheInvalidationListener extends Command
{
protected $signature = 'cache:listen-invalidations';
protected $description = 'Drop local cache entries when another node publishes an invalidation';
public function handle(): void
{
// subscribe() blocks this process (the connection is in subscribed
// mode); run the command under a supervisor (systemd, Supervisor, a container).
Redis::subscribe(['cache-invalidate'], function (string $key): void {
Cache::store('array')->forget($key);
});
}
}BLMOVE list worker
blmove passes straight through to phpredis; lrem goes through Laravel's own wrapper, whose argument order is lrem($key, $count, $value) (it calls phpredis with [$key, $value, $count]).
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
/**
* The reliable-queue pattern on a plain Redis list, without Laravel's queue
* driver: BLMOVE moves the job to a per-worker processing list atomically,
* LREM removes it after success. blmove() is passed straight to phpredis;
* lrem() goes through Laravel's wrapper, whose order is ($key, $count, $value).
*/
class ListWorker extends Command
{
protected $signature = 'mail:list-worker {worker=w1}';
protected $description = 'Consume a Redis list with BLMOVE and a processing list';
public function handle(): int
{
$queue = 'mail:list';
$processing = $queue.':processing:'.$this->argument('worker');
// Crash recovery: anything left in our processing list goes back first.
while (Redis::lmove($processing, $queue, 'RIGHT', 'RIGHT')) {
$this->warn('requeued a job left by a previous run');
}
while (true) {
// Block up to 5 seconds; false/null means the queue stayed empty.
$job = Redis::blmove($queue, $processing, 'RIGHT', 'LEFT', 5.0);
if (! is_string($job)) {
continue;
}
try {
$this->send(json_decode($job, true, flags: JSON_THROW_ON_ERROR));
Redis::lrem($processing, 1, $job);
} catch (\Throwable $e) {
// Left in the processing list; the next start requeues it.
report($e);
}
}
}
private function send(array $mail): void
{
// ...call the mail provider with an idempotency key...
}
}Queue connection config
<?php
// config/queue.php (excerpt): Laravel's built-in redis queue driver.
// It stores jobs in lists and sorted sets, not in Redis Streams.
return [
'connections' => [
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
// On Redis Cluster use a hash tag so all keys of a queue share a slot.
'queue' => env('REDIS_QUEUE', '{default}'),
// Seconds before a reserved job is pushed back for another attempt.
// Keep the worker --timeout a few seconds shorter than this.
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
// Block on the :notify list for up to 5 s instead of polling.
'block_for' => 5,
// Push only after the surrounding DB transaction commits.
'after_commit' => true,
],
],
];The Laravel angle
- The built-in driver is lists + sorted sets.
RedisQueue::pop()callsmigrate()(delayed and expired reserved jobs back to the list) and then thepopLua script;deleteReserved()is azrem;deleteAndRelease()moves the job to:delayed. Attempts are counted inside the payload (reserved['attempts'] + 1in Lua), not by Redis. - Horizon is a dashboard and supervisor for the redis driver only: its workers require the redis driver and currently do not support Redis Cluster. Supervisors define worker pools per queue with
balanceset toauto,simpleorfalse;tries,timeoutandbackoffcan be set per supervisor. Horizon does not use streams either; its workers run on the same list-and-sorted-set queue, and its metrics dashboard is filled by the scheduledhorizon:snapshotcommand. Operating it is covered in Laravel Queue Internals and Messaging Observability. - Key prefix. The
prefixoption inconfig/database.php(default<app-name>-database-) is applied by the client to every key, including stream keys, so a Go service reading the same stream must use the prefixed name (laravel-database-reports). The consumer above iterates thexreadgroupreply instead of indexing it by the unprefixed name for this reason. - Transactions.
after_commit => true(or->afterCommit()) delays the queue push until the database transaction commits; for streams written withRedis::xaddyou get no such help, which is why the event-log pattern uses an outbox table. Redis::throttleis a rate limiter, not a delivery mechanism; it does not store, retry or acknowledge messages. Use it inside a stream consumer to cap calls to a downstream API.- Consumers as processes. Long-running
reports:consumecommands need the same care asqueue:work: a supervisor,SIGTERMhandling (the snippet usespcntl_signal), memory limits and restarts on deploy.
Compared with the others
RabbitMQ
RabbitMQ is a broker of queues: producers publish to exchanges, bindings route copies into queues, and the broker tracks every delivery per channel. What it gives you that Redis Streams does not: routing (direct, topic, fanout, headers exchanges) instead of "one stream per kind of event"; automatic requeue of unacked deliveries when a consumer's channel or connection closes, so no reaper; dead-letter exchanges, message and queue TTLs and delivery limits as configuration; and replication by consensus: RabbitMQ quorum queues replicate through Raft, where a publisher confirm means a majority of replicas have the message, unlike Redis' asynchronous replication. What Redis gives you that RabbitMQ does not: replay (a consumed RabbitMQ message is gone from a classic or quorum queue), several groups reading the same entries without copying, memory-backed reads and writes (measure latency for your workload), and zero extra infrastructure if Redis is already there. RabbitMQ Streams is a separate log-oriented feature; the replay contrast here concerns classic/quorum queues. Redis requires application parking logic such as:
package main
import (
"context"
"log"
"time"
"github.com/redis/go-redis/v9"
)
const (
minIdle = 30 * time.Second
maxDeliveries = 5
)
// reap claims entries that have been pending longer than minIdle, whichever
// consumer owns them, and either re-handles them or parks them in a dead
// stream once they have been delivered too many times.
func reap(ctx context.Context, rdb *redis.Client, name string, h handler) error {
start := "0-0"
for {
msgs, next, err := rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: stream,
Group: group,
Consumer: name,
MinIdle: minIdle,
Start: start,
Count: 50,
}).Result()
if err != nil {
return err
}
for _, msg := range msgs {
if err := settle(ctx, rdb, msg, h); err != nil {
return err
}
}
if next == "0-0" {
return nil // scanned the whole PEL
}
start = next
}
}
func settle(ctx context.Context, rdb *redis.Client, msg redis.XMessage, h handler) error {
// Claiming increments the delivery counter; XPENDING exposes it.
ext, err := rdb.XPendingExt(ctx, &redis.XPendingExtArgs{
Stream: stream, Group: group, Start: msg.ID, End: msg.ID, Count: 1,
}).Result()
if err != nil {
return err
}
if len(ext) == 1 && ext[0].RetryCount > maxDeliveries {
// Preserve source identity: a crash after XADD can park a duplicate.
parked := make(map[string]interface{}, len(msg.Values)+2)
for key, value := range msg.Values {
parked[key] = value
}
parked["_source_stream"] = stream
parked["_source_id"] = msg.ID
if err := rdb.XAdd(ctx, &redis.XAddArgs{
Stream: deadStream,
MaxLen: 10_000,
Approx: true,
Values: parked,
}).Err(); err != nil {
return err
}
return rdb.XAck(ctx, stream, group, msg.ID).Err()
}
if err := h(ctx, msg); err != nil {
log.Printf("retry failed for %s: %v", msg.ID, err)
return nil // stays pending; claimed again after minIdle
}
return rdb.XAck(ctx, stream, group, msg.ID).Err()
}See RabbitMQ in Depth and, for the decision, Redis vs RabbitMQ vs Kafka.
Kafka
Kafka and Redis Streams share the vocabulary (log, consumer group, offsets/ids) and differ in almost every operational property:
| Property | Redis Streams | Kafka |
|---|---|---|
| Partitions | None: one stream = one key = one node; shard by key yourself | "Topics are partitioned, meaning a topic is spread over a number of buckets located on different Kafka brokers" |
| Consumer group semantics | Server-side load balancing of entries to any ready consumer; per-entry PEL | Partitions assigned to consumers; one committed offset per partition |
| Order inside a group | Lost as soon as there are 2+ consumers | Kept per partition |
| Replication | Asynchronous; failover is best effort | Replicated partitions; acks=all + min.insync.replicas for durable writes |
| Storage and retention | RAM; you trim with MAXLEN/MINID | Disk; retention.ms default 604800000 (7 days), size retention, compaction |
| Replay | XRANGE, XGROUP SETID within what is retained in RAM | Seek to any offset within retention, days to forever |
| Schemas | None; fields are strings | None in the broker either, but a schema registry (for example Confluent Schema Registry) is a standard companion |
| Ecosystem | Client libraries | Connect, Streams, Debezium CDC, tiered storage |
The Redis docs summarise it: multiple Redis stream keys resemble Kafka partitions more closely than a Redis consumer group does So the Redis equivalent of a keyed Kafka topic is N streams with one consumer each:
// Package main spreads one logical event stream over N Redis streams by key,
// the Redis equivalent of Kafka partitions: per-key order holds inside one
// stream, and each stream gets exactly one active consumer for ordered work.
package main
import (
"context"
"fmt"
"hash/fnv"
"os"
"github.com/redis/go-redis/v9"
)
const shards = 8
// streamFor maps a key to one of N streams. The hash tag {orders-3} decides
// the cluster slot, so different shards can live on different nodes; never
// put all shards in one tag, or they all land on one node again.
func streamFor(key string) string {
h := fnv.New32a()
_, _ = h.Write([]byte(key))
return fmt.Sprintf("{orders-%d}:events", h.Sum32()%shards)
}
// publish appends an order event to the order's shard. Events of the same
// order are totally ordered by entry id; events of different orders on
// different shards have no order relative to each other.
func publish(ctx context.Context, rdb redis.UniversalClient, orderID, typ string) (string, error) {
return rdb.XAdd(ctx, &redis.XAddArgs{
Stream: streamFor(orderID),
MaxLen: 1_000_000,
Approx: true,
Values: map[string]any{"order_id": orderID, "type": typ},
}).Result()
}
func main() {
addrs := os.Getenv("REDIS_CLUSTER_ADDRS")
if addrs == "" {
for _, id := range []string{"o-1", "o-2", "o-3"} {
fmt.Println(id, "->", streamFor(id))
}
return
}
rdb := redis.NewUniversalClient(&redis.UniversalOptions{Addrs: []string{addrs}})
defer rdb.Close()
id, err := publish(context.Background(), rdb, "o-1", "OrderPlaced")
fmt.Println(id, err)
}Where Redis Streams is enough: you already run Redis with persistence, volume fits in RAM with headroom, retention of hours to a few days is enough, consumers are a handful of services you own, and a failover that redelivers or loses the newest entries is acceptable or recoverable through retained source records and destination reconciliation. Where it is not: event backbones shared by many teams, months of replay, CDC pipelines, strict per-key order at high parallelism, or "acknowledged means it survives a node loss". See Kafka in Depth.
In production systems
- Documented delivery contract. The Redis docs state Pub/Sub is at-most-once and streams support at-most-once and at-least-once; keyspace notifications are "fire and forget". Build on that wording, not on a client library's naming.
- Documented failover limits. Streams and group state replicate asynchronously;
WAITnarrows the window but failover under Sentinel or Cluster uses best-effort replica selection to pick the most up-to-date replica. The Cluster specification says acknowledged writes can be lost during partitions. - Laravel's queue driver, from source.
Illuminate/Queue/LuaScripts.php(13.x) showsrpushfor push,zaddfor later,lpop+zaddto:reservedfor pop, andzrangebyscore+rpushfor migrating expired jobs. That design is why Laravel hasretry_afterinstead of a PEL, and why--timeoutmust stay below it. - Horizon and Cluster. The Horizon docs state it is not compatible with Redis Cluster; teams that move Redis to Cluster must keep a non-cluster Redis for Horizon or drop Horizon.
- go-redis drops slow Pub/Sub messages.
pubsub.goin go-redis v9.18 logs "channel is full ... (message is dropped)" after the send timeout. This is client-side loss on top of Redis' own at-most-once contract.
Choosing
| Workload | Recommended | Extra technique | Reason |
|---|---|---|---|
| Cache invalidation, presence, live UI | Pub/Sub (sharded in Cluster) | TTL on caches; resync on reconnect | Loss is harmless; zero storage |
| Laravel background jobs | Built-in redis queue driver (+ Horizon) | after_commit, longest expected job < --timeout < retry_after, idempotent jobs | Batteries included; lists are enough |
| Go service background jobs, moderate volume | Stream + group | XAUTOCLAIM reaper, dead stream, idempotency key | Ack, redelivery, observability built in |
| Simple fire-and-forget jobs | List + BRPOP | Periodic re-scan of the source of truth | Simplest possible |
| Domain events from a monolith to modules/services | Outbox table + relay to a stream, one group per consumer | IDMP (8.6+) or consumer dedup; MINID trim | DB remains the truth; Redis is the fast feed |
| Per-key ordered processing, parallel | N streams, one consumer per stream | Hash tags spread over Cluster nodes | Single stream + group cannot keep per-key order |
| Shared event backbone, long replay, CDC | Kafka | Outbox/Debezium, schema registry | Disk retention, partitions, replication |
| Complex routing, per-message TTL, must-not-lose work queue | RabbitMQ quorum queues | DLX, publisher confirms | Routing and consensus replication built in |
When not to use Redis for messaging
- Acknowledged must mean durable across node loss. Asynchronous replication can drop the newest
XADDs on failover; RabbitMQ quorum queues and Kafka withacks=allplus an appropriatemin.insync.replicasprovide stronger replication acknowledgements (Kafka uses the ISR, not a Raft majority). - The backlog can exceed RAM. A consumer outage of a day at full rate must fit in memory, or you trim away unprocessed work.
- Replay of weeks or months. Keeping that in RAM is expensive; Kafka retention or a database event store is the tool.
- Many teams, many event types, schema governance. There is no schema registry, no ACL per stream beyond Redis ACL key patterns, and no connector ecosystem.
- The Redis is a cache with an evicting
maxmemory-policy. Your queue can be evicted as a key. Use a separate instance withnoeviction. - Cross-stream atomicity in Cluster. Two streams on different slots cannot be written atomically.
- You need delayed delivery and routing as features. Redis has neither for streams; you build sorted-set schedulers and fan-out logic yourself.
In architecture: from a single process to a distributed system
The same three primitives appear at every scale; what changes is what you are allowed to lose and who owns the stream.
Monolith: one process, one database, one Redis
Simplest correct usage: Laravel's redis queue driver for background jobs (e-mails, PDFs, webhooks), with after_commit => true so jobs never refer to rolled-back rows, retry_after above the longest job, and idempotent handlers. Pub/Sub only for signals between app processes, such as invalidating per-process caches after a deploy or a settings change. Concrete example: a shop where OrderController@store commits the order, dispatches SendOrderConfirmation after commit, and queue:work on three processes drains queues:default; a crashed worker's job reappears after retry_after. If you add an internal event log (an audit timeline), write events to an outbox table and relay them into events:orders (event log), rather than Redis::xadd inside the request.
Modular monolith: modules talk through streams
Each module owns its stream namespace (billing:events, catalog:events) and publishes only through its own relay; other modules subscribe with their own consumer group (catalog reads billing:events as group catalog). That keeps the module boundary explicit: a module never reads another module's tables, it reacts to events. Concrete example: Billing emits InvoicePaid to billing:events; Shipping (group shipping) creates a shipment; Loyalty (group loyalty) adds points; both groups lag independently, and adding Analytics later is XGROUP CREATE billing:events analytics 0. Domain events inside a module stay in-process (Laravel events or a Go function call); only integration events cross into streams; the distinction is in Domain Events vs Integration Events.
Microservices: what survives across service boundaries
Across services, nothing from one Redis call is transactional with your database, so the reliable pieces are the same as with any broker: outbox on the producer, idempotent consumer / inbox on the consumer, at-least-once in between, and a saga for multi-step business transactions. Redis Streams fits when the services are few, owned by one team, and already share a Redis deployment; otherwise the shared Redis becomes an undeclared integration database. Concrete example (message flow):
orders-svc (Laravel) Redis (stream orders:events) payments-svc (Go) email-svc (Laravel)
1 BEGIN; insert order; insert outbox; COMMIT
2 relay: XADD orders:events IDMP relay 981 * type OrderPlaced id 42
3 group payments: XREADGROUP > -> charge (idempotency key = order 42)
4 XACK; XADD payments:events * type PaymentCaptured id 42
5 group email: XREADGROUP > send "order received"
6 group orders on payments:events: XREADGROUP > -> mark order paid (inbox table dedup), XACK
-- Payments must persist its result and an outbox record before acknowledging; publish via its relay.
-- Redis can lose an acknowledged XADD on failover. Source retention and reconciliation remain necessary.How service-to-service communication is chosen in general (sync REST/gRPC vs async messaging) is in Service Communication; designing each hop for failure is in Designing for Failure & Reliable Messaging.
Distributed data: replicas, failover, Cluster and multi-region
- Replicas: reading a stream from a replica (
XREAD/XRANGE) is fine for replay and analytics; consumer groups must talk to the primary, becauseXREADGROUPwrites (PEL, cursor). Replica lag means a replica reader can be behind. - Failover: expect duplicates (lost
XACKs) and, rarely, lost newest entries. Producers that must not lose events keep them in an outbox until a reconciliation check confirms them; consumers deduplicate. - Cluster: one stream per slot; scale by more keys; keep keys that must be touched together under one hash tag; Pub/Sub at scale means sharded Pub/Sub; Horizon needs a non-cluster Redis.
- Multi-region: Redis replication is primary-replica; cross-region active-active needs a product feature outside open-source Redis (the command pages mark Active-Active compatibility for Redis Software and Redis Cloud). Most designs keep one region authoritative for a stream and replicate events onward with a relay, or move cross-region eventing to Kafka.
- Caches next to messages: never share an instance whose
maxmemory-policyevicts; a stream evicted as "least recently used" is a silent total loss.
Scaling path: 1×, 10×, 100×
| Load | Shape | What changes |
|---|---|---|
| 1× (hundreds of messages/s) | One Redis with AOF everysec, one stream per event type, one group per consumer service, 2–4 consumers | Add the reaper, XINFO alerts, MAXLEN ~ sized from MEMORY USAGE |
| 10× (thousands/s) | Dedicated messaging Redis (noeviction), replica + Sentinel, consumers scaled per group, payloads slimmed (ids + claim-check) | COUNT batching on XREADGROUP, pipelined XACKs, age trimming with MINID, per-key sharded streams where order matters |
| 100× (tens of thousands/s and beyond, long retention) | Redis Cluster with N streams per event type spread by hash tag, or move the backbone to Kafka and keep Redis for Pub/Sub and short-lived work queues | Per-stream single-node ceiling, RAM cost of retention and asynchronous failover usually decide the move |
Lab: crashed consumer recovered by XAUTOCLAIM
Expected, not run. The commands below need a local Redis 7.0+ (redis-server --appendonly yes) and three redis-cli terminals; the output shown is the expected shape taken from the command documentation, with ids written as <id1> etc. where they depend on the clock. No Docker is required, and none was started for this page.
Experiment 1: create the stream, group and three jobs.
T1 $ redis-cli XGROUP CREATE jobs workers $ MKSTREAM
OK
T1 $ redis-cli XADD jobs '*' job 1
"1764060000000-0"
T1 $ redis-cli XADD jobs '*' job 2
"1764060000001-0"
T1 $ redis-cli XADD jobs '*' job 3
"1764060000002-0"
T1 $ redis-cli XINFO GROUPS jobs
-- expected: name "workers", consumers 0, pending 0, last-delivered-id "0-0", lag 3Experiment 2: consumer C1 reads two jobs and "crashes" (never acks).
T2 $ redis-cli XREADGROUP GROUP workers c1 COUNT 2 STREAMS jobs '>'
1) 1) "jobs"
2) 1) 1) "1764060000000-0"
2) 1) "job" 2) "1"
2) 1) "1764060000001-0"
2) 1) "job" 2) "2"
-- close terminal T2: C1 is gone, its two entries stay pendingExperiment 3: consumer C2 takes the remaining job and acks it; the PEL shows C1's orphans.
T3 $ redis-cli XREADGROUP GROUP workers c2 COUNT 10 STREAMS jobs '>'
1) 1) "jobs"
2) 1) 1) "1764060000002-0"
2) 1) "job" 2) "3"
T3 $ redis-cli XACK jobs workers 1764060000002-0
(integer) 1
T3 $ redis-cli XPENDING jobs workers
1) (integer) 2
2) "1764060000000-0"
3) "1764060000001-0"
4) 1) 1) "c1"
2) "2"
T3 $ redis-cli XPENDING jobs workers - + 10
1) 1) "1764060000000-0"
2) "c1"
3) (integer) 41250 -- idle ms, grows every second
4) (integer) 1 -- delivery count
2) 1) "1764060000001-0"
2) "c1"
3) (integer) 41250
4) (integer) 1Experiment 4: too early, then a successful XAUTOCLAIM by C2.
T3 $ redis-cli XAUTOCLAIM jobs workers c2 3600000 0-0 COUNT 10
1) "0-0"
2) (empty array) -- nothing idle for an hour yet
3) (empty array)
T3 $ redis-cli XAUTOCLAIM jobs workers c2 30000 0-0 COUNT 10
1) "0-0" -- whole PEL scanned
2) 1) 1) "1764060000000-0"
2) 1) "job" 2) "1"
2) 1) "1764060000001-0"
2) 1) "job" 2) "2"
3) (empty array) -- no dangling (trimmed) ids found
T3 $ redis-cli XPENDING jobs workers - + 10
1) 1) "1764060000000-0"
2) "c2" -- new owner
3) (integer) 1200
4) (integer) 2 -- claim incremented the delivery count
...Experiment 5: finish the work, clean up the dead consumer, check lag.
T3 $ redis-cli XACK jobs workers 1764060000000-0 1764060000001-0
(integer) 2
T3 $ redis-cli XGROUP DELCONSUMER jobs workers c1
(integer) 0 -- c1 had no pending entries left
T3 $ redis-cli XINFO GROUPS jobs
... "pending" (integer) 0 "last-delivered-id" "1764060000002-0" "entries-read" (integer) 3 "lag" (integer) 0Experiment 6 (optional): trimming under a pending entry. Read one new entry as c3 without acking, run XTRIM jobs MAXLEN 0, then XAUTOCLAIM jobs workers c2 0 0-0: expected third element lists the trimmed id (IDs whose payloads were trimmed and whose PEL references were removed), and XPENDING no longer shows it. The work is lost: this is why MAXLEN must be sized above the worst backlog or ACKED used on 8.2+.
The same scenario in code: run the Go after program with REDIS_ADDR set, kill it with kill -9 after it read entries, start it again under a different consumer name, and watch the reaper log claimed ids after minIdle (30 s).
Common misconceptions
| Belief | Reality |
|---|---|
| Pub/Sub plus a worker is a queue | No storage, no ack, every subscriber gets every message; restarts lose messages |
| A subscriber that reconnects catches up | Nothing is stored; messages published while away are gone |
| Sharded Pub/Sub is durable | It only limits where messages travel in Cluster; still at-most-once |
BRPOP is safe because Redis persists the list | The popped item exists only in the crashed worker's memory |
XACK deletes the entry | It removes the id from one group's PEL; the entry stays until trimmed (XACKDEL 8.2 does both) |
| Redis redelivers unacked entries after a timeout | Never by itself; you run XCLAIM/XAUTOCLAIM (or XREADGROUP ... CLAIM on 8.4+) |
| Consumers in a group keep per-key order | Entries go to whichever consumer asks; shard by key across streams for order |
XREAD BLOCK $ in a loop sees every entry | $ means "after now"; pass the last id received |
| Trimming respects consumers | Default KEEPREF ignores PELs and unread entries; only ACKED (8.2+) waits for all groups |
appendonly yes means no message loss | everysec can lose about a second; async replication can lose more on failover |
WAIT makes Redis streams as safe as Kafka acks=all | Failover is best effort; the docs say loss becomes "very unlikely", not impossible |
| Laravel's redis queue uses streams | Lists and sorted sets via Lua; streams need the Redis facade |
A long job is safe as long as --timeout is long | If it runs past retry_after, another worker runs it again |
| Horizon works with any Redis | Not with Redis Cluster |
| A cache Redis can host the queue | With an evicting policy the stream or list key can be evicted |
Cheat sheet
| Topic | Remember |
|---|---|
| Pub/Sub | At-most-once, nothing stored, PUBLISH returns receiver count, slow subscriber cut at client-output-buffer-limit pubsub 32mb 8mb 60 |
| Sharded Pub/Sub | SPUBLISH/SSUBSCRIBE (7.0), stays in the slot's shard |
| Keyspace notifications | Off by default (notify-keyspace-events ""), node-local in Cluster, expired fires on deletion |
| Reliable list queue | BLMOVE src processing RIGHT LEFT t, LREM processing 1 job, requeue on start |
| Laravel redis driver | queues:x list, :notify list, :delayed zset, :reserved zset scored now + retry_after |
| Stream id | ms-seq, monotonic even if the clock goes back, * to generate |
| Special ids | $ new only, 0 from start / own PEL, > never delivered, -/+ range ends |
| Consumer group | XGROUP CREATE k g $ MKSTREAM, XREADGROUP GROUP g c COUNT n BLOCK ms STREAMS k >, XACK after success |
| Recovery | XAUTOCLAIM k g me min-idle 0-0 COUNT n until cursor 0-0; park when delivery count > N |
| Trimming | MAXLEN ~ n on XADD, MINID ~ ms-0 for age, ACKED (8.2) to respect groups |
| Observability | XINFO GROUPS lag + pending, XPENDING ... IDLE, XINFO CONSUMERS inactive |
| Durability | AOF everysec ≈ 1 s loss; async replication; failover best effort |
| Memory | Measure MEMORY USAGE/XLEN, cap with MAXLEN, instance noeviction |
| Cluster | One stream = one slot = one node; hash tags for keys used together; CROSSSLOT otherwise |
| Versions | XAUTOCLAIM 6.2, sharded Pub/Sub 7.0, ACKED/XACKDEL 8.2, CLAIM 8.4, IDMP 8.6, XNACK 8.8 |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A Laravel app publishes jobs with Redis::publish and one worker subscribes. The worker is redeployed for 20 seconds. What happens to jobs published meanwhile, and what does publish return? Must-know
Answer
Answer: They are lost: Pub/Sub stores nothing and is at-most-once. publish returns the number of subscribers that received each message, here 0, which is not an error.
2 — Why does BRPOP lose a job when a worker crashes, and what does BLMOVE change? Must-know
Answer
Answer: BRPOP removes the item from Redis on delivery, so after a crash it exists nowhere. BLMOVE atomically moves it to a processing list where it stays visible until LREM; a requeuer can push it back. It gives at-least-once, so the handler must be idempotent.
3 — Which keys does Laravel's redis driver use for queue default, and what happens when a job runs longer than retry_after? Important
Answer
Answer: queues:default (list), queues:default:notify (list), queues:default:delayed and queues:default:reserved (sorted sets). A reserved job's score is now + retry_after; when it passes, the next pop migrates it back to the list and another worker runs it again.
4 — What is the difference between XREADGROUP ... STREAMS k > and XREADGROUP ... STREAMS k 0? Important
Answer
Answer: > returns entries never delivered to anyone in the group and advances last-delivered-id. 0 returns this consumer's own pending entries (its PEL), used after a restart; BLOCK, NOACK and CLAIM are ignored.
5 — Consumer C1 died with 30 entries pending. Does Redis give them to C2 automatically? What do you run? Important
Answer
Answer: No; they stay pending forever. Run XAUTOCLAIM key group c2 min-idle 0-0 COUNT n in a loop until the cursor is 0-0 (or XPENDING + XCLAIM, or XREADGROUP with CLAIM on 8.4+), then process and XACK; finally XGROUP DELCONSUMER c1.
6 — Why can two consumers in one group process events of the same order out of sequence, and how do you prevent it? Important
Answer
Answer: A group hands each new entry to whichever consumer asks first; there are no partitions. Shard by key across N streams and give each stream a single active consumer.
7 — You run XADD ... MAXLEN ~ 10000 and one group is 50,000 entries behind. What happens? Good to know
Answer
Answer: Entries it has not read are trimmed and silently skipped (and pending ones become dangling ids). Size MAXLEN above the worst backlog, alert on lag, or use ACKED trimming on 8.2+.
8 — Your consumer acked an entry, then the primary failed over. Why might the entry be processed again? Good to know
Answer
Answer: Replication is asynchronous: the XACK may not have reached the replica that was promoted, so the PEL there still holds the entry and it is redelivered. Idempotent handlers make this harmless.
9 — Why must a messaging Redis use maxmemory-policy noeviction? Important
Answer
Answer: Evicting policies remove whole keys, so a stream or queue list can disappear. With noeviction, writes fail with the OOM error instead, which the producer can detect and handle.
10 — Group lag is 0 but pending is 5,000 and growing. What is wrong? Important
Answer
Answer: Entries are being delivered but not acknowledged: handlers fail without XACK (or crash), and no reaper or parking is moving them. Check delivery counts and the reaper.
11 — Name three situations where Kafka or RabbitMQ is the better choice than Redis Streams. Must-know
Answer
Answer: Acknowledged writes must survive node loss (quorum queues, acks=all); backlog or retention larger than RAM or weeks of replay (Kafka); routing, TTLs and dead-lettering as configuration (RabbitMQ); many teams with schema governance and connectors (Kafka).
Glossary
| Term | Meaning |
|---|---|
| Pub/Sub | Redis fire-and-forget broadcast to connected subscribers (PUBLISH, SUBSCRIBE, PSUBSCRIBE) |
| Channel / pattern | Pub/Sub address; patterns are glob-style (news.*) |
| Sharded Pub/Sub | SPUBLISH/SSUBSCRIBE (7.0): channel hashed to a slot, delivered within that shard |
| Keyspace notification | Pub/Sub event about key changes on __keyspace@db__:key / __keyevent@db__:event |
notify-keyspace-events | Config enabling keyspace notifications, empty by default |
| At-most-once | Delivered zero or one time; loss possible, duplicates not |
| At-least-once | Delivered one or more times; duplicates possible, loss not (barring storage loss) |
client-output-buffer-limit pubsub | Limit after which a slow subscriber is disconnected (32mb 8mb 60 default) |
| List queue | LPUSH + BRPOP; each item to one consumer, removed on pop |
BLMOVE / LMOVE | Atomic pop-and-push between lists (6.2), replacing BRPOPLPUSH/RPOPLPUSH |
| Processing list | Per-worker list holding in-progress items for the reliable list queue |
LREM | Remove occurrences of a value from a list; acks a job in the processing list |
:reserved / :delayed / :notify | Laravel redis driver keys: in-progress zset, delayed zset, token list |
retry_after | Laravel: seconds before a reserved job is released for another attempt |
block_for | Laravel: seconds to BLPOP on the notify list when the queue is empty |
| Horizon | Laravel dashboard and supervisor for the redis queue driver; not Cluster-compatible |
| Stream | Append-only log in one key; entries of field-value pairs with increasing ids |
| Entry id | <millisecondsTime>-<sequenceNumber>; * generates it |
| Macro node / radix tree | Internal stream layout; nodes bounded by stream-node-max-bytes/-entries |
XADD | Append an entry, optionally trimming (MAXLEN/MINID) and deduplicating (IDMP) |
XRANGE / XREVRANGE | Read entries by id range |
XREAD | Read entries after given ids, optionally blocking; no group state |
| Consumer group | Named cursor plus PEL on a stream; consumers share its entries |
XGROUP | Create, destroy, set id of a group; create or delete consumers |
XREADGROUP | Read as a consumer of a group; > for new entries, 0 for own pending |
last-delivered-id | Group cursor: the last entry delivered to any of its consumers |
| PEL | Pending Entries List: delivered but unacknowledged entries per group (and per consumer) |
XACK / XACKDEL | Remove ids from a group's PEL / and delete them from the stream (8.2) |
| Delivery counter | Times an entry was delivered; incremented by claims and PEL re-reads |
XPENDING | Inspect the PEL: summary or per entry with owner, idle, count |
XCLAIM / XAUTOCLAIM | Transfer pending entries idle longer than a threshold to another consumer |
XNACK | Release own pending entries back to the group (8.8), SILENT/FAIL/FATAL |
NOACK | XREADGROUP option that skips the PEL (at-most-once) |
XINFO | Introspection: STREAM, GROUPS (lag, entries-read), CONSUMERS (idle, inactive) |
| Lag | Entries in the stream not yet delivered to a group |
MAXLEN / MINID | Trim by count / by lowest id kept (age) |
~ (approximate trim) | Trim whole macro nodes only; cheaper, may keep slightly more |
KEEPREF / DELREF / ACKED | 8.2 trim/delete modes for PEL references; ACKED waits for all groups |
IDMP / IDMPAUTO | 8.6 producer deduplication on XADD |
| Dead stream | Your own stream for parked poison entries (Redis has no built-in DLQ) |
| Reaper | Your process that runs XAUTOCLAIM and parks poison entries |
AOF / appendfsync | Append-only file and its fsync policy (always, everysec, no) |
| RDB | Point-in-time snapshot persistence |
WAIT | Block until N replicas acknowledged previous writes; reduces, does not remove, failover loss |
| Hash slot / hash tag | Cluster partitioning unit (16384) / {...} part of a key that decides the slot |
CROSSSLOT | Error for multi-key commands spanning slots |
noeviction | maxmemory-policy that rejects writes instead of evicting keys |
XCFGSET / deduplication window | Time/capacity settings for IDMP; resetting configuration clears tracked IDs |
| Idempotency | Repeating the same business operation causes no additional effect |
| Outbox | Table written in the business transaction and relayed to the broker |
| Lightweight CDC | App-level change feed into a stream, as opposed to log-based CDC |
| XDEL | Delete retained entry; not proof of processing | | BLOCK | Wait for new data, in milliseconds for streams | | BUSYGROUP / NOGROUP | Group exists / group absent | | maxmemory / OOM | Memory budget / write rejection | | migrateExpiredJobs | Laravel moves due jobs back to ready list | | go-redis / phpredis | Go client / PHP extension | | Event log / fan-out | Event history / delivery to independent consumers | | entries-read | Logical count for group lag | | Reliable queue / poison message | Recoverable work / repeatedly failing payload | | Failover / Redis Cluster | Primary replacement / hash-slot distribution | | stream-node-max-bytes / stream-node-max-entries | Macro-node limits | | RPOPLPUSH / BRPOPLPUSH | Old reliable-list commands | | RabbitMQ / Kafka / NATS / Pulsar / SQS | Brokers with different contracts | | IDMP-DURATION / IDMP-MAXSIZE | Time / capacity bounds |
References
Redis documentation, Redis Streams
Redis documentation, Redis Pub/sub and Keyspace notifications
Redis commands: XADD, XREAD, XRANGE, XREADGROUP, XACK, XACKDEL, XPENDING, XCLAIM, XAUTOCLAIM, XNACK, XTRIM, XDEL, XGROUP CREATE, XGROUP SETID, XGROUP DELCONSUMER, XINFO STREAM, XINFO GROUPS, XINFO CONSUMERS, LMOVE, BLMOVE, SPUBLISH, SSUBSCRIBE
Redis documentation, Persistence, Replication, Cluster specification, Key eviction
Redis source:
redis.conf,src/t_stream.c,src/server.c,src/cluster.cgo-redis v9: repository,
pubsub.go,stream_commands.gophpredis: repository and README,
redis.stub.phpLaravel framework source (13.x):
Queue/LuaScripts.php,Queue/RedisQueue.php,Redis/Connections/PhpRedisConnection.phpRabbitMQ documentation, Quorum Queues and Dead Letter Exchanges
Apache Kafka documentation, Introduction and Topic configs
Redis documentation: XCFGSET, Redis 8.6 limitations.