Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  The Redis Handbook
Handbook~14 min readIntermediate
Deep Dive

Redis, the
data-structure server.

Calling Redis "a cache" undersells it. It's an in-memory server whose values are real data structures — sorted sets, hashes, lists — each with atomic operations at RAM speed. That's why one tool powers caches, rate limiters, leaderboards, sessions and queues. Here's how it works, and where it fits.

01

More than a key-value cache

Most people meet Redis as a cache: put a value under a key, read it back fast. That's true — it lives in memory, so reads and writes are microseconds, not milliseconds. But the deeper idea is that Redis is a data-structure server: a value isn't an opaque blob, it's a typed structure (a list, a set, a sorted set, a hash) with commands that operate on it atomically on the server.

That changes what you can do. Instead of reading a value, modifying it in your app, and writing it back (a race-prone round trip), you tell Redis "increment this counter," "add to this sorted set," "pop from this list" — and it happens atomically in one hop. The data structure lives where the data is. That's the difference between a cache and a Swiss-army server.

02

The core data structures

Five structures cover the vast majority of Redis usage. Knowing what each is for is most of knowing Redis.

StructureWhat it isUsed for
StringA value (text, number, bytes)Cache entries, counters (INCR), flags, small blobs
HashField → value map under one keyObjects/records (a user's fields) without serializing the whole thing
ListOrdered sequence (push/pop both ends)Simple queues, recent-items, timelines
SetUnordered unique membersMembership, tags, unions/intersections (who liked both)
Sorted setMembers ordered by a scoreLeaderboards, rate limiting, priority queues, ranges

The sorted set deserves a spotlight: it keeps members ordered by a numeric score with O(log N) add/update and rank queries — which is exactly a leaderboard, and also the backbone of sliding-window rate limiters and time-ordered indexes. Many "how would you build X in Redis?" answers are "a sorted set."

03

Single-threaded, and fast because of it

Surprisingly, core Redis executes commands on a single thread, via an event loop. That sounds like a limitation, but it's a feature: because one command runs to completion before the next, every operation is atomic with no locks, no race conditions, and no context-switching overhead. INCR, a sorted-set update, a multi-key transaction — all naturally atomic.

And it's still blazing fast because Redis is in-memory: the bottleneck is the network and memory bandwidth, not CPU concurrency. The practical lesson: keep individual commands cheap. A single expensive command (a huge KEYS * scan, a giant sorted-set range) blocks the whole server for its duration, so you avoid O(N) operations on big keys on the hot path.

→ The footgun

Because it's single-threaded, one slow command stalls every other client. Never run KEYS * or big blocking operations in production — use SCAN and keep hot-path commands O(1) or O(log N).

04

Persistence — it's in memory, so…

Redis keeps data in RAM, which is why it's fast — and why durability needs care. If the process dies, in-memory data is gone unless it was persisted. Redis offers two mechanisms with different tradeoffs.

RDB — snapshots

  • Periodic point-in-time dump of the dataset
  • Compact file, fast to load, low overhead
  • Risk: lose writes since the last snapshot

AOF — append-only file

  • Logs every write operation
  • Better durability (down to ~1s or per-write)
  • Larger files, slower to load/replay

Many deployments run both: AOF for durability, RDB for fast restarts and backups. The key mindset: Redis can be durable, but its sweet spot is a fast layer where losing a little recent data on a crash is acceptable. If you need database-grade durability guarantees, that's a signal to reconsider (section 08).

05

Memory limits: eviction & TTL

RAM is finite, so Redis has to decide what to keep. Set a maxmemory limit and an eviction policy for when it's hit — most commonly allkeys-lru (evict least-recently-used) or allkeys-lfu (least-frequently-used), which turns Redis into a proper LRU/LFU cache that automatically drops cold data. Other policies evict only keys with a TTL, or refuse writes when full.

Independently, any key can be given a TTL (time to live) so it expires automatically — essential for cache freshness, session timeouts, and rate-limit windows. Between eviction (memory pressure) and TTL (explicit expiry), Redis keeps its footprint bounded without you manually cleaning up.

What that bounded cache buys you is a hit rate, and the hit rate is the whole point — it's the dial between a fast service and a slow one:

effective latency = hit_rate · 0.5ms + (1 − hit_rate) · 50ms  →  90% hits = 5.5ms, 99% = 1.0ms

A skewed workload (a few hot keys) hits often even with a small cache. The runnable version below is a real LRU cache — watch it evict cold keys and hold ~80% hit rate on 2% of the keyspace.

06

What people actually build with it

The data structures map cleanly onto classic patterns — this is why Redis is everywhere.

CacheString + TTL — the read-through/aside cache in front of a slow database. The original use.
Rate limitINCR + TTL, or sorted set — count requests per window atomically; reject over the limit.
LeaderboardSorted set — O(log N) score updates and rank/top-K queries, live.
SessionHash + TTL — fast shared session store so app servers stay stateless.
QueueList or Streams — simple job queues (LPUSH/BRPOP) or durable Streams with consumer groups.
Pub/SubChannels — lightweight real-time fan-out (chat, notifications, live updates).

The pattern is always: pick the structure whose atomic operations are the feature. A leaderboard isn't "store scores and sort" — it's "a sorted set," and the rank query is one command.

07

Availability & scale

A single Redis is a single point of failure and capped by one machine's RAM. Three mechanisms address that. Replication: a primary asynchronously copies its data to replicas, which serve reads and stand ready as failover targets. Sentinel: monitors the primary and automatically promotes a replica if it dies, giving high availability for a single logical dataset. Cluster: shards the keyspace across many primaries (by hashing keys into slots), so both capacity and throughput scale horizontally, each shard with its own replicas.

→ Rule of thumb

Need HA but your data fits one machine? Replication + Sentinel. Outgrown one machine's memory or throughput? Redis Cluster to shard across nodes. Cluster adds constraints (multi-key ops must share a slot), so don't reach for it before you need it.

08

When Redis is the wrong tool

Redis is a fast layer, not a universal database. It's the wrong choice when your dataset is much larger than affordable RAM (memory is the cost ceiling), when you need rich relational queries or transactions spanning many entities (use a relational database), or when you need strong, guaranteed durability like a system of record (async replication and snapshotting can lose recent writes on failure).

Use it for what it's superb at: caching, counters, rate limiting, leaderboards, sessions, ephemeral queues, and real-time fan-out — a blazing-fast complement to your primary store, not a replacement for it. The right question isn't "can Redis do this?" (it usually can) but "is a fast, in-memory, structure-oriented layer the right shape for this data?"

RUN IT YOURSELF

Run an LRU cache and watch the hit rate

Redis with allkeys-lru is a bounded cache that evicts the least-recently-used key past its memory limit — and the payoff is a hit rate. This is a real LRU cache run over a skewed workload where a handful of hot keys take 80% of the traffic: watch it evict cold keys, never exceed its capacity, and still hit ~80% while caching just 2% of the keyspace. Then see how that hit rate collapses the effective latency from 50ms straight-to-database down to single digits. Change the capacity or the skew.

CPython · WebAssembly
The picture

The picture: one thread, one queue, RAM behind it

clients event loop memory client A: GET client B: INCR client C: KEYS * one thread, one command at a time GET INCR KEYS * ZADD O(N): all behind it wait RAM keyspace user:42 hashhits string board zsetjobs list AOF / RDB on disk replica (async)
Every client’s command lands in one queue and runs to completion on one thread, so INCR never races another INCR. The price is head-of-line blocking: a single O(N) command such as KEYS * holds the thread, and every cheap command queued behind it waits. Durability and copies happen after the write, off to the side: the AOF or an RDB snapshot on disk, and an asynchronous replica. That is why an acknowledged write can still be lost if the primary dies first.
By the numbers

Worked example: a sliding-window rate limiter, step by step

The rule: at most 3 requests per 10 seconds per user. Keep one sorted set per user, rl:u42. Each request is a member (a unique request id) whose score is its timestamp. On every request: ZREMRANGEBYSCORE rl:u42 -inf (t−10) drops entries older than the window, ZCARD counts what is left, and if the count is under 3 you ZADD the new request and allow it. Trace one user (timestamps in seconds, illustrative):

tRemoved (score ≤ t−10)ZCARDDecisionSet after
0nothing0allow{0}
2nothing1allow{0, 2}
4nothing2allow{0, 2, 4}
7nothing3reject{0, 2, 4}
1102allow{2, 4, 11}
1322allow{4, 11, 13}
1442allow{11, 13, 14}
15nothing3reject{11, 13, 14}

Compare a fixed window, INCR rl:u42:<t div 10> with a TTL. Requests at 8, 9 and 9.5 count against window 0; requests at 10, 10.5 and 11 count against window 1. All six pass, which is six requests in three seconds. The sliding window rejects the request at 10, because 8, 9 and 9.5 are still in the set. The cost is space: up to 3 members per active user instead of one counter. Run the remove, count and add as one Lua script. Two app servers that each run ZCARD, see 2 and both ZADD would let 4 through. The single thread runs a script as one command, so the check and the add cannot interleave.

Trade-offs

Cost and trade-offs: what each command costs the one thread

Case is the command, Time its documented complexity, Space what it holds or touches. On a single-threaded server, Time is also how long every other client waits.

CaseTimeSpaceWhy
GET, SET, INCRO(1)One valueSafe on any hot path.
HGET, HSET one fieldO(1)Small hashes use a compact encodingUpdate one field of an object without rewriting it.
LPUSH, RPOPO(1)One elementLINDEX in the middle of a long list is O(N).
ZADD, ZRANKO(log N)Skip list plus hash per sorted setZSCORE is O(1); ZRANGE is O(log N + M) for M returned.
SINTERO(N × M) worst caseBuilds the resultN is the smallest set, M the number of sets. Fine for small sets.
KEYS, HGETALL, SMEMBERS on a big keyO(N)The whole reply in memoryBlocks every client for the duration.
SCAN / HSCANO(1) per call, O(N) for a full passA cursorSpreads the work out. A key can be returned twice, so dedupe.
DEL vs UNLINK on a big keyO(M) vs O(1)M elements freedUNLINK frees the memory on a background thread.

The rule that falls out: anything whose cost grows with the size of a key belongs off the hot path, or behind a cursor. A big key is a latency problem before it is a memory problem.

In the wild

Where this shows up in production and interviews

  • Cache stampede

    A hot key expires and every request misses at once, all hitting the database. Let one request refill it behind a short lock (SET lock:k <token> NX PX 5000) while the rest wait or serve the stale value. Add random jitter to TTLs so keys written together do not expire together.

  • Locks with SET NX PX

    Release a lock only if it still holds your token, checked and deleted in one Lua script. Otherwise a slow client whose lease expired deletes the next owner’s lock. Replication is asynchronous, so a failover can grant the same lock twice. If correctness depends on it, pass a fencing token to the resource.

  • Cluster hash tags

    Cluster maps keys to 16,384 slots by CRC16 of the key. If a key contains {…}, only that part is hashed. {user:42}:cart and {user:42}:profile share a slot, so one MULTI or script can touch both without a CROSSSLOT error.

  • The interview version

    For “design a leaderboard” or “design a rate limiter”, name the structure, the commands and their cost (ZADD and ZREVRANK, O(log N)). Then say what happens when the primary fails over (recent writes can vanish) and when one key goes hot. One key lives on one shard and one thread, so you split it or cache it locally.

Self-check

Check yourself

A page handler runs HGETALL on a 2-million-field hash on every view. Latency for unrelated GETs jumps. Why?

HGETALL is O(N), and Redis runs one command at a time. Every GET queued behind it waits for all 2 million fields to be serialised. Fetch only the fields you need with HMGET, iterate with HSCAN, or split the hash.

In the rate limiter above, two requests from one user arrive in the same millisecond and both use the timestamp as the member. What goes wrong?

Members of a sorted set are unique. The second ZADD only updates the score of the existing member, so two requests count as one and the limiter under-counts. Use a unique request id as the member and the timestamp as the score.

maxmemory is set with volatile-lru, but none of your keys has a TTL. What happens when memory fills?

The volatile-* policies only evict keys that have an expiry. With none to evict, Redis behaves like noeviction: reads still work and writes fail with an out-of-memory error. Use allkeys-lru or allkeys-lfu for a pure cache.

The primary acknowledges a SET, then crashes before the replica copies it. Sentinel promotes the replica. Is the write there?

No. Replication is asynchronous, so the acknowledgement only meant the primary had it. WAIT can block until replicas confirm, which narrows the window, but it does not make Redis strongly consistent. Data you cannot lose belongs in your system of record.

Frequently asked

Quick answers

What is Redis?

An in-memory data-structure server: data lives in RAM for microsecond access, and values are typed structures (strings, hashes, lists, sets, sorted sets) with atomic commands. Used for caching, rate limiting, leaderboards, sessions, queues, and pub/sub.

Why single-threaded but fast?

Commands run on one event-loop thread, so each is atomic with no locks or context switches, and it's in-memory — the bottleneck is network/memory, not CPU. The catch: one slow command blocks everyone, so keep commands cheap.

RDB vs AOF?

RDB takes periodic snapshots (compact, fast load, can lose recent writes); AOF logs every write (better durability, larger/slower). Many use both, balancing durability against performance.

When not to use Redis?

As a primary store for data larger than RAM, for complex relational queries/transactions, or when you need database-grade durability. It's a fast layer, not a replacement for your system of record.

Finished this one? 0 / 209 Handbooks done
NextRedis vs Memcached Next on the “Data, and where it lives” ladder · rung 8 of 9

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks