Pub/Sub and StreamsLesson 4.2
Redis Streams introduction: durable append-only event logs
XADD command, stream entry ID, XLEN, XRANGE, XREAD, auto-generated IDs, stream as event log, difference from Pub/Sub
Streams: persistent messaging
A Redis Stream is an append-only log of entries. Unlike Pub/Sub, entries persist until explicitly deleted. Consumers can read from any position in history.
Writing to a stream
# '*' auto-generates a timestamp-based ID
XADD events * action "login" userId "42"
# → "1700000000000-0" (millisecond timestamp + sequence)
XADD events * action "purchase" userId "42" productId "99"
XLEN events # → 2Reading entries
# Read all entries from the beginning
XRANGE events - +
# → [[1700...-0, [action, login, userId, 42]], ...]
# Read newest entries (blocking, wait 0ms = forever)
XREAD COUNT 10 BLOCK 0 STREAMS events $Streams vs Pub/Sub
Pub/Sub delivers only to currently connected subscribers and discards the message immediately. Streams persist every entry. A consumer that goes offline and reconnects can replay missed messages from its last-seen ID. This makes Streams the right choice for audit logs, event sourcing, and reliable task pipelines where message loss is unacceptable.
