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.

WordMeaning
in-memoryEntire dataset lives in RAM. Every GET/SET touches RAM, not disk — sub-millisecond latency by default.
data structureNot a key→blob store. Native types: strings, hashes, lists, sets, sorted sets, bitmaps, HyperLogLogs, streams, geo-indexes. Operations are atomic and semantically meaningful.
serverStandalone 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 cacheRedis
Shared across 10 app servers?no each has its own copyyes all connect to one Redis
Survives app restart?noyes 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\n

So 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.

  1. Client reads GET user:42 → stores "alice" locally, tells Redis "I'm tracking this key".
  2. Any writer does SET user:42 "bob".
  3. Redis pushes an invalidation message to every client tracking that key.
  4. Client evicts its local copy; next read goes to Redis and gets "bob".
TierLatency
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 once

How 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
PipeliningConcurrent goroutines
Connections used1N (one per goroutine)
Reply matchingby TCP orderby connection
Round-trips1 for N commands1 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 CaseWhy Redis FitsKey Commands
CacheSub-ms reads + TTL-based expirySET/GET + EX, MGET, SETEX
Session storeSmall, read-heavy, keyed by session ID; TTL auto-expiresHash per session, EXPIRE/TTL
Rate limitingAtomic INCR + EXPIRE — no locks neededINCR, EXPIRE, ZRANGEBYSCORE
Distributed lockSET … NX PX ttl atomically acquires with a safety netSET NX PX, DEL on release
LeaderboardsO(log N) insert and rankZADD, ZRANK, ZRANGE WITHSCORES
Task queuesLists as FIFO; Streams for durable multi-consumer ack semanticsRPUSH/BLPOP, XADD/XREADGROUP/XACK
Pub/Sub fanoutFire-and-forget to many subscribersPUBLISH, SUBSCRIBE
Real-time countersAtomic INCR; HyperLogLog for cardinality at fixed memoryINCR, PFADD, BITCOUNT
Geospatiallat/lon encoded in a sorted set; nearby in one callGEOADD, GEODIST, GEOSEARCH
Feature flagsLow-latency reads, updated centrallyHGETALL, 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
PolicyWhen fsync() runsMax data lossLatency cost
alwaysAfter every write command≤ 1 commandHigh — every write blocks on disk (~ms)
everysec defaultOnce per second (background thread)≤ 1 secondLow — main thread never waits on disk
noNever — OS decides (~30 s on Linux)≤ ~30 secondsLowest

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
PropertyRedis AOF alwaysPostgres + sync replication
Data on primary disk before OK✓✓
Data on replica disk before OK✗ async✓
Write survives failoverNot guaranteedYes — by design
Atomic multi-key transactionsSingle shard onlyFull ACID, cross-table

The principle: AOF always is a persistence mechanism on one node. Sync replication is a distributed durability contract. For money, you need the latter.