Lucky Wirasakti
3 min read

Updated

Taming Campaign Traffic with Redis Locks

#Redis#Architecture#Backend

When a marketing campaign goes live nationwide, traffic does not ramp up politely. It spikes. For a voucher-distribution chatbot, that spike is the whole point — and also the thing most likely to hand the same voucher to two people at once.

The race condition

A voucher claim is a read-then-write: check that a code is still available, then mark it as taken. Under heavy concurrency, two requests can both read "available" before either writes "taken". Both succeed. The business loses money and trust.

A lock that expires

One approach is a short-lived distributed lock keyed on the resource. Redis SET with NX and a TTL gives you exactly that: only one caller acquires the key, and if a worker dies mid-claim the lock releases itself.

from uuid import uuid4

token = uuid4().hex
acquired = redis.set(f"lock:voucher:{code}", token, nx=True, ex=5)
if not acquired:
    raise Busy("try again")
try:
    claim_voucher(code)
finally:
    release_if_owner(code, token)

A lock without a TTL is just a future outage with extra steps.

Rate limiting at the edge

Locks protect correctness; rate limits protect the system. A per-user token bucket in Redis kept individual numbers from hammering the campaign endpoint, which smoothed the load enough that the locks rarely contended in the first place.

  • Lock on the smallest resource that needs protection, not the whole request.
  • Always set a TTL — assume every worker can crash.
  • Release only if you still own the lock, to avoid freeing someone else's.

Context from my work

At Erasys Consulting, I worked on distributing 50,000 unique voucher codes through the WhatsApp Business API. A key concern was handling claims arriving at the same time. The implementation described in my work experience used pessimistic locking and database transactions; the Redis example here illustrates an additional approach to coordinating requests, rather than replacing those transactions.

Limits of this approach

A TTL releases a lock after a worker stops, but it can also expire before the work finishes. Use a unique token for each claim attempt and an atomic release that checks the owner's token. The database still needs to enforce claim rules. See the Redis documentation for lock validity and release semantics.

The distinction I want to highlight is between traffic coordination and business rules: rate limiting controls incoming requests, while transactions determine whether a claim can be saved. The 50,000 figure describes campaign inventory, rather than a throughput benchmark.

Read the webhook delivery notes or my work experience.