Idempotency keys are unique identifiers that API clients can provide in HTTP request headers to ensure that a specific API request is not processed multiple times even if it is accidentally sent more than once. This mechanism helps maintain data consistency and prevent undesired side effects like duplicated transactions or repeating customer notifications.
Idempotency keys can be passed to most of the non-idempotent endpoints through a custom header x-idempotency-key
. The value of this header should be a unique operation identifier. If the request with the same idempotency key and body has already been processed in the past the response body will be stored in a temporary storage for 48 hours and returned to all subsequent requests with 409 Conflict
status code. The 409 responses can be handled by the API client as if it would be a successful response. The use of a separate response code can help API consumers identify the root cause for duplicated requests and fix the issue.
In some cases when two duplicated requests are sent within a short interval of time it is possible that a 423 Locked
response code will be returned. The 423 response indicates that the API started processing the previous request, but the response was not generated yet. The API client should retry the request after a reasonable amount of time.
Find below an example of code that illustrates implementing the idempotency keys mechanism using Python's requests
library.