High Availability and Streams

Redis Sentinel — the summary view

Sentinel provides automatic failover for a non-clustered (single-shard) master/replica setup. Run an odd number (typically 3 or 5) on separate hosts. Detection is two-stage:

SDOWN (Subjectively Down)
  One Sentinel hasn't heard a valid PING reply within down-after-milliseconds.
  This is just that one Sentinel's opinion.

ODOWN (Objectively Down)
  Enough Sentinels (the configured quorum) independently agree on SDOWN.
  Quorum is ONLY for agreeing on the failure condition.
  1. Sentinels run leader election (Raft-like, using epoch/term numbers).
  2. The leader needs votes from a majority of all Sentinels — which is why you need ≥3.
  3. Leader picks the best replica: lowest replication lag → replica-priority → lowest runid as tiebreaker.
  4. Issues REPLICAOF NO ONE to promote, reconfigures the other replicas, updates client discovery.
sentinel monitor mymaster 10.0.0.1 6379 2     # quorum = 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1

Sentinel vs. Cluster

SentinelCluster
ShardingNone — full dataset per nodeYes — 16,384 slots across many masters
Failover run bySeparate Sentinel processesCluster nodes themselves (gossip + epoch voting)
Failure agreementquorum → ODOWN, then majority leaderMasters vote; replica claims slots with a higher configEpoch
Use whenYou need HA and the data fits one nodeYou need HA and horizontal scale

Redis Streams: A Log Inside Redis

Why it was built — the gap before Streams

Before Redis 5.0 (2018), there was no way to get "durable, replayable, multi-consumer event stream" behavior out of Redis. Lists and Pub/Sub each fail differently (next part), and the third option people reached for in production was hand-rolling it: a Sorted Set keyed by timestamp, some Lua scripts, and their own bookkeeping for "who has acked what." It worked, barely, until it didn't — no first-class persistence, no replication guarantees for the bookkeeping, and a new one reinvented per team. Streams took that recurring hack and made it a native data type.

The driver wasn't an abstract "let's add logs" itch — it was four concrete use cases people kept hitting:

  1. Chat / messaging — "show me everything I missed since I went offline." Pub/Sub structurally cannot answer this; it has zero memory. Reportedly the single biggest driver behind the design.
  2. IoT / sensor ingestion — each reading is an immutable event, and dashboarding, alerting, and long-term storage all need to consume the same feed independently, at their own pace.
  3. Reliable job processing — distributed workers where you need to detect "did this actually finish, or did the worker die mid-task?" — exactly what the PEL + XCLAIM/XAUTOCLAIM machinery below exists for.
  4. Event sourcing / activity feeds — an audit trail of what happened, not just current state, where you sometimes need to replay it: rebuild state, debug, or backfill a brand-new consumer that didn't exist when the events were created.

Why bake this into Redis instead of just running Kafka? Operational simplicity is the entire pitch. Standing up real Kafka means Zookeeper (or KRaft), a separate cluster, a different ops model, and ms-range latency instead of Redis's sub-ms. Streams gets you ordered, replayable, consumer-group-tracked, at-least-once delivery on the exact same binary, with the same sub-ms latency and the same RDB/AOF persistence and replication you already run. The trade is real — you give up partitioning, disk-tiered long retention, and exactly-once semantics (see "Where Streams fall short of Kafka" below) — but for moderate volume, it's log semantics with zero new infrastructure.

The problem — what Streams is for

Imagine you need to build a task queue where three worker processes pick up jobs, and you cannot afford to lose a single job if a worker crashes mid-processing. Now look at what Redis gives you before Streams:

ToolHow it worksWhy it fails for this use case
Lists (RPUSH / BLPOP)Push right, pop left. FIFO queue.BLPOP destroys the message on read. If the worker crashes after popping but before finishing the job — the job is gone forever. No replay, no tracking of who's working on what.
Pub/Sub (PUBLISH / SUBSCRIBE)Fire-and-forget broadcast to all currently-connected subscribers.If a subscriber is offline when the message fires — it never sees it. No persistence, no replay, no acknowledgment. It's a real-time signal, not a durable queue.

Both have the same fundamental flaw: reading destroys the data. Once consumed, there's no record of what happened. You can't ask "who processed entry #582?" or "show me everything that happened in the last hour" because the data is gone.

The idea — a log is the opposite of a queue

A log is an append-only sequence of records. Nothing is ever deleted on read — consumers track their own position (a cursor) and advance at their own pace. This is the data structure behind Kafka, behind database write-ahead logs, behind event sourcing.

Queue (List) vs. Log (Stream) — fundamentally different read semantics
Queue (List) vs. Log (Stream) — fundamentally different read semantics

This is what "a log inside Redis" means: Redis, which already holds your hashes and sorted sets and counters, now also holds an ordered, append-only, persistent sequence of events. It's a data structure (like a Hash or a List) that behaves like Kafka — but lives in a Redis key, benefits from Redis's sub-ms latency, and gets persisted via RDB/AOF alongside the rest of your data.

The one-sentence mental model: A Redis Stream is a named, ordered, append-only sequence of field-value pairs where each entry has a unique monotonically-increasing ID. Readers don't destroy — they advance a cursor.

Anatomy of a Stream entry

XADD mystream * sensor "temp" value "41.2" unit "celsius"
         │        │  └────────── field-value pairs (like a Hash) ──────────┘
         │        └── * = auto-generate ID; or specify one manually
         └── the stream key (lives in the keyspace, can have TTL, gets persisted)

Every entry gets an ID: <millisecondsTime>-<sequenceNumber>. The ID is monotonically increasing — entry N+1 always has a higher ID than entry N. This gives you total order across the entire stream.

> XADD orders * item "book" qty 2
"1700000000000-0"                         ← 1.7 trillion ms since Unix epoch, seq 0
> XADD orders * item "pen" qty 5
"1700000000000-1"                         ← same millisecond, sequence incremented
> XADD orders * item "eraser" qty 10
"1700000000001-0"                         ← next millisecond, sequence resets to 0

> XRANGE orders - +                       ← "-" = earliest, "+" = latest
1) 1700000000000-0:  item=book, qty=2     ← reads oldest to newest
2) 1700000000000-1:  item=pen, qty=5
3) 1700000000001-0:  item=eraser, qty=10

The time-based ID is not just for ordering — it means you can seek by time. Want everything after 3 PM yesterday? XRANGE orders 1690000000000 +. The stream is an index by time, for free.

Three ways to read from a Stream

ModeCommandSemanticsUse when
1. Direct readXRANGE / XREVRANGELike LRANGE — you ask for a range, you get it. Nothing is tracked.Inspecting, debugging, replaying history
2. Standalone cursorXREAD"Give me everything after ID X." You track the ID yourself in your app. No Redis-side tracking.Simple single-consumer tailing; no coordination needed
3. Consumer groupXREADGROUPRedis tracks who read what. Entries are load-balanced across consumers in the group. Redis remembers what's pending until you XACK.Distributed workers; at-least-once delivery; horizontal scale of consumption

Consumer groups — the killer feature

A consumer group is Redis tracking who consumed which entry and whether they finished processing it. This gives you three things that raw Lists and Pub/Sub cannot:

  1. Load balancing — entries are distributed across consumers in the group. Entry 0 goes to consumer-A, entry 1 to consumer-B, entry 2 to consumer-C. Each consumer gets roughly 1/N of the work.
  2. At-least-once delivery — when Redis hands entry E to consumer A, it records E in a Pending Entries List (PEL) for that consumer. The entry stays pending until A calls XACK. If A never acks (crash, bug, network), the entry can be claimed by another consumer.
  3. Fan-out — create multiple groups on the same stream. Every group gets every entry independently. Group "fraud-detection" and group "analytics" both see the full stream — each with their own load-balanced workers inside.
One stream, two consumer groups — independent consumption, independent tracking
One stream, two consumer groups — independent consumption, independent tracking
> XGROUP CREATE orders fraud-detection 0    ← 0 = consume from the very beginning
> XGROUP CREATE orders analytics 0           ← second group, independent cursor

> XREADGROUP GROUP fraud-detection consumer-A COUNT 2 BLOCK 5000 STREAMS orders >
1) orders
   1) E0: item=book, qty=2
   2) E1: item=pen, qty=5
                                                  ← E0, E1 now in consumer-A's PEL

> XREADGROUP GROUP fraud-detection consumer-B COUNT 2 BLOCK 5000 STREAMS orders >
1) orders
   1) E2: item=eraser, qty=10                    ← consumer-B gets E2 (load-balanced!)
   2) E3: item=notebook, qty=1

> XREADGROUP GROUP analytics consumer-C COUNT 5 BLOCK 5000 STREAMS orders >
1) orders
   1) E0, E1, E2, E3...                          ← consumer-C gets ALL entries (different group!)
SymbolMeaning in XREADGROUP
>"Give me entries never delivered to anyone in this group." This is how you consume new work.
0 or a specific ID"Give me entries that I (this specific consumer) was already assigned but haven't acked yet." Used on restart to reclaim your own pending work.
BLOCK 5000Long-poll for up to 5 seconds if the stream is empty — no busy-waiting, no CPU spin.

The Pending Entries List (PEL) — how at-least-once actually works

Every consumer in every group has its own PEL — a list of entry IDs that were delivered to it but not yet acknowledged. This is the mechanism that turns "fire and forget" into "deliver and confirm."

Consumer-A's PEL:
  E0: delivered 3s ago, delivered 1 time   ← healthy, still processing
  E1: delivered 120s ago, delivered 1 time  ← stuck — consumer likely crashed on this one

> XPENDING orders fraud-detection             ← inspect the whole group's backlog
> XAUTOCLAIM orders fraud-detection consumer-B 60000 0-0 COUNT 10
                                              ← "claim entries idle >60s for consumer-B"
Lifecycle of an entry through a consumer group
Lifecycle of an entry through a consumer group

Without the PEL you have at-most-once — a crash means the entry is lost. With the PEL + XAUTOCLAIM you have at-least-once — a crash means the entry is re-delivered. (For exactly-once you need idempotent processing on the consumer side; Streams won't deduplicate for you.)

Streams vs. Pub/Sub

Pub/SubStreams
PersistenceNone — fire-and-forgetStored in the keyspace; persisted via RDB/AOF
Offline subscriberMisses everythingCatches up on reconnect (replay from last ID)
Replay historyImpossibleXRANGE / re-read from any ID
Consumer groupsNo — every subscriber gets allYes — load-balanced + acked delivery
Delivery semanticsAt-most-onceAt-least-once (PEL + XACK)

Where Streams fall short of Kafka

KafkaRedis Streams
Partitioned — multiple ordered domains distributed across brokersOne key = one shard; no native sharded-partition model
Disk-based retention — weeks of data cheaplyRAM-based — must cap with MAXLEN or MINID
Tiered storage, exactly-once semantics, cross-topic transactionsNone of the above

Use Streams for a durable, replayable, consumer-grouped queue inside an existing Redis at modest volume. Reach for Kafka at high volume or long retention.