Redis Deep Dive
- 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 hugeDEL, 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
maxmemoryand an eviction policy deliberately; find big keys and hot keys before they find you; never runKEYSin 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
| Type | Key operations (complexity) | Use cases |
|---|---|---|
| String | GET, SET … EX … NX, INCR/INCRBY O(1); up to 512 MB | Cached JSON, counters, locks, idempotency markers, feature flags |
| Hash | HSET, HGET, HINCRBY O(1); HGETALL O(n) | Session objects, cart (field = SKU, value = quantity), per-user rate counters |
| List | LPUSH/RPOP O(1), BLMOVE blocking, LRANGE O(n) | Simple queues, recent-items lists (capped with LTRIM) |
| Set | SADD, SISMEMBER O(1), SINTER | Unique visitors per day (small scale), tags, "already notified" sets |
| Sorted set | ZADD, ZINCRBY, ZRANK O(log n), range by score or rank | Leaderboards, delayed jobs (score = due time), sliding-window rate limits, top-N |
| Stream | XADD, XREADGROUP, XACK, XAUTOCLAIM | Durable-ish event log with consumer groups, pending-entry tracking |
| HyperLogLog | PFADD, PFCOUNT, PFMERGE; ≤ 12 KB per key, ≈ 0.81% standard error | Approximate unique counts: distinct buyers per campaign, unique card numbers per merchant per day |
| Bitmap | SETBIT, GETBIT, BITCOUNT, BITOP | Daily active users by numeric user id, feature-enabled flags, attendance-style data |
| Geo | GEOADD, GEOSEARCH | Nearest 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,ZINCRBYcannot 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:
UNLINKandFLUSHALL ASYNCfree 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
| Mode | How | Loss on crash | Costs |
|---|---|---|---|
| None | Pure in-memory | Everything | None; acceptable for caches you can rebuild |
| RDB snapshots | BGSAVE forks a child that writes a compact point-in-time file, triggered by save rules or replication | Since the last snapshot (often minutes) | fork() latency on large datasets; copy-on-write can temporarily use much more memory under heavy writes |
| AOF | Appends every write command; appendfsync always / everysec (default) / no; background rewrite compacts it | everysec: about one second of writes; always: little, at a large throughput cost | Larger files, rewrite overhead; Redis 7 uses a multi-part AOF with a base file plus incremental files |
| RDB + AOF | AOF with an RDB preamble (default when AOF is on) | Like AOF | Fast 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 timeoutblocks 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-lagmake 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) orASK(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}:itemsand{cart:42}:metashare 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 inKEYS(required for Cluster routing). Long scripts block the server; afterbusy-reply-threshold(5 s by default) Redis answers other clients withBUSYand you can onlySCRIPT KILLa 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/EXECqueues commands and executes them together without interleaving, but there is no rollback: if one command fails at runtime, the others still apply.WATCHadds optimistic concurrency:EXECaborts if a watched key changed.
Memory, expiry and eviction
maxmemorycaps the dataset;maxmemory-policydecides what happens when it is reached:
| Policy | Evicts | Use for |
|---|---|---|
noeviction (default) | Nothing; writes fail with an error | Data you must not lose silently (queues, locks, rate limits) |
allkeys-lru / allkeys-lfu | Any key, least recently / least frequently used | Pure caches (LFU handles "popular but not recent" better) |
volatile-lru / volatile-lfu | Only keys with a TTL | Mixed instances: cache keys have TTLs, others do not |
allkeys-random / volatile-random | Random | Uniform access patterns |
volatile-ttl | Keys with the nearest expiry | When 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_memorywithused_memory_rss(mem_fragmentation_ratioinINFO memory);activedefragcan compact with jemalloc.MEMORY USAGE keyreports 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)), notINFO 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 = localZREVRANK+ZCARDof 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 WITHSCORESon 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}:h3would pull all N keys back into one slot.
- By score range (
- Rebuild beside the live key, then swap. Load totals from the source of truth into a temporary key with pipelined
ZADDbatches, thenRENAMEit 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, onlylb:campaign:2025-11inside the braces is hashed, which is exactly the live key's name.RENAMEfrees the old value too, in the background iflazyfree-lazy-server-delisyes(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
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Standalone + replica + Sentinel | Simple, all multi-key commands work | Capacity limited to one primary; async failover loses writes | Datasets that fit one node, moderate throughput |
| Redis Cluster | Horizontal scale for memory and throughput, built-in failover | Cross-slot restrictions, cluster-aware clients, resharding operations | Large caches, high-throughput rate limiting and sessions |
| No persistence | Fastest, simplest | Cold cache after restart: stampede risk | Pure caches with warm-up strategy |
AOF everysec (+RDB preamble) | About one second of loss, fast restarts | More I/O, rewrites | Sessions, rate limits, queues on Redis |
| Lua scripts / functions | Atomic multi-step logic, one round trip | Blocks the server while running; cluster single-slot rule | Check-and-set logic |
MULTI/EXEC + WATCH | Optimistic transactions | No rollback, retries under contention | Simple multi-key updates |
| Managed (ElastiCache, MemoryDB, Memorystore, Azure Cache) | Less operations, automated failover | Cost, version lag, some commands restricted | Most 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,CONFIGfor 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. UseSCANwithMATCHandCOUNT.- Big keys. A hash with millions of fields or a multi-megabyte string. Symptoms: slow
HGETALL, multi-secondDEL(useUNLINK), uneven memory across cluster nodes, replication spikes. Find them withredis-cli --bigkeysor--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 --hotkeysworks 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
BGSAVEor 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.
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
- 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 withPFADD/PFCOUNT; compareMEMORY USAGEof the HyperLogLog with a set holding the same ids. - Blocking. In one terminal run
redis-cli --latency. In another,DEBUG POPULATE 2000000thenKEYS nothing-matches-*(it still scans every key); observe the latency spike. Repeat withSCAN 0 MATCH nothing-matches-* COUNT 1000and compare. - 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 forbighash2), find them withredis-cli --bigkeys, then timeDEL bighash1againstUNLINK bighash2. - 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.
- Eviction.
CONFIG SET maxmemory 50mb,CONFIG SET maxmemory-policy allkeys-lfu, write keys until memory is full, and watchevicted_keysinINFO stats; then switch tonoevictionand observe the write error. - Persistence. Write keys,
docker kill redis-lab(no graceful shutdown), restart, and count what survived with AOF on; repeat with--appendonly noand a defaultsavepolicy.
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).
Related
- Caching — cache-aside, invalidation and stampedes.
- Rate Limiting — algorithms and placement.
- Distributed Locks & Leases — fencing tokens and lease safety.
- Flash Sale System — Redis as a stock gate under extreme load.
- Real-time Gaming Leaderboard — sorted sets at scale.
- NoSQL Data Modeling — key-value modeling in the wider NoSQL landscape.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).