Redis Cheatsheet

How Redis replicates, fails over with Sentinel, shards with Cluster, persists with RDB and AOF, and evicts keys when memory is full. Each entry gives the problem, how it works, redis.conf and redis-cli examples, real-world notes and trade-offs.

Updated: 2026-10-07

5 entries

Quick tables

Reference and comparison tables for quick scanning.

Deployment modes compared

Deployment modes compared
Replica onlySentinelCluster
FailoverManualAutomatic (Sentinel promotes a replica)Automatic (replicas are elected by masters)
ShardingNo: one dataset per masterNo: one dataset per masterYes: 16384 hash slots over masters
Max datasetOne node's RAMOne node's RAMSum of the masters' RAM
Client supportAny clientSentinel-aware client to find the masterCluster-aware client (MOVED / ASK)
Multi-key commandsAll keysAll keysOnly keys in the same hash slot (use hash tags)
Extra processesNoneAt least 3 Sentinels on independent machinesNone (cluster bus on port + 10000)
Pick it whenRead scaling, warm standby, devDataset fits one node and you need HADataset or write throughput exceeds one node

Persistence options compared

Persistence options compared
OptionData you can loseWrite costRestart speedNotes
NoneEverythingNoneInstant, emptyPure cache only
RDB onlySince the last snapshot (minutes)fork() periodically, no per-write I/OFastCompact single file, ideal for backups
AOF appendfsync everysecAbout 1 secondBackground fsync each second; lowSlower (replay)Default AOF policy; good balance
AOF appendfsync alwaysAt most the last batch before the fsyncfsync per batch of commands; highSlower (replay)Group-commits parallel writes
AOF appendfsync noWhatever the OS had not flushed (~30 s on Linux)LowestSlower (replay)Fast but weakest AOF
RDB + AOFAs the AOF policyBoth costsAOF is used on restartRecommended for PostgreSQL-like safety

Replication is not a substitute for persistence: a master that restarts empty can wipe its replicas. Keep persistence on, or disable automatic restarts.

Replication

Asynchronous leader-follower replication: a command stream, partial resync from a backlog, and a full RDB resync when it falls too far behind.

The problem

One Redis instance is a single point of failure and a read bottleneck. Replication keeps live copies on other nodes for read scaling and as the material for failover — cheaply, by streaming the master's commands asynchronously.

How it works

  • A replica (`replicaof host port`) connects to the master. When the link is healthy the master streams every dataset-changing command (client writes, key expirations, evictions) to it.
  • Every master has a replication ID (a history) and an offset that grows with each byte of the stream. (ID, offset) identifies an exact version of the dataset.
  • After a disconnect the replica sends PSYNC with its replid and offset; if the master's replication backlog still holds the missing part, only that part is sent (partial resync). Otherwise a full resync happens.
  • Full resync: the master forks, writes an RDB (or streams it over the socket with diskless replication), buffers new writes, ships the RDB, then sends the buffered commands. Many replicas can share one RDB.
  • Replication is asynchronous: the master does not wait for replicas, so a write acknowledged to the client can be lost on failover. `WAIT n timeout` blocks until n replicas acknowledge — fewer lost writes, but still not a CP system.
  • `min-replicas-to-write` and `min-replicas-max-lag` refuse writes when too few replicas are close behind, bounding the data-loss window instead of letting it grow without limit.
  • Replicas are read-only by default, do not expire keys themselves (the master sends DEL), and by default ignore maxmemory (the master evicts); replicas can chain from other replicas.
  • A promoted replica starts a new replication ID but remembers the old one, so other replicas can still partially resync after a failover.
  • With persistence off on the master, an automatic restart brings it back empty and its replicas copy the emptiness. Keep persistence on, or disable auto-restart.

Examples

redis.conf on a replica and the write-safety guard on the master.

properties
# replica
replicaof 10.0.0.10 6379
replica-read-only yes

# master: refuse writes if fewer than 1 replica is within 10 s of lag
min-replicas-to-write 1
min-replicas-max-lag 10
repl-backlog-size 64mb

Check lag, then ask for stronger acknowledgement on one critical write.

bash
redis-cli INFO replication
redis-cli SET order:42 paid
redis-cli WAIT 1 100

In practice

  • Read scaling — Send slow O(N) reads to replicas, accepting small staleness; writes always go to the master.
  • Backups — Run RDB snapshots on a replica so the master avoids fork and disk I/O (keep the master's own persistence in mind).
  • Monitoring — Watch master_repl_offset vs slave_repl_offset, replication lag and `sync_full` counts; frequent full syncs mean the backlog is too small.
  • Pitfall — Treating WAIT as strong consistency: acknowledged writes can still be lost across a failover.

Trade-offs

Pros

  • Cheap, low-latency and non-blocking on the master
  • Read scaling and warm standbys with trivial configuration
  • Partial resync makes brief disconnects cheap

Cons

  • Asynchronous: acknowledged writes can be lost on failover
  • Replica reads can be stale
  • Full resyncs fork the master and move the whole dataset

High availability

Sentinels monitor a master, agree it is down by quorum, elect a leader by majority and promote a replica; clients ask Sentinel who the master is.

The problem

Plain replication does nothing when the master dies: someone has to notice, pick the freshest replica, promote it and tell every client. Sentinel automates that for a single (non-sharded) dataset.

How it works

  • Sentinel is a separate process that monitors masters and replicas, notifies you, performs automatic failover, and acts as the configuration provider clients ask for the current master address.
  • Failure detection: a Sentinel that cannot reach the master for `down-after-milliseconds` marks it subjectively down (SDOWN). When `quorum` Sentinels agree, it is objectively down (ODOWN).
  • The quorum is used only to detect the failure. To actually fail over, one Sentinel must be elected failover leader by a majority of all Sentinel processes (with 5 Sentinels and quorum 2, a failover still needs 3 reachable).
  • The leader picks a replica (by priority, replication offset and run id), promotes it with REPLICAOF NO ONE, reconfigures the other replicas, and publishes the new master with a higher configuration epoch.
  • Run at least three Sentinels on machines or zones that fail independently. Two Sentinels on the master's box die with it and cannot authorize a failover.
  • Clients must be Sentinel-aware: they connect to Sentinels, ask `SENTINEL get-master-addr-by-name`, and re-resolve on failover or connection errors.
  • Replication stays asynchronous, so acknowledged writes can be lost; `min-replicas-to-write` limits the window. A partitioned old master keeps accepting writes until it learns it was demoted.
  • Sentinel gives high availability, not sharding: the dataset still has to fit one master.

Examples

sentinel.conf: monitor a master named mymaster; 2 Sentinels must agree it is down.

properties
port 26379
sentinel monitor mymaster 10.0.0.10 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1

Ask Sentinel who the master is, and trigger a failover test.

bash
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
redis-cli -p 26379 SENTINEL replicas mymaster
redis-cli -p 26379 SENTINEL failover mymaster

In practice

  • Typical layout — 3 nodes, each running a Redis and a Sentinel: one master, two replicas, quorum 2.
  • Clients — Official clients (redis-py, go-redis, Jedis, Lettuce, ioredis) have Sentinel modes that resolve and follow the master.
  • Kubernetes — Run Sentinels as a StatefulSet across zones; the headless Service gives stable names, and announce addresses matter behind NAT.
  • Pitfall — Putting all Sentinels in one zone or on the Redis hosts with only two machines: no majority left when the box dies.

Trade-offs

Pros

  • Automatic failover without changing data model or commands
  • Simple to operate compared with Cluster; all multi-key commands still work
  • Clients discover the master dynamically

Cons

  • No sharding: capacity and write throughput are one node's
  • Asynchronous replication can lose acknowledged writes; split brain is possible until demotion
  • Needs a Sentinel-aware client and at least three well-placed Sentinels

Data is sharded over 16384 hash slots owned by masters, each with replicas; clients follow MOVED/ASK redirections and multi-key commands must share a slot.

The problem

When the dataset or write rate no longer fits one node, you must shard. Redis Cluster splits the key space over many masters, each with replicas, and handles failover itself — with no proxy in the middle.

How it works

  • The key space is split into 16384 hash slots: `HASH_SLOT = CRC16(key) mod 16384`. Each master owns a subset of slots; a cluster has at most 16384 masters, and about 1000 is the recommended ceiling.
  • Hash tags: if a key contains `{...}`, only the text inside the braces is hashed, so `{user:1}:cart` and `{user:1}:profile` share a slot. Multi-key commands, transactions and Lua scripts work only when all keys are in one slot.
  • Clients are cluster-aware: they cache the slot map, and a node that does not own a slot answers `-MOVED slot host:port` (permanent: update the map) or `-ASK` (temporary, during migration).
  • Each node opens two ports: the client port (6379) and the cluster bus (port + 10000) used for gossip, failure detection and failover. Both must be reachable between nodes; NAT and port remapping are not supported.
  • Failure detection is by gossip: a master is failed when a majority of masters have seen it unreachable for `cluster-node-timeout`; one of its replicas is then elected by the masters and promoted.
  • Resharding moves slots between masters online (`redis-cli --cluster reshard`), using MIGRATING / IMPORTING and ASK redirections; replicas can migrate to masters left without any replica.
  • Replication between nodes is asynchronous and the winner of a failover wins (“last failover wins”): there are small windows where acknowledged writes are lost, and larger ones for clients stuck in a minority partition. After `cluster-node-timeout` the minority side stops accepting writes.
  • By default (`cluster-require-full-coverage yes`) the cluster stops serving if any slot has no owner; relax it only if partial availability is acceptable.

Examples

Create a 3-master, 3-replica cluster and inspect it; -c follows redirections.

bash
redis-cli --cluster create \
  10.0.0.1:6379 10.0.0.2:6379 10.0.0.3:6379 \
  10.0.0.4:6379 10.0.0.5:6379 10.0.0.6:6379 \
  --cluster-replicas 1

redis-cli -c -h 10.0.0.1 CLUSTER KEYSLOT '{user:1}:cart'
redis-cli -h 10.0.0.1 CLUSTER NODES
redis-cli --cluster check 10.0.0.1:6379

Per-node cluster settings.

properties
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 15000
cluster-require-full-coverage yes
appendonly yes

In practice

  • Large caches and session stores — Hash tags group related keys; the keyspace is spread evenly by CRC16 so hot shards are rare.
  • Cluster-aware clients — redis-py-cluster / redis-py, go-redis ClusterClient, Lettuce and Jedis cache the slot map and follow MOVED.
  • Managed services — ElastiCache and other clouds expose cluster mode with the same slot model and resharding.
  • Pitfall — A single hot key or a huge hash tag group lands on one node: hash slots balance keys, not load.

Trade-offs

Pros

  • Linear scale of memory and write throughput over masters
  • Built-in failover and resharding without a proxy or external coordinator
  • Continues serving while a majority of masters and a replica per failed master remain

Cons

  • Multi-key operations restricted to one slot; some commands unavailable across slots
  • Asynchronous replication: acknowledged writes can be lost, more so on the minority side of a partition
  • Operationally heavier: two ports per node, cluster-aware clients, careful resharding

Durability

RDB snapshots are compact but can lose minutes; AOF logs every write and with everysec loses about a second; use both for safety.

The problem

Redis keeps data in RAM, so a restart or crash loses it unless it is written to disk. Redis offers snapshots and a write log, and the choice sets how much you can lose, how fast you restart and how much each write costs.

How it works

  • RDB: point-in-time snapshots written by a forked child (copy-on-write) every N seconds if M keys changed (`save 60 1000`), or on demand (BGSAVE). One compact file, fast restarts, perfect for backups.
  • RDB downside: after a crash you lose everything since the last snapshot (usually minutes); fork() on a big dataset can pause serving for milliseconds up to about a second.
  • AOF: logs every write command. `appendfsync everysec` (default) fsyncs each second in the background, so you can lose about one second; `always` fsyncs per batch of commands (very slow, very safe, group commit); `no` leaves flushing to the OS (~30 s on Linux).
  • AOF is append-only, so a power cut cannot corrupt it; a half-written last command is trimmed on load (redis-check-aof can fix it). The file is rewritten in the background (BGREWRITEAOF) to the minimal command set.
  • Since Redis 7.0 the AOF is multi-part: a base file (RDB or AOF format) plus incremental files tracked by a manifest, which removes the old rewrite buffering costs.
  • Redis documentation recommends using both for PostgreSQL-like safety; RDB alone is fine if a few minutes of loss is acceptable; AOF alone is discouraged because snapshots are valuable for backups and fast restarts.
  • When both are enabled, restart replays the AOF as the most complete record.
  • Backups: copy RDB files (safe while running, they are written atomically) to another host or object storage on a schedule and test restores. Replication and persistence are different tools.

Examples

A balanced durable setup: RDB for backups and fast restart plus AOF with everysec.

properties
save 3600 1 300 100 60 10000
appendonly yes
appendfsync everysec
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-use-rdb-preamble yes
dir /var/lib/redis

Trigger and check persistence work.

bash
redis-cli BGSAVE
redis-cli INFO persistence | grep -E 'rdb_last_bgsave_status|aof_enabled|aof_last_bgrewrite_status'
redis-check-aof --fix appendonlydir/appendonly.aof.1.incr.aof

In practice

  • Pure cache — No persistence (or RDB only for warm restarts); data can be rebuilt from the source of truth.
  • Session / queue / leaderboard stores — AOF everysec plus periodic RDB: at most about a second of loss, with snapshot backups off-host.
  • Monitoring — Alert on `rdb_last_bgsave_status`, `aof_last_bgrewrite_status`, `latest_fork_usec` and AOF delayed fsync counts.
  • Pitfall — Large heaps with transparent huge pages or little spare RAM make copy-on-write fork expensive: leave headroom for BGSAVE and AOF rewrite.

Trade-offs

Pros

  • RDB: compact, fast restart, easy backups, low runtime cost
  • AOF: bounded loss (about 1 s with everysec), readable and repairable log
  • Both together give safety plus fast operational tooling

Cons

  • RDB: minutes of loss and fork pauses on large datasets
  • AOF: bigger files, slower restart and some write overhead, especially with `always`
  • Neither survives disk loss without off-host backups

Memory

maxmemory plus an eviction policy (allkeys-lru, LFU, volatile-ttl, noeviction) decides what happens when Redis is full.

The problem

Redis stores everything in RAM, which is finite. Without a limit it grows until the OS kills it; with a limit it must decide what to do when full — refuse writes or throw something away. The eviction policy makes that decision explicit.

How it works

  • `maxmemory` caps the memory used for data (0 means no limit on 64-bit). When a command would exceed it, Redis applies `maxmemory-policy` until usage is back under the limit.
  • `noeviction` (the default) returns errors for writes that add data while reads keep working: right when Redis is a database, wrong for a cache.
  • `allkeys-lru` evicts the least recently used keys, a good default for caches with a hot subset; `allkeys-lfu` (Redis 4.0+) evicts the least frequently used and often gives a better hit ratio; `allkeys-random` suits uniform access; Redis 8.6 adds `lrm` (least recently modified).
  • `volatile-*` policies only consider keys that have a TTL (`volatile-ttl` evicts those closest to expiry) and behave like noeviction when no key has one; they suit a mixed cache-plus-persistent-keys instance, though two instances are cleaner.
  • LRU and LFU are approximations: Redis samples a few keys (`maxmemory-samples`, 5 by default; 10 is close to true LRU) and evicts the best candidate. LFU uses a Morris counter with `lfu-log-factor` (10) and `lfu-decay-time` (1 minute).
  • Replication and AOF buffers are not counted toward maxmemory, so leave headroom (10–30 % or more) under the host's RAM; check `mem_not_counted_for_evict`.
  • A replica ignores maxmemory by default and relies on the master's DEL commands; size replicas at least as large as the master.
  • Watch `evicted_keys` and `keyspace_hits / (hits + misses)`: many evictions with a low hit ratio mean the cache is too small or the policy does not fit the access pattern. Prefer TTLs so keys expire before they must be evicted.

Examples

A cache: bounded memory, LFU eviction, and headroom for buffers.

properties
maxmemory 6gb
maxmemory-policy allkeys-lfu
maxmemory-samples 10
lfu-log-factor 10
lfu-decay-time 1

Is the cache working? Hit ratio, evictions and memory not counted for eviction.

bash
redis-cli INFO stats | grep -E 'keyspace_hits|keyspace_misses|evicted_keys|expired_keys'
redis-cli INFO memory | grep -E 'used_memory_human|maxmemory_human|mem_not_counted_for_evict'

In practice

  • Cache tier — allkeys-lru or allkeys-lfu with TTLs on every key; monitor hit ratio and evictions.
  • Database use — noeviction so a full instance fails loudly instead of silently dropping data; alert well before 100 %.
  • Mixed instance — volatile-lru keeps persistent keys safe, but running separate cache and data instances is cleaner.
  • Pitfall — Setting maxmemory equal to the machine's RAM: buffers, fork copy-on-write and fragmentation push the process into the OOM killer.

Trade-offs

Pros

  • Predictable memory use with a policy that fits the workload
  • Approximate LRU/LFU are cheap yet close to ideal
  • noeviction protects data when Redis is the source of truth

Cons

  • Eviction can drop keys you still needed; a wrong policy tanks the hit ratio
  • maxmemory does not cover every buffer, so real usage exceeds it
  • volatile policies silently behave like noeviction when keys lack TTLs