Skip to content

Lesson 3 of 9 · 27m

Expiration, Idempotency, and Atomic Multi-Step Operations

Use TTLs, compare-and-set patterns, pipelines, and Lua correctly so retries and concurrency do not corrupt state.

Production Redis bugs are often retry bugs wearing a costume. A payment client times out, retries, and creates two jobs. A deploy overlaps an old worker with a new worker and both consume the same lock. Redis gives you strong primitives, but only if you use them atomically and understand what is not atomic.

Expiration is a lifecycle tool, not cleanup magic

Set TTLs when data becomes meaningless, dangerous, or expensive after a deadline:

SET password-reset:9f31 token-value EX 900
EXPIREAT session:01JRYC 1780003600

SET ... EX is preferable to setting a value and expiring it in a second operation because a client crash between commands would otherwise create immortal state. Check what your client library actually sends; convenience wrappers sometimes hide multi-command behavior.

Understand volatile versus durable data

TTL interacts with eviction and replication in ways operators need to know. Expired keys disappear lazily when accessed and actively through Redis's expiration cycle. A replica may still return a key briefly around expiration timing because expiration is replicated as deletion events. If correctness depends on time, compare an explicit timestamp in the value instead of trusting wall-clock-perfect disappearance.

Idempotency keys need atomic compare-and-set

Use SET key value NX EX ttl as a one-command claim:

SET idempotency:checkout:ord_881 "processing" NX EX 300

Possible outcomes:

OK      -> caller owns the operation
nil     -> key exists; inspect status before deciding

Do not implement this as GET, then SET if absent. Two clients can both pass the GET check. For robust workflows store a state value such as processing, complete, or a payload hash, then update it according to carefully designed transitions.

Lua is atomic but not free

A Lua script runs without interleaving commands from other clients. That makes it suitable for small invariants:

-- claim.lua
if redis.call('EXISTS', KEYS[1]) == 1 then
  return 0
end
redis.call('SET', KEYS[1], ARGV[1], 'EX', tonumber(ARGV[2]))
return 1
redis-cli EVAL "$(cat claim.lua)" 1 claim:job-901 worker-17 60

Because scripts block the server, they must be short, deterministic, and bounded. Never loop over an unbounded keyspace. If a script can run for seconds, it is a denial-of-service tool.

Pipelines are not transactions

Pipelining reduces round trips. MULTI/EXEC groups commands, but it is not a rollback-capable relational transaction. If one queued command is syntactically valid and then fails at execution type checks, others may still run. Design for partial effects or use Lua when the invariant truly matters.

Field notes

  • GETSET and INCR are atomic; read-modify-write pseudo-code in your application is not.
  • TTL jitter helps avoid synchronized expiry stampedes for hot cache keys.
  • Use PEXPIRE only when millisecond semantics are genuinely needed; seconds are easier to audit.
  • Distributed locks are a sharp tool. Prefer idempotency and uniqueness constraints before reaching for Redlock-style designs.

Was this lesson helpful?

Sign in to rate