Idempotency keys

Use a customer-scoped idempotency key to distinguish a completed replay from a request still in progress, preventing checkout retries from creating duplicate orders.

Learning outcomes

  • Explain why checkout retries need a customer-scoped idempotency key.
  • Use Redis SET NX to ensure only one concurrent request claims a key.
  • Distinguish pending requests from completed requests and return the appropriate response.
  • Handle failed requests and cancellation without leaving unnecessary pending claims.
  • Explain the consistency gap between a MySQL commit and recording the completed result in Redis.
Prerequisite conceptsTransaction

A customer submits POST /v1/orders, but their phone loses its connection before the response arrives. The order may already exist in MySQL. When the customer retries, the API must not create another order or charge them twice.

The client cannot know whether the first request committed. You need a way to identify multiple HTTP attempts as one logical checkout. The same mechanism must also prevent two concurrent requests from creating the same order.

The logical operation

An idempotency key identifies one logical operation rather than one HTTP request. The client generates the key when the customer starts checkout and reuses it for every retry of that checkout.

For example, the client sends:

http
POST /v1/orders
Authorization: Bearer <access-token>
Idempotency-Key: 8c1f7d42-4e5a-4e1d-9a12-123456789abc
Content-Type: application/json

The key belongs in the request header, not in the order body. W3B4 accepts keys containing between 1 and 36 characters.

The client must keep the same key until the operation finishes. Generating a new key for every retry defeats the mechanism because the server sees each attempt as a new operation.

A new checkout gets a new key.

Customer-scoped keys

An idempotency key is unique within a customer's operations, not across every customer in the system. Two customers can independently generate the same string.

You therefore combine the authenticated customer's ID with the key when storing it in Redis.

For example:

idem:42:8c1f7d42-4e5a-4e1d-9a12-123456789abc
idem:57:8c1f7d42-4e5a-4e1d-9a12-123456789abc

These are separate Redis keys because customer 42 and customer 57 are different callers.

Use the caller's authenticated user ID. Do not accept a user ID from the request body to determine the key's scope. The authentication middleware already provides the caller's identity.

This separation also prevents one customer from replaying another customer's result by choosing the same idempotency key.

Atomic key claiming with SET NX

The first request must claim the key before it starts creating the order. Otherwise, two requests could both check Redis, see that the key is missing and proceed to create separate orders.

Redis provides SET NX for this operation. NX means Redis sets the key only when it does not already exist.

redis
SET idem:42:checkout-123 pending NX EX 86400

This command performs the check and write atomically.

  • If the key does not exist, Redis stores pending and reports success.
  • If the key already exists, Redis does not overwrite it and reports that the claim failed.
  • EX 86400 gives the key a 24-hour expiration.

Only one concurrent request can successfully create the initial claim. Every other request must inspect the existing value to determine whether the first request is still running or has completed.

The expiration prevents abandoned keys from remaining in Redis forever. It does not guarantee that an order was created.

The three outcomes

The Redis store needs to distinguish three outcomes.

Redis stateMeaningHTTP response
Key does not existThis request successfully claimed the keyContinue processing
pendingAnother request is still processing the key409 request_in_progress
Order IDAn earlier request completed200 with the existing order

A completed key stores the order ID. The handler uses that ID to load the existing order and return it.

The original request returns 201. A completed replay returns 200, with the same order ID and total.

The request body does not determine the replay result. Suppose the first request places a Farmhouse order with quantity 1, and the retry sends quantity 3 using the same key. The second request still returns the first order. It must not reprice the new body or create another order.

A different key represents a different operation and can create another order.

Claim, process and resolve

The complete lifecycle has three stages.

  1. Claim: attempt to create the customer-scoped Redis key with SET NX.
  2. Process: price the requested lines and execute the MySQL order transaction.
  3. Resolve: replace pending with the order ID after success, or delete the key when the operation is rejected or fails.

The following diagram shows how requests interact with the same key.

The first request claims the idempotency key and commits one order. A concurrent second request sees pending and receives 409. A later third request sees the completed order ID and receives 200 with the same order.The first request claims the idempotency key and commits one order. A concurrent second request sees pending and receives 409. A later third request sees the completed order ID and receives 200 with the same order.

The timing changes the response, but it does not change the number of orders. Only the request that wins the claim performs the order creation.

This is the behaviour tested with 50 concurrent requests in W3B4. Exactly one response must be 201, and the database must contain exactly one order for that customer. The other responses can be 200 or 409.

Releasing rejected requests

A failed request must not permanently consume its key.

Consider a customer submitting three lines:

  • A valid Farmhouse line.
  • An item with size XL, which produces size_not_offered.
  • An unknown item ID, which produces unknown_item.

The configurator returns both pricing problems. The API responds with 400 invalid_order and includes the zero-based line indexes.

No order should be created. The handler must also release the pending key so the customer can correct the request and retry with the same key.

This is different from a completed replay. A rejected request has no order ID to store.

The same cleanup principle applies when the request context has already been cancelled.

Context cancellation during cleanup

Go cancels r.Context() when the client disconnects or the request ends. That is normally useful because database and Redis operations should stop when the request is no longer active.

However, cleanup sometimes needs to continue after cancellation.

Suppose the customer disconnects while the API is handling an invalid order. The handler needs to release the Redis key even though the original request context is cancelled.

Go's context.WithoutCancel creates a context that retains the original context values but does not inherit its cancellation or deadline.

go
cleanupCtx := context.WithoutCancel(r.Context())

if err := releaseKey(cleanupCtx); err != nil {
    return fmt.Errorf("release idempotency key: %w", err)
}

The same idea applies when marking a successful request as completed. The Redis operation should not be cancelled solely because the client disconnected after the database transaction committed.

The consistency gap between Redis and MySQL

Redis and MySQL do not share a transaction. This creates a failure window between committing the order and marking its idempotency key as completed.

Consider this sequence:

  1. Redis stores pending.
  2. MySQL commits the order, its order lines, first order event and outbox row in one database transaction.
  3. The API process crashes before Redis receives the completed order ID.

The database now contains a valid order, but Redis still contains pending.

A retry finds that pending value and receives 409 request_in_progress. In the reference implementation, the pending key has a 24-hour TTL. Retries continue receiving the conflict while that key remains pending.

After the key expires, a new request can claim it again. Since the current schema does not store the idempotency key alongside the order, the API has no durable record connecting that request key to the previously committed order. A retry could therefore create another order.

Separate request identity from event identity

An idempotency key and an order event ID identify different things.

The idempotency key identifies one customer's logical checkout. The event ID identifies a particular order event and must be unique across the entire order_events table.

Consider two customers who both choose the same idempotency key. Their Redis keys are different because their customer IDs differ. Their order events still need separate identifiers.

Keep the identities separate:

IdentifierGenerated byUniqueness scopePurpose
Idempotency keyClientPer customerIdentifies a checkout operation
Event IDServerEntire order_events tableIdentifies an order event
Order IDMySQLEntire orders tableIdentifies an order

Reusing the idempotency key as the event ID would break the global uniqueness requirement when two customers choose the same key.

The W3B4 request lifecycle

The POST /v1/orders endpoint combines these ideas.

First, the handler validates authentication, the customer's role, the key and the request body. It then claims the customer-scoped key before doing the pricing and database work.

A completed key returns the existing order with 200. A pending key returns 409 request_in_progress. A newly claimed key proceeds to server-side pricing.

If pricing rejects the order, the handler releases the key and returns the validation errors. If pricing succeeds, the order transaction writes the order, its lines, its initial event and its outbox row together.

After the database commit, the handler records the order ID in Redis and returns 201.

Week 4's Expo checkout will use this same key across retries. The important boundary is between a pending operation and a completed one: a retry must either discover the existing order or avoid creating a second one.

Check your understanding

Question 1 of 4

A customer submits an order, loses the response and retries with the same idempotency key. The first request already committed its order and marked the key completed. What should the API return?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (go-redis v9, Redis 7).

Finished Lesson 3.9?