Rate limiters, locks and transactions
Redis commands are atomic and fast, and every app server can reach the same Redis. That makes it the standard tool for coordinating many servers: limiting request rates, making sure only one worker does a job, and changing several keys together safely.
Rate limiting: fixed window
"At most 5 requests per minute per user." Count requests in a key that expires at the end of the window:
The app compares the INCR result with the limit: requests 1–5 are allowed, and the 6th gets HTTP 429 Too Many Requests. EXPIRE … NX sets the expiry only once, on the first request, so the window doesn't keep extending.
async function allowRequest(userId, limit = 5, windowSeconds = 60) {
const key = `rate:${userId}:${Math.floor(Date.now() / 1000 / windowSeconds)}`;
const [count] = await redis.multi()
.incr(key)
.expire(key, windowSeconds, 'NX')
.exec();
return count <= limit;
}Putting the window number in the key (as above) is a common variant: each minute gets a fresh key.
The weakness of fixed windows: a user can send 5 requests at 12:00:59 and 5 more at 12:01:00, which is 10 in two seconds.
Rate limiting: sliding window with a sorted set
Store each request's timestamp in a sorted set, remove the old ones, and count what's left:
The second check finds 3 requests in the window, so request #5 is rejected. This is precise, at the cost of storing one entry per request. Production rate limiters often run these steps in a small Lua script so they happen atomically.
Distributed locks
Ten servers run the same scheduled job, but it must run once. Use SET … NX with an expiry as a lock:
Three rules for correct locks:
- Always set an expiry (
PX 30000). If the holder crashes, the lock frees itself. - Use a unique value (a random token) for each holder.
- Only delete your own lock. Check that the value is still your token before deleting. Otherwise, if your work took longer than the expiry, you could delete someone else's lock. Check-and-delete must be atomic, so it's done with a tiny Lua script:
-- release.lua: delete the key only if it still holds my token
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
endawait redis.eval(releaseScript, { keys: ['lock:daily-report'], arguments: [myToken] });⚠️ A Redis lock is great for efficiency (avoiding duplicate work). For correctness (never ever two writers, as with money), also protect the data itself, for example with database constraints or version checks, because pauses and failovers can make two clients believe they hold the lock.
Transactions: MULTI and EXEC
MULTI starts queuing commands; EXEC runs them all together, with no other client's commands in between:
Notice the prompt shows (TX) while queuing, and each command replies QUEUED. DISCARD throws the queue away.
Two differences from SQL transactions:
- There's no rollback. If one queued command fails at run time (such as
INCRon a non-number), the others still run. - You can't read values in the middle and decide what to do: all commands are queued before any runs.
Optimistic locking with WATCH
To make a change that depends on a value you read (check-then-act), use WATCH. If any watched key changes before your EXEC, the whole transaction is cancelled and EXEC returns (nil). Then you retry.
Two clients try to buy the last ticket at the same time:
Asha's EXEC returned (nil): nothing ran, so the ticket count never went negative. Her app would re-read the count, see 0, and show "sold out".
Pipelining
Every command is a network round trip (often 0.2–1 ms). Sending 1,000 commands one by one wastes most of the time waiting. Pipelining sends many commands at once and reads all the replies together, which is often 10× faster or more for bulk work:
// node-redis
const batch = redis.multi();
for (const id of productIds) batch.get(`cache:product:${id}`);
const results = await batch.execAsPipeline(); // one round trip (no MULTI/EXEC wrapper)Pipelining is about speed; MULTI/EXEC is about atomicity. Clients can combine both.
Practice
- Implement a fixed-window limit of 3 requests: send 4
INCRs and decide which would be rejected. - Show that a second client can't take a lock held by a first client, then that it can after the lock expires (
DEBUG SLEEPmoves the simulator's clock). - Recreate the ticket race, but this time make Asha the faster client.
1.Why must a Redis lock always have an expiry?
2.A queued command fails inside MULTI/EXEC. What happens to the others?
3.What does EXEC return when a WATCHed key was changed by another client?