Core Concepts

Redis

Serve hot reads and coordinate short-lived work with Redis data structures.

Free~22 min

Redis keeps values in memory and runs commands directly on them. Reach for it when many requests need the same small value quickly, or when concurrent clients need to update a counter or share short-lived coordination state.

Start with a durable store for the records the product must keep. PostgreSQL can own the current status of a dashboard export, and object storage can hold its CSV. Redis can serve repeated status reads and help the application notify viewers or share background work.

Read a hot value through Redis

The export service looks up export 17 with the key export:17:status. When GET finds no key, redis-cli displays (nil). The application reads PostgreSQL, gets ready, and fills Redis with a time to live (TTL) of 60 seconds. This pattern is cache-aside. The application loads the cache when it needs a value.

Example redis-cli session. The redis> prompt marks commands. The PostgreSQL lookup happens between the first GET and SET.

redis> GET export:17:status
(nil)
 
redis> SET export:17:status ready EX 60
OK
 
redis> GET export:17:status
"ready"
 
redis> TTL export:17:status
(integer) 57

EX 60 sets the lifetime in seconds, and TTL reports how many seconds remain. The cache hit returns the stored copy and avoids another database query. Follow the two read paths below. Redis SET · Redis TTL

A delayed fill can restore an old value

Earlier, while export 17 is still running, a reader misses the key and loads that status from SQL. The reader pauses. A writer finishes the export, commits ready to SQL, and deletes the Redis key. If the reader now fills Redis with running, the old value gets a fresh 60-second TTL.

Delete the cached value after the database commit to narrow the window for stale reads. A screen that needs an up-to-date confirmation can read the SQL primary. If other readers can tolerate a brief stale value, use a short TTL.

To reject a fill that races with an invalidation Redis has already received, keep the invalidated row's new revision in Redis. Compare the fill's revision to that marker and write only if the fill is at least as new. Do the comparison and write in one Redis operation, and keep the marker long enough to cover delayed fills.

A missing key can also mean eviction

At the end of the TTL, Redis treats the key as expired. Redis can also remove it before the deadline if memory pressure triggers eviction under its maxmemory policy. A reader sees the same cache miss either way.

redis> GET export:17:status
(nil)
 
redis> TTL export:17:status
(integer) -2

TTL returning -2 means the key is gone. Redis has policies that favor keeping recently used keys (LRU) or frequently used keys (LFU). With noeviction, reads still work and fills that add memory can fail when Redis is full. The cache-aside request can still return the SQL result. Redis key eviction

Choose a data structure by what the application does

The export status can be a string because the application reads the whole value. Other parts of the service need different operations.

OperationRedis structureCommands
Read or replace export 17's statusStringGET, SET
Update one cached metadata fieldHash, a set of named fields under one keyHSET, HGET
Count status pollsString storing an integerINCR
Check whether an export is activeSet, a collection with unique membersSADD, SISMEMBER
List recent exports in time orderSorted set, with a timestamp as each member's scoreZADD, ZRANGE
Keep completion events for readers to replayStream, a sequence of entries with ordered IDsXADD, XREAD

Two application requests might both read a count of 41, add one, and each write back 42. INCR export:17:polls increments the number in one command. When two clients send it to the same primary, the two commands return 42 and 43 in execution order.

redis> INCR export:17:polls
(integer) 42
 
redis> INCR export:17:polls
(integer) 43

A Redis transaction with MULTI and EXEC, a Lua script, or a Redis Function can run several operations without interleaving from other clients. If an executed command in a transaction fails, other valid commands can still take effect. Validate inputs before writing in a script because earlier writes can survive a later script error. Redis transactions · Redis Lua scripts

Share cache rebuild work with a short lease

When a popular key disappears, many requests can hit SQL at once. This is a cache stampede. On one Redis primary, use a second key, export:17:rebuild, to let one worker fill the cache while others briefly wait and recheck it. Give the key a deadline so work can continue if its owner crashes. That time-limited claim is a lease.

redis> SET export:17:rebuild worker-a:01 NX PX 2000
OK
 
redis> SET export:17:rebuild worker-b:try NX PX 2000
(nil)

NX sets the key only when it is absent. PX 2000 gives the lease two seconds. Use a fresh, random value each time you try to acquire it. These readable tokens identify the two workers in the example.

Suppose worker A pauses for longer than two seconds. The lease expires, so worker B can acquire it.

redis> SET export:17:rebuild worker-b:02 NX PX 2000
OK

When A resumes, it can attempt to release its own lease by comparing the stored token and deleting the key in one atomic operation. Save this Lua script as release-rebuild.lua.

if redis.call("GET", KEYS[1]) == ARGV[1] then
  return redis.call("DEL", KEYS[1])
end
return 0

While B still holds the lease, A's release returns zero. The key remains owned by B.

$ redis-cli --no-raw --eval release-rebuild.lua \
    export:17:rebuild , worker-a:01
(integer) 0
 
redis> GET export:17:rebuild
"worker-b:02"

A worker can keep running after the key expires. The random token makes release safe. To enforce ownership of a durable action, have the protected resource reject older fencing tokens, numbers that increase for each owner, or enforce the rule in PostgreSQL. A Redis lease is enough for this cache rebuild if duplicate work is tolerable. Redis lease pattern · Distributed Locking

Send the same ready event to two kinds of reader

The SQL update to ready is committed. Now the export service can send an event so the browser refreshes or a worker creates a notification.

Pub/Sub for viewers who are connected now

A subscriber watches the channel export:ready:live with SUBSCRIBE. Assume one viewer is subscribed and another is offline when the service publishes the export ID and status.

redis> PUBLISH export:ready:live "17 ready"
(integer) 1

The integer counts subscribers Redis sent the message to on this server. Pub/Sub has no acknowledgment that a subscriber handled the message. The online viewer gets 17 ready. An offline viewer gets no message when it reconnects because Redis Pub/Sub keeps no history. Treat the update as a refresh hint and fetch current status on reconnect. Redis PUBLISH · Pub/Sub delivery

A Stream for readers who need the event later

The service can instead append event fields to export:ready:stream. Redis assigns an ordered ID when XADD gets *. On a fresh stream, a reader can start from 0-0 and use XREAD to get entries after that ID. A returning viewer can supply the last ID it applied.

redis> XADD export:ready:stream * export_id 17 status ready
"1795867200000-0"
 
redis> XREAD COUNT 1 STREAMS export:ready:stream 0-0

Decoded RESP2 reply for XREAD, shown as JSON.

[
  ["export:ready:stream", [
    ["1795867200000-0", ["export_id", "17", "status", "ready"]]
  ]]
]

Recover an interrupted notification worker

To have workers divide the notification jobs, create a consumer group. The group has a position for new entries plus a pending entries list for entries already assigned to workers. The > in XREADGROUP asks for an entry that the group has yet to deliver.

redis> XGROUP CREATE export:ready:stream export-notifiers 0-0
OK
 
redis> XREADGROUP GROUP export-notifiers notifier-a COUNT 1 STREAMS export:ready:stream >

Notifier A gets the same stream entry shown above. Redis adds its ID to the group's pending list under notifier-a. Suppose A commits the notification to SQL, then crashes before acknowledging the entry. After 30 seconds of idle time, notifier B can take over.

redis> XAUTOCLAIM export:ready:stream export-notifiers notifier-b 30000 0-0 COUNT 1

Decoded reply on Redis 7.0 or later. The first field is the next scan position. Here 0-0 marks the end of the scan. The second field holds the claimed entries, and the third lists missing stream entries that Redis removed from the pending list during the scan.

[
  "0-0",
  [["1795867200000-0", ["export_id", "17", "status", "ready"]]],
  []
]

B attempts the same notification write. A unique SQL constraint on the export ID and notification kind lets B recognize the notification already exists. Now B sends XACK. The result 1 means Redis cleared one pending entry for the group. The event still exists in the stream.

redis> XACK export:ready:stream export-notifiers 1795867200000-0
(integer) 1

The idle clock measures time since Redis delivered the entry or another worker last claimed it. It can cross the threshold while a worker is still processing the event. Make the durable effect safe to repeat, and acknowledge only after it completes. Redis XREADGROUP · Redis XAUTOCLAIM · Redis XACK

Keep enough history to replay

Redis Streams use memory. Choose a retention limit that leaves room for the longest outage viewers and workers need to recover from. Later, if the stream holds 10,001 entries, trimming to exactly 10,000 removes one from the oldest end.

redis> XTRIM export:ready:stream MAXLEN = 10000
(integer) 1

If the cap removes a pending entry's payload, a worker can no longer replay that payload from the stream. Monitor idle pending work and the oldest retained entry. Use Kafka or a dedicated log when the design needs long retention or independent partitions. Redis XTRIM

Plan for memory limits and failover

Disk persistence helps a Redis process recover its data after restart. Redis can periodically save a snapshot of the dataset (RDB) or append writes to a log (AOF). The snapshot can miss writes since it was taken. With an append-only log that syncs once per second, a crash can still lose recent writes. Redis persistence

Replication sends writes to another server and is asynchronous by default. If the primary acknowledges the export event and fails before its replica gets the entry, the promoted server can lack that event. The export status and file are still available from their durable stores. Redis replication

When a SQL status change must lead to a notification, write the change and an event record in one database transaction using a transactional outbox. Keep the outbox row until the notification exists in SQL. A periodic job can find events without a completed notification and publish them again, including events Redis previously acknowledged. The unique notification constraint makes those retries safe.

Redis Cluster spreads keys across hash slots, groups of keys that are served by particular shards. A transaction or Lua script that works across keys needs them in the same slot. A shared hash tag places two keys together, such as export:{17}:status and export:{17}:rebuild. One stream key still lives on one shard. If you split work across more stream keys, define what ordering you need across them. Redis Cluster hash tags

How to use in a system design

Start with the operation and the load. If 5,000 dashboard tabs poll the same export every two seconds, that is 2,500 status reads per second. Keep PostgreSQL as the owner of the status. When repeated reads become a bottleneck and the dashboard can tolerate a brief stale value, cache that one small result for 60 seconds. The key is export:17:status, so all those requests can reuse one fill. Bound concurrent rebuilds with a short lease and return the SQL result if Redis rejects a write. A database read is the simpler path if the load is low or the answer must be current.

For live refreshes, use Pub/Sub and have reconnecting viewers fetch current state. Use a Stream when a worker needs replay. Give it its own memory budget if cache keys can be evicted, set retention from the recovery window, and track the age of pending work. When missing a notification would break the product, keep a durable outbox entry and acknowledge delivery only after the idempotent effect commits.

See also

  • Idempotency - makes retried Stream work safe to repeat.
  • Data Replication - frames primary, replica, lag, and failover behavior.
  • Consistency Models - explains the stale-read boundary around replicas and caches.
  • Distributed Locking - compares leases, fencing, and correctness assumptions across coordination stores.
  • Messaging and Work Queues - compares work sharing, fan-out, retention, and replay.
  • Caching - follows a cache hit, a stale fill, and overlapping misses.
  • Live Updates and Reconnects - pairs a stream cursor with the state the browser already applied.
  • Memcached (forthcoming) - a simpler cache without Redis's broader data structures.

Used in

  • ChatGPT - holds reply events for reconnects, account rate counters, and short-lived publishing leases.
  • Batched Inference Service - stores short-lived results by request ID for polling.
  • Online Chess - pushes live moves with Pub/Sub while durable game history supplies replay.
  • Crossword Solver Service - stores temporary progress keyed by job and attempt.

Done reading? Mark it so it sticks in your dashboard.

Discussion