The radio show
On a busy high street there's a little radio station. The host reads out news on one channel, and anyone with a radio tuned to that channel hears it at the same moment.
That's the whole deal. If your radio was off, you missed it: there's no recording to play back later. If nobody is listening, the host's words just go out into the air. And if one listener's old radio is so slow that unheard words keep piling up for it, the station cuts that radio off, so one slow listener can't jam the whole station.
The radio is quick and simple. It's great for "something just happened" news, where missing a bit is fine.
Pub/sub: fire and forget
Redis and Valkey have two built-in ways to pass messages. Redis pub/sub delivers messages from publishers to every client currently subscribed to a channel.
SUBSCRIBE newslistens on a channel;PSUBSCRIBE news.*listens on every channel matching a glob pattern.PUBLISH news "hello"pushes the message to all current subscribers and returns how many received it. With no subscribers it returns 0 and the message is gone.- Nothing is stored. A subscriber that is disconnected, even for a second, misses whatever was published meanwhile. Delivery is at-most-once, with no acknowledgements and no replay.
- Slow subscribers are disconnected. Messages wait in the client's output buffer, and the default
client-output-buffer-limit pubsub 32mb 8mb 60closes the connection if the buffer passes 32 MB, or stays above 8 MB for 60 seconds.
In RESP2 a subscribed connection can only run the (un)subscribe commands, PING, RESET and QUIT (RESP3
lifts this), so clients usually use a dedicated connection for it. In a cluster, classic PUBLISH is broadcast to every node; sharded pub/sub
(SSUBSCRIBE, SPUBLISH, added in Redis 7.0) keeps a channel's traffic on the shard that owns its slot.
Use pub/sub for live notifications, cache invalidation and chat-style fan-out, where a missed message is acceptable or recoverable by other means.
The deli ticket rail
Next door is a deli. When you order, the cashier writes your order on a ticket and pins it at the end of a long metal rail, which is called the stream. Tickets go on in order and stay pinned, so nothing is missed if nobody looks for a minute.
Every ticket gets a number stamped by the clock: the time it was pinned, plus a small extra number if two tickets were pinned in the same moment. So tickets are always in order, and each has its own number.
Anyone can walk past and read the rail. The owner, Olga, keeps a tally of what sells. She remembers the last ticket number she read, and next time she reads only the newer ones. Reading a ticket doesn't take it off the rail. Olga can even wait by the rail until a new ticket goes up.
The rail isn't endless. When it gets long, the oldest tickets are taken down to make room.
Streams: an append-only log
A Redis stream is a data type: an append-only log of entries stored under one key. Each entry is a set of field-value pairs with a unique, increasing ID.
1XADD orders * item ham size large -> "1718000000000-0"*lets Redis generate the ID as<milliseconds>-<sequence>: the server time in milliseconds plus a counter for entries added in the same millisecond. IDs only grow, so the stream is ordered by them.XRANGE orders - +reads a range;XREAD COUNT 10 STREAMS orders 0reads entries after an ID. Reading removes nothing, and the reader remembers the last ID it saw.XREAD BLOCK 5000 STREAMS orders $waits up to 5 seconds for entries newer than the current last one.$means "only what arrives from now on".
A stream keeps everything until you trim it. XADD orders MAXLEN ~ 10000 * ... caps it at roughly 10,000
entries, and MINID trims by ID, so by age. The ~ lets Redis trim whole internal nodes, which is much
cheaper than an exact cut, so the stream may hold a few more entries than the limit. XTRIM does the same on
its own.
Streams live in memory, like every Redis key, and one stream key lives on one node. Durability comes from Redis persistence and replication, not from the stream itself.
Teams of servers
Plain reading is fine for a tally, but sandwiches need making, and each sandwich should be made once. So the deli has a sandwich team, a group of servers that share the work, called a consumer group. Each server takes the next ticket nobody on the team has taken yet, so no two servers make the same order. The team keeps a marker on the rail just after the last ticket it handed out, so everyone knows where the next one is.
The team keeps a clipboard of tickets that are taken but not finished, with who has each one. When Sam hands over a sandwich, he stamps his ticket done and it comes off the clipboard. The ticket itself stays on the rail.
The accounting team, with Ali, works from the same rail with its own marker and its own clipboard. The sandwich team taking a ticket doesn't hide it from accounting.
Consumer groups
A consumer group lets several consumers share one stream, with each entry delivered to one consumer in the group.
1XGROUP CREATE orders sandwiches $ MKSTREAM2XREADGROUP GROUP sandwiches sam COUNT 1 BLOCK 5000 STREAMS orders >3XACK orders sandwiches 1718000000000-0
- The group stores a last delivered ID. Reading with
>returns entries after it and moves it forward, so two consumers never get the same new entry. - Every delivered entry goes into the group's pending entries list (PEL), with the consumer that owns it,
the time it was delivered and a delivery count.
XPENDINGshows it. XACKremoves an entry from the PEL. It does not delete it from the stream.- Reading with an ID such as
0instead of>returns the consumer's own pending entries. A consumer that restarts reads its history first, then switches to>.
Groups are independent: each has its own last delivered ID and PEL, so sandwiches and accounting each
see every entry. Within a group, consumers are named by the client and created on first use, and there's no
partition assignment like in Kafka: any consumer can take the next entry.
When the deli has a bad day
Sometimes a server takes a ticket and then never finishes: Sam feels faint and goes home with order 1 on the clipboard under his name. The ticket is still on the rail, but nobody else will pick it up on their own.
So every now and then, another server checks the clipboard for tickets that have sat untouched too long and claims them. Tia takes over Sam's ticket and makes the sandwich. The wait is a choice: check too soon and Tia grabs a ticket Sam is still working on, so the order is made twice. Check too late and a customer waits.
But maybe Sam did make that sandwich before he left, and just didn't stamp it. Then the order gets made twice. That's why careful servers glance at the counter first: "is order 1 already done?" A ticket may be handled more than once, but it is never just forgotten. And if one ticket is so odd that every server who takes it gives up, the servers pin it on a "problem tickets" board themselves after a few tries, instead of passing it around forever.
Two more bad days. The rail only has room for so many tickets, so when it's full the oldest are taken down, even one the sandwich team hasn't reached yet, and that order is simply gone. And a power cut can wipe out the last few moments of the cashier's notes: tickets the cashier said were pinned may not be on the backup rail.
The rail keeps every ticket, stamped or not, until someone takes old ones down, and every unstamped ticket also adds a line to the clipboard. With nobody tidying, the deli fills up. The radio has its own bad day, described earlier: miss the show and it's gone.
What can go wrong
Pub/sub's failures (a disconnected subscriber misses messages, a slow one is cut off) are covered in
the pub/sub topic above, so this is about Streams. If a consumer crashes after reading but
before XACK, its entries stay in the PEL forever. Redis doesn't time them out or redeliver them on its own.
1XAUTOCLAIM orders sandwiches tia 60000 0-0 COUNT 10XAUTOCLAIM (Redis 6.2 and later) scans the PEL from an ID and transfers entries idle for longer than the
given milliseconds to the calling consumer, returning them and a cursor to continue from. It's the
cursor-style form of XPENDING followed by XCLAIM. Claiming increments the delivery count (unless JUSTID
is used). Since Redis 8.4, XREADGROUP โฆ CLAIM min-idle-time can fold this into the normal > read (Valkey
doesn't have it).
The result is at-least-once delivery: an entry processed but not acknowledged is processed again by whoever claims it. Make handlers idempotent (for example, key the side effect on the entry ID or an order id) and acknowledge only after the work is done.
Failure modes:
- A consumer dies holding pending entries. The entries sit in its PEL and nothing else reads them.
Symptom:
XPENDING orders sandwichesshows a growing count and a large idle time for one consumer, and the stream's lag stops falling. Fix: runXAUTOCLAIM(orXPENDINGthenXCLAIM) from a healthy consumer on a schedule. Claiming a live consumer's entry gives a duplicate, so pick the idle time with care. - A poison entry. An entry that crashes every consumer is claimed again and again. Symptom: one ID with a
delivery count that keeps rising (shown by
XPENDING) while consumers restart in a loop. Fix: past a limit you choose, copy the entry to a dead-letter stream withXADD, thenXACKit. Redis doesn't do this itself. - Trimming deletes entries a slow group hasn't read.
MAXLENandMINIDignore consumer groups by default. Symptom:XREADGROUP โฆ 0returns IDs with no fields, and since Redis 7.0XCLAIMandXAUTOCLAIMdrop such IDs from the PEL (XAUTOCLAIMlists them as deleted), so the work is silently lost. Fix: size the cap for your slowest group and alert on its lag. Redis 8.2 addedACKEDtoXADDandXTRIMto trim only entries every group has acknowledged (not in Valkey). - A failover loses recent writes. Replication is asynchronous, so an
XADDthe primary acknowledged can be missing if it fails before the replica receives it; group state andXACKs can be lost too. Symptom: after promotion, recent entries are gone, or acknowledged ones are delivered again. Fix: accept it and keep handlers idempotent, or narrow the window withWAIT numreplicas timeoutafter critical writes.WAITdoesn't make failover lossless. Persistence settings (AOFappendfsync) add their own window on restart. - Memory grows without bound. A stream keeps every entry until trimmed,
XACKdoesn't delete, and each unacknowledged entry also costs a PEL record. Symptom: risingused_memory, then evictions or write errors undermaxmemory. Fix: trim onXADD(MAXLEN ~orMINID ~), acknowledge promptly, and monitor the PEL size.
| Choice | You gain | You pay |
|---|---|---|
| Pub/sub instead of Streams | No storage, no acknowledgements, very simple | Missed messages while disconnected; a slow subscriber is dropped |
Exact MAXLEN instead of ~ | The stream is never longer than the cap | Each trim does more work on the write path |
| Short vs long claim idle time | Short: stuck entries retried quickly; long: few duplicates | Short: slow-but-alive consumers get duplicates; long: entries wait after a crash |
WAIT after critical writes vs not | Smaller loss window on failover | Higher write latency, and still not lossless |
In Java, record the entry ID as processed only after the side effect succeeds, ideally in the same transaction as the side effect, or with opsForValue().setIfAbsent(key, "1", ttl) (Redis SET โฆ NX EX) used as a claim and deleted if the work fails. Spring's StreamMessageListenerContainer doesn't claim for you, so run XAUTOCLAIM from a scheduled job.
Choosing, and the Java helpers
So which one should the street use? The radio, when news is only useful right now and missing a bit is fine. The ticket rail, when every order must be made and nobody may be forgotten. And for a whole chain of shops with years of tickets, a much bigger ticket system, built for that.
In a Java program you don't stand at the rail yourself. Spring gives you a shift manager, called a listener container, who keeps checking the rail for your team, hands each new ticket to your method (Sam, in our deli), and your method stamps it done when the sandwich is made.
Pub/sub, Streams or Kafka
| Pub/sub | Redis Streams | Kafka | |
|---|---|---|---|
| Storage | None | In memory, one key per stream | On disk, partitioned across brokers |
| Delivery | At-most-once, live only | At-least-once with XACK | At-least-once; exactly-once within Kafka using transactions |
| Replay | No | Yes, until trimmed | Yes, until retention |
| Work sharing | No, every subscriber gets everything | Consumer groups, any consumer takes the next entry | Consumer groups, each partition read by one consumer in the group |
| Good for | Live notifications | Job queues, modest event logs, if you already run Redis | High-volume event streams, long history |
Everything here works the same on Valkey, which forked from Redis 7.2.4 and keeps these commands.
Streams in Spring Data Redis
RedisTemplate.opsForStream() (or StringRedisTemplate) wraps the stream commands:
1redis.opsForStream().add("orders", Map.of("item", "ham", "size", "large")); // XADD2redis.opsForStream().createGroup("orders", ReadOffset.from("0"), "sandwiches"); // XGROUP CREATE, once
A StreamMessageListenerContainer runs the XREADGROUP polling loop on its own thread and calls your
StreamListener:
1@Component2class SandwichMaker implements StreamListener<String, MapRecord<String, String, String>> {3private final StringRedisTemplate redis;45SandwichMaker(StringRedisTemplate redis) { this.redis = redis; }67@Override8public void onMessage(MapRecord<String, String, String> record) {9makeSandwichOnce(record.getId(), record.getValue()); // idempotent10redis.opsForStream().acknowledge("sandwiches", record); // XACK11}12}1314@Bean15StreamMessageListenerContainer<String, MapRecord<String, String, String>> container(16RedisConnectionFactory factory, SandwichMaker maker) {17var options = StreamMessageListenerContainer.StreamMessageListenerContainerOptions18.builder().pollTimeout(Duration.ofSeconds(2)).build();19var container = StreamMessageListenerContainer.create(factory, options);20container.receive(Consumer.from("sandwiches", "worker-1"),21StreamOffset.create("orders", ReadOffset.lastConsumed()), maker);22return container;23}
The container is a SmartLifecycle bean, so Spring starts it with the context and stops it on shutdown.
ReadOffset.lastConsumed() with a Consumer means >: new entries for the group. receiveAutoAck(...)
acknowledges on delivery instead, which is simpler but loses at-least-once if your handler then fails. The
container doesn't claim other consumers' stuck entries, so schedule an XAUTOCLAIM job yourself.
For pub/sub, redis.convertAndSend("news", "hello") publishes and a RedisMessageListenerContainer holds the
subscriber connection and calls your MessageListener.
Errors stop the subscription: by default the container cancels a subscription when polling or your
listener throws. Register with
container.register(StreamReadRequest.builder(offset).consumer(consumer).autoAcknowledge(false).cancelOnError(e -> false).build(), maker)
to keep it running, and handle failures in your listener.
Group must exist: XREADGROUP fails with NOGROUP if the group hasn't been created, and XGROUP CREATE
fails with BUSYGROUP if it already exists. Create it at startup and ignore BUSYGROUP.