TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท redis ยท valkey ยท messaging ยท pub/sub ยท streams

Redis Streams and pub/sub

Two messaging tools inside Redis and Valkey. Pub/sub pushes each message to whoever is subscribed right now and keeps nothing; Streams are an append-only log where consumer groups share entries and acknowledge them, giving at-least-once delivery.

14 min5 animations

๐Ÿ“š Builds on๐Ÿ“ฌ Apache Kafka๐ŸŽฝ Redis and Valkey

๐Ÿ–จ๏ธ Cheat sheet

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 news listens 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 60 closes 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.

Pub/sub reaches whoever is listening now5 steps
๐ŸŽ™๏ธRadio host๐Ÿ“กRadio station๐Ÿ‘ฉListener Ana๐Ÿ‘จListener Ben
Press play and watch it happen!

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 0 reads 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.

A stream keeps every entry, in order6 steps
Ticket rail012345๐Ÿง‘โ€๐Ÿ’ผCashier Dee๐Ÿ‘ตOwner Olga
Press play and watch it happen!

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. XPENDING shows it.
  • XACK removes an entry from the PEL. It does not delete it from the stream.
  • Reading with an ID such as 0 instead 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.

A consumer group shares the entries4 steps
๐Ÿฅช Sandwich teamTicket rail012345๐Ÿง‘โ€๐ŸณServer Sam๐Ÿ‘ฉโ€๐ŸณServer Tia
Press play and watch it happen!

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 10

XAUTOCLAIM (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 sandwiches shows a growing count and a large idle time for one consumer, and the stream's lag stops falling. Fix: run XAUTOCLAIM (or XPENDING then XCLAIM) 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 with XADD, then XACK it. Redis doesn't do this itself.
  • Trimming deletes entries a slow group hasn't read. MAXLEN and MINID ignore consumer groups by default. Symptom: XREADGROUP โ€ฆ 0 returns IDs with no fields, and since Redis 7.0 XCLAIM and XAUTOCLAIM drop such IDs from the PEL (XAUTOCLAIM lists 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 added ACKED to XADD and XTRIM to trim only entries every group has acknowledged (not in Valkey).
  • A failover loses recent writes. Replication is asynchronous, so an XADD the primary acknowledged can be missing if it fails before the replica receives it; group state and XACKs 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 with WAIT numreplicas timeout after critical writes. WAIT doesn't make failover lossless. Persistence settings (AOF appendfsync) add their own window on restart.
  • Memory grows without bound. A stream keeps every entry until trimmed, XACK doesn't delete, and each unacknowledged entry also costs a PEL record. Symptom: rising used_memory, then evictions or write errors under maxmemory. Fix: trim on XADD (MAXLEN ~ or MINID ~), acknowledge promptly, and monitor the PEL size.
ChoiceYou gainYou pay
Pub/sub instead of StreamsNo storage, no acknowledgements, very simpleMissed messages while disconnected; a slow subscriber is dropped
Exact MAXLEN instead of ~The stream is never longer than the capEach trim does more work on the write path
Short vs long claim idle timeShort: stuck entries retried quickly; long: few duplicatesShort: slow-but-alive consumers get duplicates; long: entries wait after a crash
WAIT after critical writes vs notSmaller loss window on failoverHigher 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.

Claiming a stuck entry4 steps
๐Ÿฅช Sandwich teamTicket rail012345๐Ÿง‘โ€๐ŸณServer Sam๐Ÿ‘ฉโ€๐ŸณServer Tia
Press play and watch it happen!

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/subRedis StreamsKafka
StorageNoneIn memory, one key per streamOn disk, partitioned across brokers
DeliveryAt-most-once, live onlyAt-least-once with XACKAt-least-once; exactly-once within Kafka using transactions
ReplayNoYes, until trimmedYes, until retention
Work sharingNo, every subscriber gets everythingConsumer groups, any consumer takes the next entryConsumer groups, each partition read by one consumer in the group
Good forLive notificationsJob queues, modest event logs, if you already run RedisHigh-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>> {3    private final StringRedisTemplate redis;4 5    SandwichMaker(StringRedisTemplate redis) { this.redis = redis; }6 7    @Override8    public void onMessage(MapRecord<String, String, String> record) {9        makeSandwichOnce(record.getId(), record.getValue());      // idempotent10        redis.opsForStream().acknowledge("sandwiches", record);   // XACK11    }12}13 14@Bean15StreamMessageListenerContainer<String, MapRecord<String, String, String>> container(16        RedisConnectionFactory factory, SandwichMaker maker) {17    var options = StreamMessageListenerContainer.StreamMessageListenerContainerOptions18            .builder().pollTimeout(Duration.ofSeconds(2)).build();19    var container = StreamMessageListenerContainer.create(factory, options);20    container.receive(Consumer.from("sandwiches", "worker-1"),21            StreamOffset.create("orders", ReadOffset.lastConsumed()), maker);22    return 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.

๐Ÿ”ง Going deeper

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.

A Spring stream listener4 steps
๐Ÿฅช Sandwich teamTicket rail012345๐Ÿง‘โ€๐Ÿ’ผCashier Dee๐Ÿ“‹Shift manager๐Ÿง‘โ€๐ŸณServer Sam
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Redis Streams and pub/sub, told the same way as the story.
  1. Cy's radio was off when the host read out the news. He switches on a minute later. What does he hear?
  2. Sam takes ticket 3 and goes home sick without stamping it done. What happens to ticket 3?
  3. Why should a server check the counter before making a claimed order?
  4. The sandwich team and the accounting team both use the rail. Sam takes ticket 1 and stamps it done. Does accounting still see it?
  5. The rail is capped, and the oldest tickets are taken down. The sandwich team is far behind and hasn't reached ticket 5, which is now taken down. What happens to that order?
Answer every question to check.Passing marks Redis Streams and pub/sub as done.
Got the hang of Redis Streams and pub/sub? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿงฐ Caching with Redis, Valkey and HazelcastStep 6 of 8

โ† Previous on the path๐Ÿ”‘ Distributed locks with RedisNext on the path โ†’๐Ÿช Amazon ElastiCache