• 4 min read • Backend Engineering

Idempotency keys are a caching problem

Retries are unavoidable in a distributed system. A mobile client loses signal mid-request, a load balancer times out and resends, a user gets an ambiguous spinner and taps buy a second time thinking the first tap didn’t register. None of that is a bug. The bug is in what the server does with the second copy of a request that already ran.

The usual framing is “payments need idempotency keys, because double-charging is bad.” That’s true, but it hides how general the fix is. Without the payments context it’s a cache: a key, a lookup before doing work, a write after, and a TTL. It differs from an ordinary cache only in where the key comes from and what a hit means.

Same mechanism, different vocabulary

Ordinary cacheIdempotency key
Key originDerived from the request by the serverGenerated by the client, opaque to the server
Hit means”Recomputing would give the same answer, skip it""This exact request already happened, return what happened”
Miss meansCompute it, store itDo the real work, then store the result
InvalidationTTL or explicit evictionTTL only, and it has to outlast every plausible retry window

The structural difference is who defines “the same request”. A normal cache key can be rebuilt from the request body on the server, because two requests with the same body are interchangeable. An idempotency key can’t, because its job is to tell a retry apart from a second, deliberate request that looks identical. Only the client knows which one it’s sending, so the client supplies the key.

Seen this way, the test for whether an endpoint needs one is whether it has a side effect and whether the client’s network conditions can make it send the same request twice. Any POST that creates a row, decrements a counter, sends an email, or charges a card qualifies. A GET doesn’t need this because a GET is already safe to repeat by definition; a POST /orders isn’t, unless something makes it act like one.

What it looks like in a real checkout path

flash-sale-system’s /pay endpoint takes a client-generated UUIDv4 as an Idempotency-Key header. The server namespaces it by the authenticated user before touching Redis:

# backend/services/payment_service.py
idem_key = f"idem:pay:{user}:{request.idempotency_key}"

cached = await self.r.get(idem_key)
if cached:
    data = json.loads(cached)
    return ProcessPaymentResponse(
        status=data["status"], quantity=data["quantity"], message="idempotency cache hit"
    )

The user prefix has nothing to do with retries. Without it, a key generated by one user could be replayed by anyone who obtained it, since Redis has no notion of who’s asking. Namespacing by user means a leaked idempotency key only ever replays inside the account it belongs to.

On a miss, the server does the real work in four steps and writes the cache entry last:

  1. Confirm the reservation is still held
  2. Run the payment
  3. Write to the outbox table
  4. Cache the response
await self.r.setex(idem_key, 86400, json.dumps(response_data))

86400 seconds is 24 hours, and that number is the whole idempotency guarantee. It is long enough to cover a browser reconnecting or a mobile client resuming from the background, short enough that Redis doesn’t accumulate stale keys forever. Too short, and a slow retry after the TTL expires reruns the request as if it were new. Too long, and it’s a slow memory leak.

What a key like this doesn’t cover

An idempotency key stops a retried request from re-running. It does nothing for a second, deliberate request, because from the client’s perspective that’s a new key. If a user taps buy twice on purpose, both taps are legitimate new requests as far as the server is concerned, and handling that is a different problem (disabling the button, confirming intent).

The same key also answers “did this already happen?”:

# GetPaymentStatus
idem_key = f"idem:pay:{request.user_id}:{request.idempotency_key}"
cached = await self.r.get(idem_key)
if cached:
    data = json.loads(cached)
    return GetPaymentStatusResponse(status=data["status"], quantity=data["quantity"])
return GetPaymentStatusResponse(status="not_found", quantity=0)

A frontend that isn’t sure whether its request succeeded can poll this instead of guessing, which gives the user one less reason to hit buy again.

Not to be confused with rate limiting

/reserve sits behind a separate Redis check, an INCR plus a first-hit EXPIRE, that looks similar but solves a different problem:

RATE_LIMIT_DURATION = 60
RATE_LIMIT_MAX = 5000

async def check_rate_limit(request: Request):
    client_ip = request.client.host if request.client else "unknown"
    key = f"rate_limit:{client_ip}"
    try:
        current = await r_async.incr(key)
        if current == 1:
            await r_async.expire(key, RATE_LIMIT_DURATION)
        if current > RATE_LIMIT_MAX:
            raise HTTPException(status_code=429, detail="Too many requests. Slow down!")
    except redis.ConnectionError:
        print("Rate limit check skipped (Redis down)")

Both use Redis and both sit in front of a write, which is where the confusion comes from. They answer different questions and deliberately fail in opposite directions:

KeyQuestion it answersFails
idem:pay:{user}:{key}Has this exact request already happened?Closed, retry gets the cached result
rate_limit:{ip}Has this client sent too many requests?Open, if Redis is down the limiter gets out of the way

If Redis is unreachable, the rate limiter’s except redis.ConnectionError branch lets requests through instead of blocking every buyer during a sale. A missed rate-limit window during an outage is recoverable; refusing every legitimate request is much worse. An idempotency check can’t make that trade, because failing open means paying twice.

The gap it doesn’t close

None of this replaces a uniqueness constraint in the database. The outbox table has no unique constraint tying a row back to an idempotency key. A crash between the outbox write and the Redis setex would leave no cached response to catch a third retry, and the outbox itself wouldn’t reject a duplicate insert. In this system the Redis key is the only protection against a duplicate charge in that gap. That’s an acceptable bet for a 24-hour cache and a poor one for a permanent record.

Back to top