In this document, you'll learn what an idempotency key is in Medusa.
An Idempotency Key is a unique, randomly generated key associated with an operation, such as the cart completion process. The idempotency key can be passed in the header of a request to an API Route. This allows you to safely retry requests without accidentally performing the same operation twice.
For example, if a connection error occurs while the customer is completing their cart and placing an order, you can retry from the last recovery point before the error occurred.
When an operation first starts, the idempotency key is generated using the
v4 method. Then, the backend sets the following headers in the response:
<IDEM_VAL> is the idempotency key generated.
These headers can then be passed again for subsequent retrying requests and will be available on the response of these requests as well. The value of the idempotency key remains the same across requests and responses, even if an error occurs and you retry the request.
For example, when the cart completion process starts, the Medusa backend generates the idempotency key and sets the necessary headers on the response. If an error occurs in the request, you can later retry the request by passing these same headers in your request.
IdempotencyKey Entity Overview
The idempotency key's data is stored within the
IdempotencyKey entity. Some of its attributes include:
idempotency_key: a unique string indicating the value of the idempotency key.
request_method: a string indicating the method of the latest request related to the idempotency key's operation. For example,
request_params: a JSONB object indicating the parameters of the latest request related to the idempotency key's operation.
request_path: a string indicating the path of the latest request related to the idempotency key's operation.
response_code: a number indicating the response code of the latest request related to the idempotency key's operation.
response_body: a JSONB object indicating the response body of the latest request related to the idempotency key's operation.
recovery_point: a string indicating the point to continue from when retrying the request. The default value is
Idempotency Key Stages
Idempotency key stages are the different recovery points that are available for an operation. Every operation has at least the
For example, the cart completion operation has the following stages or recovery points:
You can use the
IdempotencyKeyService in your custom development to ensure requests can be safely retried or continued.
Learn how to use the IdempotencyKeyService in your code.