Kest

Search

Search the documentation

Reliability

Idempotency keys

Make "retry" safe: the same request is carried out once.

A customer taps Pay, the connection drops, the app does not know whether it worked, and retries. Without protection you charge twice. Idempotent means "doing it twice has the same effect as doing it once". GET, PUT and DELETE already are. POST is not, so clients send a unique Idempotency-Key header (a UUID they make up) with every attempt of the same operation, and the server carries it out once.

POST /payments                  Idempotency-Key: 5b1e...      -> runs the handler, 201, the response is stored
POST /payments                  Idempotency-Key: 5b1e...      -> replays the stored 201 (header Idempotent-Replayed: true); nothing is charged again

Turn it on

app.http(adapter) {
    useMiddleware(IdempotencyMiddleware(IdempotencyOptions().apply {
        required = true                      // a POST or PATCH without the header is a 400
        ttl = Duration.ofHours(24)           // keys are remembered for a day
        store = myStore                      // see below
    }))
}

Nothing changes in your controllers: the middleware sits in front of them.

What it answers

SituationResponse
First request with this keyyour handler runs; the response is stored (2xx, 3xx and 4xx; 5xx are not stored so a retry gets another chance)
Same key, same request, handler finishedthe stored response, with Idempotent-Replayed: true; the handler does not run
Same key, first request still running409 Conflict with Retry-After: 1
Same key, but a different method, path, query or body422: the key was used for something else (probably a client bug)
No key, required = true400
Key longer than 255 characters400

"Same request" is decided by a fingerprint of the method, path, query and body, so a client cannot reuse one key for two different payments.

Who owns a key

By default keys are kept apart per caller (scope is the Authorization header), so user A can never replay, or block, user B's key. Change it to whatever identifies the caller, for example the tenant:

scope = { request -> request.header("x-tenant") ?: "" }

Several instances: use a shared store

InMemoryIdempotencyStore (the default) lives in one process. Behind a load balancer the retry may reach another instance, which has never seen the key. Implement IdempotencyStore over Redis or your database. The contract is small:

MethodMust do
begin(key, fingerprint, ttl)atomically claim the key; return true if you were first (Redis: SET key value NX PX)
fingerprint(key)the fingerprint saved by begin, or null
get(key)the finished response, or null while running
complete(key, response, ttl)save the response
abandon(key)forget the key (used after a 5xx so a retry can run)

Client side

Generate the key once per operation, not once per attempt, and keep it until you know the outcome:

val key = UUID.randomUUID().toString()
retry(3) { http.post("/payments", body) { header("Idempotency-Key", key) } }

Idempotency inside your own code

The middleware protects an HTTP endpoint. For a queue consumer or an event handler, de-duplicate on the message id yourself, with a unique constraint:

@OnEvent("order.paid") fun onPaid(e: OrderPaid) {
    if (!processed.insertIfAbsent(e.eventId)) return        // INSERT ... ON CONFLICT DO NOTHING; false when it was already there
    ship(e.orderId)
}

Read more