Technical Talk · Expanded Web Edition

Redis Internals, Sentinel & Cluster.

An English, expanded edition of my earlier Redis deep-dive talk—covering why Redis behaves differently from Memcached, how its internal C data structures adapt encodings automatically, how RDB/AOF persistence and eviction work, a complete walkthrough of Redis Sentinel automatic failover & client connection discovery, and how sharding compares across Twemproxy, Codis and Redis Cluster.

  • Redis vs Memcached
  • 6 Internal Structures
  • Eviction & RDB/AOF
  • Redis Sentinel Failover
  • Client Discovery
  • Cluster vs Codis

01 · Architectural comparison

Redis vs Memcached under the hood.

Both are blazing-fast in-memory stores, yet their core engineering philosophies diverge sharply across I/O threading, memory allocation, concurrency control and feature set.

Dimension Memcached Redis
Network I/O Model Multi-threaded non-blocking I/O built on libevent: a main listener thread accepts sockets and hands descriptors via pipes to worker threads. Uses multiple CPU cores well, but introduces cache-coherency traffic and global lock contention (e.g. shared locks for global stats counters). Single-threaded I/O multiplexing via its lightweight ae event loop (epoll, kqueue, select). Zero lock overhead makes fast I/O commands fly—but heavy CPU commands (SORT, huge SUNION, KEYS *) stall all other requests. (Redis 6+ added optional I/O threads for socket reads/writes while keeping command execution single-threaded.)
Memory Management Pre-allocated slab / chunk memory pool. Eliminates malloc/free overhead and limits fragmentation, but wastes internal slack inside chunks and can trigger per-slab evictions even while other slab classes still have free memory. Allocates memory on demand (jemalloc), trading some fragmentation for flexible sizing. Tracks keys with TTL separately in an expires dict; persistent keys are never evicted under noeviction (and only eligible keys are evicted under volatile-* policies).
Data Consistency Provides built-in CAS (Check-And-Set) for optimistic lock-free concurrency control on individual keys. No standalone CAS command, but supports MULTI / EXEC transactions (atomic command batches uninterrupted by other clients), optimistic locking via WATCH, and atomic server-side Lua scripts.
Data Types & Operations Simple key-value strings only; no key enumeration, no persistence and no built-in replication. Rich native types (String, List, Hash, Set, Sorted Set…), RDB/AOF persistence, primary-replica replication, Sentinel HA and Cluster sharding. Never run KEYS * in production—use incremental SCAN or inspect offline RDB dumps.

02 · Measuring real throughput

Benchmarks, pipelining & where Redis actually slows down.

In memory, CPU execution of a single GET or SET takes microseconds—so network round trips, payload size and socket management dominate real-world performance.

Pipelining (-P 16) vs Single-Command · Xeon E5520 @ 2.27GHz
# Without pipelining (1 RTT per command)
$ ./redis-benchmark -r 1000000 -n 2000000 -t get,set,lpush,lpop -q
SET:   122,556.53 requests/sec
GET:   123,601.76 requests/sec
LPUSH: 136,752.14 requests/sec
LPOP:  132,424.03 requests/sec

# With pipelining (-P 16 commands batched per write/read)
$ ./redis-benchmark -r 1000000 -n 2000000 -t get,set,lpush,lpop -P 16 -q
SET:   552,028.75 requests/sec  (4.5× faster)
GET:   707,463.75 requests/sec  (5.7× faster)
LPUSH: 767,459.75 requests/sec  (5.6× faster)
LPOP:  770,119.38 requests/sec  (5.8× faster)
Latency Distribution · 50 Parallel Clients · 3-Byte Payload
$ redis-benchmark -n 100000

====== SET (114,293.71 req/sec · 0.88s) ======
  58.50% <= 0 ms
  99.17% <= 1 ms
  99.85% <= 3 ms
 100.00% <= 9 ms

====== GET (81,234.77 req/sec · 1.23s) ======
  43.12% <= 0 ms
  96.82% <= 1 ms
  98.62% <= 2 ms
 100.00% <= 3 ms

Throughput per Data Size (Log-Log Scale)

1 GigE vs TCP localhost vs Unix socket
1M 100k 10k 1k 100 Throughput (q/s) · log 100 B 1 KB 10 KB 100 KB Payload Data Size (bytes · log scale) Unix socket TCP localhost 1 GigE NIC 1 Gbps NIC bottleneck ~1,200 q/s @ 100 KB payload

Beware "Big Keys" Over the Network: For small payloads (100 B – 1 KB), throughput stays above 100k–200k req/s across 1 GigE, TCP localhost and Unix domain sockets. Once values grow past 10 KB → 100 KB, a 1 Gbps NIC saturates rapidly and QPS plunges toward ~1,200 req/s—100× slower—while also blocking the single event loop during serialization.

Takeaway: Keep values compact, compress large blobs client-side if necessary, and split oversized hashes/lists rather than fetching megabyte keys.

Requests per Second vs Concurrent Connections

epoll scales smoothly up to 60,000+ clients
140k 120k 100k 80k 60k 40k 20k 0 Requests / sec (QPS) 0 10k 20k 30k 40k 50k 60k 70k Simultaneous Client Connections Peak ~125k QPS Graceful epoll scaling ~49k QPS @ 62k conns

Connection Count vs QPS: Because Linux epoll scales cleanly with idle file descriptors, Redis handles tens of thousands of simultaneous clients without collapsing: throughput peaks around 110k–125k QPS at low-to-moderate concurrency and degrades gradually to ~50k QPS even at 60,000 open connections.

Takeaway: Always enable TCP keep-alive and reuse connection pools—opening a fresh TCP socket per request destroys latency far faster than maintaining pooled connections.

03 · Inside the C engine

redisObject & the 6 internal data structures.

Every value stored in Redis is wrapped in a lightweight redisObject header. By decoupling the public type (String, List, Hash, Set, ZSet) from the internal encoding, Redis automatically starts with ultra-compact memory layouts and upgrades to high-speed structures only when a key grows large.

server.h · struct redisObject (robj)
typedef struct redisObject {
  unsigned type:4;     /* String, List, Hash, Set, ZSet */
  unsigned encoding:4; /* int, embstr, raw, ziplist, dict, skiplist… */
  unsigned lru:24;     /* LRU clock or LFU 8-bit freq + 16-bit time */
  int refcount;        /* reference count for shared integers/objects */
  void *ptr;           /* pointer to the underlying data structure */
} robj;
Why dynamic encoding matters

Memory Efficiency Meets O(1) Speed

Pointer-heavy structures like hash tables and linked lists consume significant RAM per element. When a Hash or List only holds a few dozen short items, scanning a contiguous byte array (ziplist) fits inside CPU L1/L2 cache lines and cuts memory overhead dramatically.

The moment an item exceeds a configured entry count or byte threshold, Redis transparently converts the object’s encoding and ptr to a dict, linkedlist or skiplist—with zero application changes.

Structure 1 · SDS

Simple Dynamic String

Replaces raw C strings with a header storing len (used bytes, excluding \0), free (unused capacity) and buf[].

  • O(1) STRLEN & binary safety (can hold embedded null bytes).
  • Space pre-allocation & lazy freeing trade a bit of extra RAM to avoid repeated malloc/free syscalls when strings grow or shrink.
Structure 2 · Linkedlist

Doubly Linked List

Maintains head, tail, len and type callbacks (dup, free, match).

  • O(1) push/pop at both ends regardless of list size.
  • O(N) middle lookup—which is why Redis Lists intentionally do not provide an O(1) "contains member" command.
Structure 3 · Dict

Hash Table & Incremental Rehash

Powers both the top-level Redis keyspace (plus expires dict) and large Hash objects. Uses MurmurHash2 and carries two tables: ht[0] (active) and ht[1] (rehash target), tracked by rehashidx.

  • Grows to the next 2ⁿ ≥ used × 2 when load factor exceeds threshold; shrinks when load factor < 0.1.
  • Progressive rehashing migrates buckets incrementally across normal reads/writes so the single event loop never freezes.
Structure 4 · SkipList

Probabilistic Skip List

An ordered linked list layered with randomized express forward pointers, achieving O(log N) average search, insert and delete—rivaling balanced trees with simpler range scans.

  • Stores span counts on each level so ZRANK computes rank in O(log N).
  • Allows duplicate score values (broken by lexicographical member) and adds a level-1 backward pointer for ZREVRANGE.
Structure 5 · Intset

Compact Integer Set

A sorted contiguous integer array whose element width adapts automatically across int16, int32 and int64.

  • When an inserted integer exceeds the current bit width, Redis reallocates the array and upgrades all existing items cleanly.
  • Upgrades are one-way (no automatic downgrade on delete).
Structure 6 · Ziplist

Memory-Packed Ziplist

A single contiguous byte block (zlbytes | zltail | zllen | entry… | zlend). Each entry records previous_entry_length (for reverse traversal), encoding and content.

  • Cascade update edge case: Inserting/deleting an item near 250–253 bytes can expand the next node’s previous_entry_length from 1 to 5 bytes, rippling down consecutive boundary-sized entries. (Redis 7 replaced ziplist with listpack to eliminate cascade updates.)

04 · Types, encodings & thresholds

Five core data types & when their encodings convert.

Select any Redis data type below to inspect its internal encodings, default conversion thresholds from redis.conf, time complexities and classic production patterns.

Interactive Redis Type & Encoding Explorer

05 · Operations & durability

Memory eviction policies & persistence (RDB vs AOF).

Running Redis safely in production requires deciding two things up front: what happens when RAM hits maxmemory, and how much data loss (if any) you can tolerate on restart.

Memory limits · maxmemory-policy

All 8 Eviction Policies

Always set maxmemory explicitly (note: in redis.conf, 1k = 1000 bytes whereas 1kb = 1024 bytes; 1gb = 1024³ bytes). When full, Redis applies your chosen policy:

PolicyBehavior When Memory Is Full
noevictionDefault. Never evicts; returns OOM errors on writes.
allkeys-lruEvicts least-recently-used key across all keys (great for pure caches).
volatile-lruEvicts approximated LRU key only among keys with a TTL.
allkeys-lfuEvicts least-frequently-used key across all keys (resists one-off scan bursts).
volatile-lfuEvicts approximated LFU key only among keys with a TTL.
volatile-ttlEvicts the TTL key closest to expiring.
allkeys-random / volatile-randomEvicts a random key (all keys or TTL-only).
Persistence · RDB snapshots & AOF log

Balancing Fast Restarts vs Durability

RDB (Point-in-Time Snapshot): Compact LZF-compressed binary dump (dump.rdb) created via background fork(). Fast to back up and fast to reload, but writes since the last snapshot can be lost on a crash.

AOF (Append-Only File): Logs every write command sequentially (appendonly.aof). With appendfsync everysec, at most ~1 second of writes is at risk; periodic BGREWRITEAOF compacts history. (Modern Redis also supports hybrid RDB+AOF files for fast restarts with low loss.)

redis.conf · Persistence essentials
# RDB snapshot triggers (seconds, changes)
save 900 1       # 1+ change in 15 min
save 300 10      # 10+ changes in 5 min
save 60 10000    # 10,000+ changes in 60s
# save ""        # disable RDB entirely
dbfilename dump.rdb
rdbcompression yes  # LZF compression

# AOF write-ahead log
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec

06 · High availability & automatic failover

Primary-Replica replication, Redis Sentinel & client discovery.

Plain Primary-Replica replication copies data asynchronously to standby replicas and scales read throughput—but if the Primary crashes, writes stop until an engineer manually promotes a replica and updates every application’s connection string. Redis Sentinel automates health checks, quorum-based failover, and live client service discovery.

Step 1 · Basic Primary-Replica config

Setting Up Replication

The Primary needs no special replication config. Each Replica points to the Primary (using replicaof, or legacy slaveof) and serves read-only traffic while syncing changes asynchronously over a replication backlog buffer (PSYNC supports partial resync on brief disconnects; full RDB sync runs on first join):

Replica redis.conf
replicaof 10.0.1.10 6379   # legacy: slaveof <ip> <port>
masterauth <primary-password>
replica-read-only yes      # legacy: slave-read-only yes
replica-priority 100       # lower = preferred for promotion (0 = never)
Step 2 · Sentinel quorum config

Configuring a 3-Node Sentinel Cluster

Always deploy an odd number of Sentinel processes (minimum 3) on separate hosts/AZs. Sentinel fulfills four roles: Monitoring, Notification, Automatic Failover, and Configuration Provider for clients.

sentinel.conf (port 26379)
# Watch logical group "mymaster" with quorum = 2 of 3 Sentinels
sentinel monitor mymaster 10.0.1.10 6379 2
sentinel auth-pass mymaster <primary-password>
sentinel down-after-milliseconds mymaster 5000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 60000

# On Redis Primary: guard against split-brain writes
min-replicas-to-write 1
min-replicas-max-lag 10

Redis Sentinel High-Availability Topology & Client Discovery Flow

Sentinels coordinate failover & discovery—actual data traffic goes directly from Client to Redis
Application Clients Lettuce · StackExchange.Redis REDIS SENTINEL QUORUM (3 NODES · PORT 26379) Sentinel 1 :26379 Sentinel 2 :26379 Sentinel 3 :26379 1. Discover +switch-master PING / INFO / PubSub gossip Redis Primary 10.0.1.10:6379 Reads & Writes Redis Replica 1 10.0.1.11:6379 Async sync · Read-only Redis Replica 2 10.0.1.12:6379 Async sync · Read-only 2. Direct Data Connection Verify ROLE == master REDIS DATA PLANE · LOGICAL GROUP "mymaster"

Key misconception cleared: Redis Sentinel is not a data proxy. Clients ask Sentinels for the current Primary address (and listen for failover events), then open normal high-speed connections straight to Redis.

Interactive Walkthrough · Primary-Replica Switchover

Step-by-Step Redis Sentinel Automatic Failover

How the Leader Sentinel Chooses Which Replica Becomes the New Primary

Sentinels do not pick randomly. After filtering out disconnected replicas or those that have been out of touch with the old Primary for too long, the Leader Sentinel sorts remaining candidates in strict order: (1) lowest non-zero replica-priority (default 100; 0 means never promote), (2) highest replication offset (the replica that has received the most recent writes), and (3) lowest lexicographical runid as a deterministic tie-breaker.

How Clients Connect Through a Sentinel Cluster

Instead of hard-coding a Redis IP address, your application gives a Sentinel-aware Redis driver a list of Sentinel addresses and the logical group name (e.g. mymaster). Under the hood, every mature client follows the same five-step discovery protocol:

Step 1

Query Any Reachable Sentinel

The client iterates through its configured Sentinel seed list (s1:26379, s2:26379, s3:26379) and asks the first responsive node: SENTINEL get-master-addr-by-name mymaster.

Step 2

Connect & Verify ROLE

The client opens a direct socket to the returned ip:port and sends ROLE to confirm it really is a master—preventing accidental writes to a stale, partitioned old Primary.

Step 3

Subscribe to +switch-master

A background connection subscribes to Sentinel’s +switch-master Pub/Sub channel (and also refreshes the Sentinel list via SENTINEL sentinels mymaster) to receive instant failover broadcasts.

Step 4

Automatic Pool Rebind

When a failover occurs—or if a write receives a connection reset or READONLY error—the client drops stale pooled sockets, resolves the new Primary from Sentinel, and resumes traffic automatically.

Java · Spring Boot + Lettuce (Sentinel + Replica Reads)
# application.yml
spring:
  data:
    redis:
      password: ${REDIS_PASSWORD}
      sentinel:
        master: mymaster
        nodes:
          - 10.0.1.21:26379
          - 10.0.1.22:26379
          - 10.0.1.23:26379

// Optional: route read commands to replicas with Lettuce
var clientConfig = LettuceClientConfiguration.builder()
    .readFrom(ReadFrom.REPLICA_PREFERRED)
    .build();
C# / .NET · StackExchange.Redis Sentinel Discovery
var options = new ConfigurationOptions
{
    ServiceName = "mymaster",
    Password = Environment.GetEnvironmentVariable("REDIS_PASSWORD"),
    AbortOnConnectFail = false,
    EndPoints =
    {
        { "10.0.1.21", 26379 },
        { "10.0.1.22", 26379 },
        { "10.0.1.23", 26379 }
    }
};

// Discovers active primary & auto-switches on +switch-master
var mux = await ConnectionMultiplexer.ConnectAsync(options);
IDatabase db = mux.GetDatabase();
Production Note: Sentinel Solves Availability, Not Write Sharding

A Sentinel topology still has one active Primary holding the entire dataset in RAM. When your dataset outgrows a single host’s memory or write throughput saturates one CPU core, you need horizontal sharding—covered next.

07 · Scaling memory & writes horizontally

Redis sharding: Client-side, Proxy (Twemproxy / Codis) & Redis Cluster.

When a single Primary can no longer fit all keys in memory or handle peak write QPS, Redis can be partitioned across multiple shards using three distinct architectural models.

Model 1 · Application router

Client-Side Sharding

The Redis client hashes each key locally (e.g. consistent hashing) and routes directly to the target Redis instance with zero middleware hops.

  • Pros: Fully transparent logic, no extra proxy infrastructure.
  • Cons: Static topology—adding or removing nodes requires manual rebalancing and coordinated code/config deploys; hard to keep sharding logic identical across Java, C#, Python and Go services.
Model 2 · Middleware proxy

Proxy Mode (Twemproxy & Codis)

Stateless proxies sit between apps and Redis shards, speaking the standard Redis protocol so applications treat the entire fleet like one giant single-node Redis.

  • Twemproxy: Lightweight and fast, but cannot reshard live without restarting.
  • Codis: Combines stateless codis-proxy, a web dashboard (codis-config), a slot-aware codis-server fork supporting online atomic migration, and ZooKeeper to sync routing metadata across proxies.
Model 3 · Official decentralized

Redis Cluster (16,384 Hash Slots)

Decentralized peer-to-peer cluster with no central proxy. Every key maps to one of 16,384 hash slots via CRC16(key) mod 16384, with nodes exchanging membership and slot maps via Gossip.

  • Smart clients: Cache the slot → node map locally; if topology shifts, a node returns a MOVED or ASK redirect so the client updates its map automatically.
  • Hash tags: Wrap a shared substring in braces like user:{42}:profile and user:{42}:cart so multi-key commands land on the same slot.
Capability (Slide 46 Comparison) Codis Twemproxy Redis Cluster
Online resharding without restarting cluster Yes No Yes
Pipelining support Yes Yes Per-node / smart client
Hash tags {tag} for multi-key operations Yes Yes Yes
Multi-key operations during live resharding Yes N/A (static) Restricted (CROSSSLOT / ASK)
Redis client compatibility Any standard client Any standard client Cluster-aware client required

Explore Related Architecture Talks

Caching pairs directly with Web Scale-Out & Database Tuning.

See how Redis caching fits into the wider backend scaling story—protecting MySQL connection limits, eliminating slow queries with EXPLAIN, and scaling stateless web fleets behind L2/L4/L7 load balancers.