Skip to main content

Redis Deep Dive

Learning objectives
  • Pick the right Redis data structure for sessions, carts, counters, queues, leaderboards and cardinality estimates
  • Explain the single-threaded execution model and why one slow command hurts every client
  • Choose persistence (RDB, AOF, both, none) and replication settings for a stated loss tolerance
  • Explain Redis Cluster hash slots, hash tags and redirects, and Sentinel failover
  • Implement atomic patterns with Lua: token-bucket rate limiting, safe lock release, idempotency, stock decrement
  • Configure memory limits and eviction, and avoid big keys, hot keys and blocking commands

TL;DR​

  • Redis is an in-memory data structure server: strings, hashes, lists, sets, sorted sets, streams, HyperLogLog, bitmaps, geo. Choosing the structure is the data model.
  • Commands execute one at a time on a single thread, so each command is atomic, and one slow command (KEYS, a huge DEL, a long Lua script) stalls everyone. I/O threads (6.0+) only parallelize socket reads and writes.
  • Persistence: RDB snapshots (compact, may lose minutes), AOF with appendfsync everysec (may lose about a second), or both. Replication is asynchronous: a failover can lose acknowledged writes.
  • Cluster splits keys into 16,384 hash slots (CRC16(key) mod 16384); multi-key operations need keys in the same slot, which hash tags ({order:9001}:lines) guarantee.
  • Lua scripts and functions run atomically: use them for check-and-set logic (rate limiters, compare-and-delete locks, conditional decrements).
  • Treat Redis as a cache, coordinator and fast-path store, not the system of record for money. Back critical invariants (idempotency, stock, balances) with database constraints.
  • Set maxmemory and an eviction policy deliberately; find big keys and hot keys before they find you; never run KEYS in production.

Why it matters​

Almost every bank and e-commerce platform runs Redis: session stores, product and price caches, rate limiters at the API gateway, OTP and login-attempt counters, flash-sale stock gates, idempotency fast paths, leaderboards for promotions, and lightweight queues. Because it is fast and simple, it ends up on the critical path of checkout and login, and its failure modes become your outages: a cache stampede after a restart, a hot key during a sale, a KEYS * from a debug script freezing the cluster, a failover that silently dropped lock or stock updates. Interviewers want to see that you use Redis deliberately and know where its guarantees end.

Core concepts​

Data structures and when to use them​

TypeKey operations (complexity)Use cases
StringGET, SET … EX … NX, INCR/INCRBY O(1); up to 512 MBCached JSON, counters, locks, idempotency markers, feature flags
HashHSET, HGET, HINCRBY O(1); HGETALL O(n)Session objects, cart (field = SKU, value = quantity), per-user rate counters
ListLPUSH/RPOP O(1), BLMOVE blocking, LRANGE O(n)Simple queues, recent-items lists (capped with LTRIM)
SetSADD, SISMEMBER O(1), SINTERUnique visitors per day (small scale), tags, "already notified" sets
Sorted setZADD, ZINCRBY, ZRANK O(log n), range by score or rankLeaderboards, delayed jobs (score = due time), sliding-window rate limits, top-N
StreamXADD, XREADGROUP, XACK, XAUTOCLAIMDurable-ish event log with consumer groups, pending-entry tracking
HyperLogLogPFADD, PFCOUNT, PFMERGE; ≤ 12 KB per key, ≈ 0.81% standard errorApproximate unique counts: distinct buyers per campaign, unique card numbers per merchant per day
BitmapSETBIT, GETBIT, BITCOUNT, BITOPDaily active users by numeric user id, feature-enabled flags, attendance-style data
GeoGEOADD, GEOSEARCHNearest stores or pickup points

Implementation details that matter for memory: small hashes, lists, sets and sorted sets use compact encodings (listpack, previously ziplist; intset for small integer sets) until they exceed thresholds such as hash-max-listpack-entries (128 by default), after which they switch to hash tables or skip lists and use several times more memory. Keeping many small hashes can be far cheaper than many top-level keys. Sorted sets are a skip list plus a hash table, which is why rank and range operations are O(log n).

Streams deserve a note: they persist like any other key and support consumer groups with acknowledgements and a pending-entries list, which makes them better than lists or Pub/Sub for work queues. But they inherit Redis's durability limits, so for payment events prefer Kafka or an outbox (see Message Queues & Event Streaming). Pub/Sub is fire-and-forget: disconnected subscribers miss messages.

Execution model​

  • Atomicity per command comes for free: INCR, SET NX, ZINCRBY cannot interleave with other commands.
  • Latency is shared: an O(n) command over a million-element collection blocks all clients for its duration. Typical simple commands take microseconds; throughput of the order of 100k operations per second per instance is common, and pipelining pushes it higher (rough; depends on hardware, payload size and network).
  • Background threads handle work that can be deferred: UNLINK and FLUSHALL ASYNC free memory in the background (lazy free), AOF fsync happens off the main thread.
  • Pipelining sends many commands without waiting for each reply; it cuts round trips, not server work. It is not atomic.

Persistence​

ModeHowLoss on crashCosts
NonePure in-memoryEverythingNone; acceptable for caches you can rebuild
RDB snapshotsBGSAVE forks a child that writes a compact point-in-time file, triggered by save rules or replicationSince the last snapshot (often minutes)fork() latency on large datasets; copy-on-write can temporarily use much more memory under heavy writes
AOFAppends every write command; appendfsync always / everysec (default) / no; background rewrite compacts iteverysec: about one second of writes; always: little, at a large throughput costLarger files, rewrite overhead; Redis 7 uses a multi-part AOF with a base file plus incremental files
RDB + AOFAOF with an RDB preamble (default when AOF is on)Like AOFFast restarts and small loss window

Operational notes: set vm.overcommit_memory = 1 on Linux so fork() does not fail, disable transparent huge pages (they make copy-on-write expensive), leave memory headroom for snapshots, and watch latest_fork_usec in INFO.

Replication and Sentinel​

  • Replicas connect to the primary, receive a full snapshot, then a continuous stream of commands. A brief disconnection resumes from the replication backlog (repl-backlog-size, small by default; increase it so reconnects do not trigger full resyncs).
  • Replication is asynchronous. WAIT numreplicas timeout blocks until replicas acknowledge, reducing but not eliminating loss: a failover can still promote a replica that missed writes.
  • min-replicas-to-write / min-replicas-max-lag make a primary refuse writes when it cannot reach enough replicas, which bounds how long an isolated old primary accepts writes that will be lost.

Sentinel provides HA for non-cluster deployments: three or more Sentinel processes monitor the primary; when a quorum agrees it is down, they elect a leader Sentinel, which promotes a replica and reconfigures the others; clients ask Sentinels for the current primary address.

Redis Cluster​

  • The keyspace is split into 16,384 hash slots: slot = CRC16(key) mod 16384. Each primary owns a subset of slots and has replicas; failover is decided by a majority of primaries via the cluster bus (gossip), without Sentinel.
  • Clients are cluster-aware: they cache the slot map; a node that does not own a key replies MOVED (slot lives elsewhere permanently) or ASK (slot is being migrated), and the client retries at the right node.
  • Multi-key commands, transactions and Lua scripts must touch keys in a single slot, or fail with CROSSSLOT. A hash tag forces related keys into one slot: only the substring inside the first {…} is hashed, so {cart:42}:items and {cart:42}:meta share a slot.
  • Overusing one hash tag concentrates load on one slot; tag by entity (customer, order), not by type.
  • Scaling: add nodes and migrate slots (redis-cli --cluster reshard / rebalance), online. Only database 0 exists in cluster mode.

Atomicity: Lua, functions, MULTI/EXEC​

  • Lua scripts (EVAL, EVALSHA) run atomically: no other command executes until the script finishes. Pass every key the script touches in KEYS (required for Cluster routing). Long scripts block the server; after busy-reply-threshold (5 s by default) Redis answers other clients with BUSY and you can only SCRIPT KILL a script that has not written yet.
  • Functions (Redis 7+, FUNCTION LOAD, FCALL) are named, persisted and replicated libraries of Lua code; prefer them for long-lived logic.
  • MULTI / EXEC queues commands and executes them together without interleaving, but there is no rollback: if one command fails at runtime, the others still apply. WATCH adds optimistic concurrency: EXEC aborts if a watched key changed.

Memory, expiry and eviction​

  • maxmemory caps the dataset; maxmemory-policy decides what happens when it is reached:
PolicyEvictsUse for
noeviction (default)Nothing; writes fail with an errorData you must not lose silently (queues, locks, rate limits)
allkeys-lru / allkeys-lfuAny key, least recently / least frequently usedPure caches (LFU handles "popular but not recent" better)
volatile-lru / volatile-lfuOnly keys with a TTLMixed instances: cache keys have TTLs, others do not
allkeys-random / volatile-randomRandomUniform access patterns
volatile-ttlKeys with the nearest expiryWhen TTL reflects value
  • LRU and LFU are approximate: Redis samples a few keys (maxmemory-samples, 5 by default) and evicts the best candidate.
  • Expiry is lazy (checked on access) plus an active cycle that samples keys with TTLs; a mass of keys expiring at the same moment causes a burst of work and, for caches, a stampede on the database.
  • Fragmentation: compare used_memory with used_memory_rss (mem_fragmentation_ratio in INFO memory); activedefrag can compact with jemalloc. MEMORY USAGE key reports one key's footprint.
  • Keep separate instances (or at least separate policies) for cache data and must-not-evict data.

Patterns​

Cache-aside​

Read: GET; on miss, load from the database, SET key value EX ttl. Write: update the database, then DEL the key (delete rather than update, to avoid racing writers leaving a stale value). Add TTL jitter (for example ±10%) so keys do not expire together, and stampede protection: a short SET lock:key 1 NX PX 2000 so only one caller recomputes, or in-process singleflight. Details in Caching.

Rate limiter​

Fixed window: INCR rl:{merchant:7}:202511281001 plus EXPIRE on first increment (do both in a script or MULTI so a crash cannot leave a key without TTL). Sliding window log: a sorted set of request timestamps, trimmed with ZREMRANGEBYSCORE. Token bucket: tokens and last refill time in a hash, updated atomically by a script (see In practice). Fail-open or fail-closed when Redis is unavailable is a business decision: login and OTP endpoints usually fail closed, product browsing fails open. See Rate Limiting.

Distributed lock (with caveats)​

Acquire: SET lock:payout:merchant:42 <random-token> NX PX 30000. Release: a script that deletes the key only if the value is still your token, so you never release someone else's lock after yours expired.

The caveats are what interviewers look for:

  • Lease expiry while still working: a GC pause, slow disk or network partition outlasts the TTL; another process acquires the lock; both now act.
  • Failover: the lock was written to the primary, which crashed before replicating; the new primary has no lock.
  • Redlock (acquiring on a majority of independent instances) addresses failover but still relies on timing assumptions; Martin Kleppmann's 2016 critique "How to do distributed locking" and Salvatore Sanfilippo's reply "Is Redlock safe?" are the canonical debate.
  • The robust fix is a fencing token: a monotonically increasing number issued with the lock and checked by the resource being protected (for example the database rejects writes with an older token). Redis locks alone do not provide this.

Rule of thumb: Redis locks are fine for efficiency (avoid two workers doing the same expensive job). For correctness of money movements, rely on database constraints, conditional updates or a consensus-backed lock service. See Distributed Locks & Leases.

Leaderboard​

ZINCRBY lb:campaign:2025-11 <points> customer:42, top ten with ZRANGE lb:campaign:2025-11 0 9 REV WITHSCORES, a user's position with ZREVRANK. Use one key per period and let old ones expire. Scores are doubles, so composite scores for tie-breaking (points and time) must stay within 2⁵³ to remain exact. See Real-time Gaming Leaderboard.

  • Size it before you shard it. Raw data is small: 25M members with a 24-byte ID and a small score is ≈650 MB. Real overhead per member (skip-list node, hash entry, string header) is nearer ≈100 bytes (rough), so budget a few GB plus fork headroom. That still fits one node; measure with MEMORY USAGE.
  • Count members with ZCARD (O(1)), not INFO keyspace, which counts keys per database, not members of a set.
  • Cluster will not spread one board. A sorted set is one key, so it hashes to one slot on one node; adding nodes does not help a board that has outgrown or overheated its node. Split it into N keys yourself and merge in the application:
    • By score range (lb:campaign:2025-11:r0 = 0–99 points, …:r1 = 100–499, …): top N reads the highest range, then the next one down if it is short; rank = local ZREVRANK + ZCARD of every higher range. A member crossing a boundary must move between two keys.
    • By member hash (…:h0 … …:h7): writes spread evenly; top N = ZRANGE … 0 N-1 REV WITHSCORES on every key, merged; one member's exact rank is no longer a single call.
    • Do not wrap the shared prefix in a hash tag: {lb:campaign:2025-11}:h3 would pull all N keys back into one slot.
  • Rebuild beside the live key, then swap. Load totals from the source of truth into a temporary key with pipelined ZADD batches, then RENAME it over the live key: readers see the old board or the new one, never a half-built one. In Cluster both keys must share a slot; below, only lb:campaign:2025-11 inside the braces is hashed, which is exactly the live key's name. RENAME frees the old value too, in the background if lazyfree-lazy-server-del is yes (check your version's default).
redis-cli -c ZADD '{lb:campaign:2025-11}:tmp' 412 customer:42 398 customer:7 # repeat in batches
redis-cli -c RENAME '{lb:campaign:2025-11}:tmp' lb:campaign:2025-11

Idempotency fast path​

SET idem:{merchant:7}:<key> PENDING NX EX 86400: if it returns OK, process the request and overwrite the value with the response; if not, GET it and return the stored response, or 409 while PENDING. This removes most duplicate traffic cheaply, but because Redis can lose recent writes on failover or eviction, payment systems still enforce a unique constraint in the database as the source of truth (see Schema Patterns and Idempotency & Exactly-Once).

Flash-sale stock gate​

Load stock into Redis before the sale; each purchase attempt runs a script that decrements only if the remaining count is at least the requested quantity, and pushes the reservation to a stream or queue. Only admitted buyers proceed to the database, which performs the authoritative conditional decrement. Redis absorbs the stampede; the database keeps the truth. See Flash Sale System and Inventory & Flash Sales.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Standalone + replica + SentinelSimple, all multi-key commands workCapacity limited to one primary; async failover loses writesDatasets that fit one node, moderate throughput
Redis ClusterHorizontal scale for memory and throughput, built-in failoverCross-slot restrictions, cluster-aware clients, resharding operationsLarge caches, high-throughput rate limiting and sessions
No persistenceFastest, simplestCold cache after restart: stampede riskPure caches with warm-up strategy
AOF everysec (+RDB preamble)About one second of loss, fast restartsMore I/O, rewritesSessions, rate limits, queues on Redis
Lua scripts / functionsAtomic multi-step logic, one round tripBlocks the server while running; cluster single-slot ruleCheck-and-set logic
MULTI/EXEC + WATCHOptimistic transactionsNo rollback, retries under contentionSimple multi-key updates
Managed (ElastiCache, MemoryDB, Memorystore, Azure Cache)Less operations, automated failoverCost, version lag, some commands restrictedMost cloud deployments; MemoryDB when durability matters more

In practice​

  • Licensing and forks: Redis moved to source-available licenses in 2024, which led to the Linux Foundation fork Valkey; Redis 8 later added an AGPL option. Cloud providers offer Valkey and Redis OSS-compatible services. Check what your platform supports; the concepts on this page apply to both.
  • Sizing: memory for data plus overhead per key (tens of bytes, rough) plus fragmentation plus fork headroom. Keep instances moderate in size so forks, failovers and resyncs stay fast.
  • Client settings: connection pools sized to need, short timeouts (tens of milliseconds for cache reads), bounded retries with jitter, and circuit breakers so a slow Redis degrades to the database rather than taking the service down (see Resilience Patterns).
  • Security: ACLs with per-service users and command restrictions (disable FLUSHALL, KEYS, DEBUG, CONFIG for applications), TLS, no public exposure. Do not cache sensitive data such as full card numbers (see Compliance).
  • Monitoring: INFO (memory, evictions, keyspace hits and misses, connected clients, replication offset, instantaneous_ops_per_sec), SLOWLOG GET, LATENCY DOCTOR, and big/hot key scans during off-peak.

A token-bucket rate limiter with go-redis v9, atomic in one script and using the Redis clock so app servers' clocks do not matter:

package ratelimit

import (
"context"

"github.com/redis/go-redis/v9"
)

// KEYS[1] = bucket; ARGV[1] = capacity, ARGV[2] = refill tokens per second, ARGV[3] = cost.
var tokenBucket = redis.NewScript(`
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)

local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(state[1]) or capacity
local ts = tonumber(state[2]) or now

tokens = math.min(capacity, tokens + math.max(0, now - ts) / 1000 * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) + 1000)
return allowed
`)

type Limiter struct {
rdb redis.Scripter
capacity int
perSec float64
}

func New(rdb redis.Scripter, capacity int, perSec float64) *Limiter {
return &Limiter{rdb: rdb, capacity: capacity, perSec: perSec}
}

// Allow reports whether one request for the given subject may proceed.
func (l *Limiter) Allow(ctx context.Context, subject string) (bool, error) {
n, err := tokenBucket.Run(ctx, l.rdb, []string{"rl:{" + subject + "}"}, l.capacity, l.perSec, 1).Int()
if err != nil {
return false, err // caller decides fail-open or fail-closed
}
return n == 1, nil
}

Safe lock release by token:

var unlock = redis.NewScript(`
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
`)

func TryLock(ctx context.Context, rdb *redis.Client, key string, ttl time.Duration) (string, bool, error) {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil { // crypto/rand
return "", false, err
}
token := hex.EncodeToString(buf)
ok, err := rdb.SetNX(ctx, key, token, ttl).Result()
return token, ok, err
}

func Unlock(ctx context.Context, rdb *redis.Client, key, token string) error {
return unlock.Run(ctx, rdb, []string{key}, token).Err()
}

Common pitfalls​

  • KEYS * in production. It scans the whole keyspace on the main thread. Symptom: every client times out for seconds. Use SCAN with MATCH and COUNT.
  • Big keys. A hash with millions of fields or a multi-megabyte string. Symptoms: slow HGETALL, multi-second DEL (use UNLINK), uneven memory across cluster nodes, replication spikes. Find them with redis-cli --bigkeys or --memkeys; split by sub-key. A leaderboard sorted set with hundreds of millions of members is the same problem, and Cluster cannot split it for you (see Leaderboard under Patterns).
  • Hot keys. One flash-sale SKU or one config key read by every request. Symptom: one cluster node at 100% CPU while others idle. Mitigate with client-side or in-process caching, read replicas for that key, or splitting into N copies. redis-cli --hotkeys works with an LFU eviction policy.
  • No TTL on cache keys. Symptom: memory grows until eviction or OOM errors at peak.
  • Synchronized expiry. Thousands of keys set with the same TTL at deploy time. Symptom: periodic database load spikes. Add jitter.
  • Redis as the system of record for money or stock. Symptom: after a failover, some decrements or idempotency markers are gone and duplicates slip through.
  • Using Pub/Sub for important messages. Symptom: messages lost whenever a subscriber reconnects.
  • Unbounded retries from clients during a Redis incident. Symptom: a brief slowdown turns into a retry storm that keeps Redis saturated.
  • Large fork under memory pressure. Symptom: latency spikes or OOM during BGSAVE or replica full sync.

Interview angle​

  • Prompts: "How would you implement a rate limiter?", "Design a leaderboard", "Can you use Redis for distributed locks?", "What happens to your cache when Redis restarts?", "How does Redis Cluster shard data?"
  • A strong answer picks the data structure, makes multi-step logic atomic with a script, states persistence and failover loss windows, and keeps correctness-critical invariants in the database.
  • Expect follow-ups: hash tags and CROSSSLOT, hot keys during a sale, eviction policy choice, the Redlock debate and fencing tokens, AOF fsync trade-offs.
  • Red flags: "Redis is single-threaded so it's slow", "Redis locks guarantee mutual exclusion", using KEYS, no TTLs, no plan for cache stampedes.

Self-check​

1. Why is INCR safe under concurrency without any locking, and what does that imply about slow commands?

The main thread executes commands one at a time, so an INCR cannot interleave with another command on the same key; each command is atomic. The flip side is that a long-running command blocks every other client until it finishes, so O(n) commands over large collections, KEYS, big DELs and long scripts directly add latency for everyone.

2. Compare RDB and AOF for a session store that may lose at most a few seconds of data.

RDB snapshots are compact and fast to load but lose everything since the last snapshot, typically minutes. AOF with appendfsync everysec loses about one second, at the cost of more disk I/O and periodic rewrites. Use AOF (with the RDB preamble for fast restarts), and remember that asynchronous replication can still lose writes on failover.

3. A Lua script touching cart:42:items and cart:42:meta fails in Redis Cluster with CROSSSLOT. Why, and how do you fix it?

The two keys hash to different slots, and scripts in Cluster may only access keys in one slot. Rename them with a hash tag so only the shared part is hashed: {cart:42}:items and {cart:42}:meta land in the same slot. Pass both in KEYS so the client routes the script to the node owning that slot.

4. List three ways a Redis-based lock can be held by two clients at once.

The holder pauses (GC, CPU starvation, network partition) past the TTL while another client acquires the expired lock; the primary fails over before the lock key replicated, so the new primary grants it again; or a client releases with a plain DEL after its lock expired and deletes another client's lock. Fencing tokens checked by the protected resource are the robust mitigation.

5. Which eviction policy would you choose for (a) a product cache and (b) an instance holding rate-limit counters and idempotency markers?

(a) allkeys-lfu or allkeys-lru: every key is a rebuildable cache entry, and LFU keeps popular items even if not touched in the last second. (b) noeviction with ample memory and alerts: silently evicting counters or idempotency markers breaks limits and allows duplicates. Ideally keep them on separate instances.

6. Scenario: during a flash sale one Redis Cluster node hits 100% CPU while others are idle. What is happening and what do you do?

A hot key (likely the stock counter or product cache entry for the sale SKU) lives in one slot on that node. Short term: cache the product data in-process for a second or two, reduce per-request Redis calls, and gate traffic upstream. Structurally: split stock into N sub-counters across slots (stock:sku-1:0 … stock:sku-1:7) with buyers hashed to a sub-counter, and serve read-mostly hot data from replicas or local caches.

7. Why should a payment API not rely only on Redis for idempotency?

Redis replication is asynchronous and keys can be lost on failover, restart without persistence, or eviction. If the idempotency marker disappears, a retried request is processed again and the customer is charged twice. Redis can serve as a fast path, but the database must enforce uniqueness of the idempotency key in the same transaction as the payment.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Run the patterns and break things on purpose.

docker run --name redis-lab -p 6379:6379 -d redis:7.4 \
redis-server --appendonly yes --enable-debug-command yes
docker exec -it redis-lab redis-cli
  1. Structures. Build a cart as a hash, a leaderboard as a sorted set (top 3 with ZRANGE … REV WITHSCORES), and count 100,000 distinct ids with PFADD/PFCOUNT; compare MEMORY USAGE of the HyperLogLog with a set holding the same ids.
  2. Blocking. In one terminal run redis-cli --latency. In another, DEBUG POPULATE 2000000 then KEYS nothing-matches-* (it still scans every key); observe the latency spike. Repeat with SCAN 0 MATCH nothing-matches-* COUNT 1000 and compare.
  3. Big key. Create two 2-million-field hashes with EVAL "for i=1,2000000 do redis.call('HSET', KEYS[1], 'f'..i, i) end return 1" 1 bighash1 (and again for bighash2), find them with redis-cli --bigkeys, then time DEL bighash1 against UNLINK bighash2.
  4. Rate limiter. Wire the Go token bucket against this instance, fire 200 requests in a second at capacity 50 and refill 10/s, and verify about 50 are allowed immediately and the rest follow the refill rate.
  5. Eviction. CONFIG SET maxmemory 50mb, CONFIG SET maxmemory-policy allkeys-lfu, write keys until memory is full, and watch evicted_keys in INFO stats; then switch to noeviction and observe the write error.
  6. Persistence. Write keys, docker kill redis-lab (no graceful shutdown), restart, and count what survived with AOF on; repeat with --appendonly no and a default save policy.

Done when you can explain every latency spike and data-loss result in terms of the execution model and persistence settings.

Further reading​

  • Redis documentation: data types, persistence, replication, Sentinel, Cluster specification, eviction (redis.io/docs).
  • Valkey documentation (valkey.io).
  • Martin Kleppmann, "How to do distributed locking" (2016), and Salvatore Sanfilippo, "Is Redlock safe?" (2016).
  • Josiah L. Carlson, Redis in Action.
  • Alex Xu, System Design Interview Vol. 1 (rate limiter) and Vol. 2 ch. 10 (leaderboard).
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).