Idempotent Create Endpoints: Making POST Safe to Retry
A request can fail after the server has already done the work: the connection drops, the client times out, a proxy retries. If the endpoint creates something, a naive retry creates it twice. An idempotent endpoint gives the same result however many times the same request arrives, so clients can retry without fear.
Reads, PUT and DELETE are naturally idempotent. POST /things is not — and it is the one clients most need to retry.
The idempotency key
The standard fix is to let the client name the attempt. The client generates a unique key (a UUID) for each logical operation and sends it with every retry of that operation:
POST /api/users
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
{
"username": "johndoe",
"email": "[email protected]",
"password": "…"
}
The server remembers which keys it has already processed and what it answered.
On the server
- Look the key up.
- If it has been seen, return the stored response. Do not run the operation again.
- If not, run the operation and store the key with its result in the same transaction as the creation, so a crash cannot leave one without the other.
def create_user(key, data):
with db.transaction():
seen = db.find_idempotency_record(key)
if seen:
return seen.response # replay: same status, same body
if db.user_exists(data["username"], data["email"]):
response = ({"error": "username or email already in use"}, 409)
else:
user = db.create_user(data)
response = ({"user": user}, 201)
db.save_idempotency_record(key, response)
return response
A retry with the same key gets the original 201 and the same user back. A different request that collides on username or email gets a 409, because it really is a different attempt.
Details that matter
- Make the key unique in the database. Two retries can arrive at the same moment, and a unique constraint on the key turns that race into a clean conflict instead of a duplicate.
- Store the full response as well as the key. Replaying the exact status code and body is what makes retries invisible to the client.
- Check the payload. If a key comes back with a different body, that is a client bug. Reject it (
422) rather than replay a response to a different question. - Expire old keys. A day or a week is plenty, since the keys only exist to catch retries.
- Natural keys work too. If the entity already has a client-chosen id, as in
PUT /api/users/<uuid>, the id itself is the idempotency key, and the endpoint becomes an upsert.