← Building blocks

Do read-modify-write atomically

Consistency & coordinationfundamental

Two requests read the same counter and both write +1, losing an increment.

Say it like this

The rate-limit check is a read-modify-write that two gateways can race on, so I run it as one atomic Lua script in Redis instead of a GET followed by a SET.

Basic solution

Use an atomic primitive: INCR, a Lua script, a conditional update, or a transaction.

Redis INCR / EVALSHASQL UPDATE ... SET n = n + 1CAS

Race in the app vs one script in the store

Top: two gateways both read 3 tokens and both write 2, losing a decrement. Bottom: the same logic runs as one script on the Redis thread, so the second caller sees 2 and writes 1.

How it works

  1. A naive counter does three things in the application: GET n from the store, compute n + 1 locally, then SET n + 1 back. If two requests both GET while n is 3, both compute 4 and both SET 4, so one increment is lost.
  2. An atomic primitive moves the read-modify-write into the store, where it runs as one indivisible step that no other command can interleave with: INCR in Redis, UPDATE ... SET n = n + 1 in SQL, or a compare-and-set that writes only if the current value is what you expect.
  3. For multi-step logic (read two keys, decide, write one), bundle the whole thing in a Lua script in Redis or a transaction in SQL. The store runs the script or transaction to completion before touching the next command, so nothing can change the keys halfway through.
  4. The store executes the operation on one thread or under one lock and returns the result, so every caller sees a consistent before and after: the second caller's read already includes the first caller's write.
  5. Atomicity is scoped to one node or one row. Across shards or stores there is no single thread or lock to rely on, so you need a different tool: a saga, an outbox, or an idempotent retry.

The single-threaded trick

  • Redis runs one command (or one script) at a time per node, so any script is atomic by construction. That is why rate limiters and counters live there.

Worked example

Rate limiter, token bucket in Redis

  • 100 requests per minute per API key, 50,000 active keys, 20 gateways calling in parallel.
  • Each request runs EVALSHA with the key: read tokens and last refill time, add tokens for the elapsed time (up to the cap), subtract one if available, write both values back, return allowed and remaining. All in one script, about 30 microseconds of Redis time.
  • Without the script: GET, compute, SET is two round trips of about 0.3 ms each and a race window of several hundred microseconds during which another gateway can read the same tokens. At 20 gateways and bursty clients the limit is routinely overshot by a few percent, which for a limit that protects a downstream service is a real overload.
  • Throughput: one Redis node does about 100,000 scripts per second; the fleet needs about 8,000 per second at peak. One primary with a replica is enough, with more than 10× headroom.
  • Related SQL version: UPDATE buckets SET tokens = tokens - 1 WHERE key = ? AND tokens > 0; a zero row count means the caller is limited, and the check and the decrement happened in one statement.

Variants and when each wins

Single-command atomics (INCR, DECR, HINCRBY, SQL n = n + 1)

  • One command that reads, changes and writes a value inside the store. It wins whenever the logic is one arithmetic step, because it is the simplest and fastest form.

Scripted or transactional (Redis Lua, SQL transaction with a row lock)

  • Several reads and writes bundled so they run as one indivisible unit. It wins for multi-key or conditional logic such as a token bucket; keep Lua scripts to a few operations because the node does nothing else while one runs.

Compare-and-set (CAS, conditional writes, DynamoDB ConditionExpression)

  • Write only if the value is still what you read, and fail otherwise so the caller re-reads and retries. It wins when contention is low, because no lock is held and the happy path costs nothing extra.

Local aggregation then atomic flush

  • Count in process memory and send one INCRBY with the total every 100 ms. It wins when the counter is extremely hot, cutting store traffic by orders of magnitude at the cost of a 100 ms window where the stored count lags.

Recommendation: a single atomic command when it fits, a Lua script for multi-step limits, CAS for low-contention updates, and local aggregation when the counter is extremely hot.

Failure modes

Lost update

  • You notice a counter that is lower than the number of events you can count in the logs. It happens because the read-modify-write runs in the application, so two concurrent requests read the same value and one overwrites the other's increment. Move the increment into the store as an atomic command.

Non-atomic INCR plus EXPIRE

  • You notice rate-limit keys that never expire, so a client stays limited forever after a crash. It happens because INCR and EXPIRE were two separate commands, and the process died between them, leaving a key with no TTL. Use SET with EX and NX for the first write, or a script that increments and sets the expiry together.

Long script blocks the node

  • You notice Redis latency spiking to tens of milliseconds for every client at once. It happens because a Lua script is iterating over thousands of keys, and Redis runs nothing else until the script finishes. Keep scripts to a few operations, and do heavy work in batches outside the store.

Atomic on one shard, not across

  • You notice a global limit being overshot by roughly the number of shards. It happens because the key was split across shards and each shard enforces its own copy of the count. Route one logical counter to one shard, or accept the approximation and size the limit accordingly.

Retry after a timeout double-applies

  • You notice a client that timed out, retried, and was charged twice. It happens because the first increment succeeded inside the store but the reply was lost on the network, so the retry incremented again. Store an idempotency key with the result inside the same atomic step, so the retry finds the key and returns the stored result instead of incrementing.

Interviewer follow-ups

Answer out loud before you open each one.

Why is a Lua script atomic in Redis?

Redis executes commands on a single thread per node and runs a script to completion before touching the next command, so nothing can interleave. The guarantee is per node; keys on different shards are not covered.

How do you make INCR and EXPIRE atomic?

Either SET key 1 EX 60 NX on first use and INCR afterwards, or a two-line Lua script that increments and sets the expiry if the result is 1. The point is that a crash between the two steps must not leave a key without a TTL.

Compare CAS with a lock.

CAS never blocks: it attempts the write and fails if someone else changed the value, so the caller retries. A lock blocks others until the holder finishes. CAS wins at low contention; a lock wins when retries would thrash.

What is the atomic step in a key generation service?

Claiming a batch of unused keys: mark N rows used and return them in one transaction, so two app servers can never receive the same key. In Redis that is SPOP with a count, which removes and returns members in one command.

Connections

Pairs with
Limit requests per client · Make sure only one worker does it · Make retries safe · Detect conflicting updates
Pulls against
Partition the data
Used in
Distributed Rate Limiter · Distributed Key-Value Cache (Redis / Memcached-like)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon API GatewayGateway A, Gateway BAPI Gateway, ApigeeAPI ManagementKong, Tyk
Amazon ElastiCacheRedis (naive), Redis (script)MemorystoreAzure Managed RedisRedis, Valkey, Memcached