An idempotency key is a unique, client-generated identifier attached to an API request, enabling a server to safely retry operations by recognizing and returning the cached result of a previous identical request. The mechanism works by having the client generate a unique key (e.g., a UUID) for each distinct logical operation. The server, upon receiving the first request with a new key, processes it and stores the resulting response (or state change) indexed by that key. Any subsequent retry with the same key triggers a lookup; if a result exists, the server returns the stored response without re-executing the operation, thus preventing duplicate side effects like double-charging a payment or creating two database records.
Key Mechanism Steps:
- Client Generation: The client creates a unique key (e.g.,
idempotency-key: req_abc123) and includes it in the request headers.
- Server Check: The server checks its cache (often a fast key-value store) for an existing entry matching the key.
- First Request: If no entry exists, the server executes the operation, stores the final response/state, and returns the result.
- Subsequent Retries: For duplicate requests with the same key, the server returns the cached response with an appropriate status code (e.g.,
409 Conflict or 200 OK with the original result), bypassing business logic.
This pattern is foundational for building resilient distributed systems and stateful agents that must handle network flakiness and retries predictably.