What Is Redis
Three study guides in one place: how Redis actually works under the hood, how to build a correct rate limiter on top of it, and three protocol/durability deep dives that resolve the questions the main text raises but doesn't fully unpack.
The event loop, the allocator, the page table, the replication stream. Every section ends where the next one begins: memory layout drives fork cost, fork cost drives latency, latency drives failover, failover drives write loss.
| Word | Meaning |
|---|---|
in-memory | Entire dataset lives in RAM. Every GET/SET touches RAM, not disk — sub-millisecond latency by default. |
data structure | Not a key→blob store. Native types: strings, hashes, lists, sets, sorted sets, bitmaps, HyperLogLogs, streams, geo-indexes. Operations are atomic and semantically meaningful. |
server | Standalone process (port 6379), separate from your app. Language-agnostic via TCP + RESP. Multiple services share one instance. |
Why "separate process over TCP" = shared
Redis runs as its own OS process listening on 127.0.0.1:6379 (or a remote IP). Your app talks to it over a TCP socket — same as any network call, even on the same machine. The contrast is with an in-process cache (a HashMap inside your app):
| In-process cache | Redis | |
|---|---|---|
| Shared across 10 app servers? | no each has its own copy | yes all connect to one Redis |
| Survives app restart? | no | yes with persistence |
| Latency | ~nanoseconds (pointer deref) | ~microseconds (TCP round-trip) |
Because it's a separate process, any language, any service, any machine on the network can connect to the same instance — that's what makes it shared.
RESP — The Wire Format
Client sends: Server replies:
*3\r\n +OK\r\n
$3\r\nSET\r\n
$3\r\nfoo\r\n
$3\r\nbar\r\nSo simple you can telnet localhost 6379 and type commands by hand. Redis 7.0 → RESP3 adds typed responses (maps, doubles, booleans) and the > push type, which is what makes client-side caching possible at all.
Client-Side Caching
Your app keeps a local HashMap of hot Redis values — reads hit process memory instead of going over TCP. The problem: how do you know when Redis has a fresher value? RESP3 solves it with key tracking + invalidation push.
- Client reads
GET user:42→ stores"alice"locally, tells Redis "I'm tracking this key". - Any writer does
SET user:42 "bob". - Redis pushes an invalidation message to every client tracking that key.
- Client evicts its local copy; next read goes to Redis and gets
"bob".
| Tier | Latency |
|---|---|
| Local HashMap (client-side cache hit) | ~10 ns |
| Redis on localhost (miss → TCP round-trip) | ~100 µs |
| Postgres on localhost | ~1–5 ms |
Stale window = the time between the write and the invalidation message arriving — sub-millisecond on a local network. Without RESP3 you'd need a TTL and would simply accept stale data for N seconds.
Pipelining
Normal flow pays a round-trip per command (~100 µs each). Pipelining batches N commands into one TCP write and reads N replies back — cost is ~1 round-trip regardless of N.
✗ Without pipelining — 3 round-trips (~300 µs)
client.Set(ctx, "a", 1, 0)
client.Set(ctx, "b", 2, 0)
client.Set(ctx, "c", 3, 0)✓ With pipelining — 1 round-trip (~100 µs)
pipe := client.Pipeline()
pipe.Set(ctx, "a", 1, 0) // queued
pipe.Set(ctx, "b", 2, 0) // queued
pipe.Set(ctx, "c", 3, 0) // queued
pipe.Exec(ctx) // flushed onceHow does the client match replies to commands? TCP is an ordered byte stream. Redis processes commands in arrival order and replies in the same order, so the client just counts: reply #1 = command #1. No IDs needed. Pipelining is per-connection — it's a purely client-side batching trick; the server doesn't know it's a "pipeline", it just sees commands arriving faster.
Pipelining vs concurrent goroutines
Three goroutines each calling SET is not pipelining — each borrows its own connection from the pool and waits on its own reply stream.
Goroutine 1 → conn A → SET a 1 → waits → +OK
Goroutine 2 → conn B → SET b 2 → waits → +OK
Goroutine 3 → conn C → SET c 3 → waits → +OK| Pipelining | Concurrent goroutines | |
|---|---|---|
| Connections used | 1 | N (one per goroutine) |
| Reply matching | by TCP order | by connection |
| Round-trips | 1 for N commands | 1 per goroutine |
Use pipelining when commands are independent (writing 500 analytics events). Don't when command #2 depends on command #1's result — use MULTI/EXEC or a Lua script instead.
Where Redis Shows Up in Production
| Use Case | Why Redis Fits | Key Commands |
|---|---|---|
| Cache | Sub-ms reads + TTL-based expiry | SET/GET + EX, MGET, SETEX |
| Session store | Small, read-heavy, keyed by session ID; TTL auto-expires | Hash per session, EXPIRE/TTL |
| Rate limiting | Atomic INCR + EXPIRE — no locks needed | INCR, EXPIRE, ZRANGEBYSCORE |
| Distributed lock | SET … NX PX ttl atomically acquires with a safety net | SET NX PX, DEL on release |
| Leaderboards | O(log N) insert and rank | ZADD, ZRANK, ZRANGE WITHSCORES |
| Task queues | Lists as FIFO; Streams for durable multi-consumer ack semantics | RPUSH/BLPOP, XADD/XREADGROUP/XACK |
| Pub/Sub fanout | Fire-and-forget to many subscribers | PUBLISH, SUBSCRIBE |
| Real-time counters | Atomic INCR; HyperLogLog for cardinality at fixed memory | INCR, PFADD, BITCOUNT |
| Geospatial | lat/lon encoded in a sorted set; nearby in one call | GEOADD, GEODIST, GEOSEARCH |
| Feature flags | Low-latency reads, updated centrally | HGETALL, HSET |
What Is AOF? (and why always still isn't enough)
AOF (Append-Only File) is Redis's write-ahead log. Every write command that executes on the main thread is appended to a file in RESP format; on restart Redis replays it top-to-bottom. Three stages get a command to physical disk:
Stage 1 Command executes on main thread → appended to in-memory AOF buffer
Stage 2 write() flushes buffer to the AOF file descriptor
Data is now in the kernel's page cache — NOT yet on physical disk
Stage 3 fsync() forces page cache → physical disk
↑ this is what appendfsync controls| Policy | When fsync() runs | Max data loss | Latency cost |
|---|---|---|---|
always | After every write command | ≤ 1 command | High — every write blocks on disk (~ms) |
everysec default | Once per second (background thread) | ≤ 1 second | Low — main thread never waits on disk |
no | Never — OS decides (~30 s on Linux) | ≤ ~30 seconds | Lowest |
always is the strictest policy: Redis won't return OK until that write is physically on disk. That sounds durable — and it is, for the primary. It only solves half the problem.
Gap 1 — Replication is still asynchronous
Client → master: SET balance:user1 500
master → fsync() on AOF → replies OK ──────► client: durable ✓
master → streams write to replica ──────► (async, lagging behind)t0 Client: SET balance:user1 500 → master: OK (replica hasn't seen it)
t1 Master dies
t2 Cluster promotes the replica
t3 New master never had balance:user1=500. Acknowledged write is GONE.
t4 Old master rejoins, sees higher configEpoch, discards its version to sync.Gap 2 — No cross-key atomicity across a failover
Debiting A and crediting B must be atomic. MULTI/EXEC on a single node gives you that. But if those keys land on different Cluster shards you get CROSSSLOT — and even on one shard, an acknowledged MULTI/EXEC can be lost entirely after a failover.
Why Postgres + sync replication is the right answer
Client → Postgres primary
→ writes WAL (write-ahead log)
→ sends WAL record to standby
→ waits for standby to flush to disk and acknowledge
→ returns COMMIT OK| Property | Redis AOF always | Postgres + sync replication |
|---|---|---|
| Data on primary disk before OK | ✓ | ✓ |
| Data on replica disk before OK | ✗ async | ✓ |
| Write survives failover | Not guaranteed | Yes — by design |
| Atomic multi-key transactions | Single shard only | Full ACID, cross-table |
The principle: AOF
alwaysis a persistence mechanism on one node. Sync replication is a distributed durability contract. For money, you need the latter.