Explainer · Engineering
What is an idempotency key: and why your app needs one
Every offline-capable app eventually answers the same question: what happens when the user taps "send" twice, or the network dies mid-request and the client retries? The answer is a small mechanism called an idempotency key, here is how it works, and how it looks in our own code.
The problem in one sentence
Networks are unreliable, so clients must retry; retries mean the same logical action arrives more than once; without protection, "more than once" becomes two time entries, two invoices, two bookings.
Note what the problem is not: it is not "the user double-clicked." Users do double-click, but the common case is far less visible, a mobile app on a construction site loses signal, queues the clock-in, the server applies it, the response dies in transit, and the app (correctly) sends it again. The duplicate is the system working as intended.
The mechanism
An idempotency key is a unique identifier the client generates per logical action, not per HTTP request. The client attaches the same key to the original request and every retry of that action. The server keeps a record of keys it has seen; when a key arrives twice, the server returns the first result instead of executing the mutation twice.
Three properties make it work:
- The client owns the key. If the server issued it, a retry before receiving it could not be identified. The key is minted on the device, in our mobile apps a UUID created the moment the user stamps, not when the network call fires.
- The record is a claim, not a result. The server writes the claim first ("this key is mine, outcome pending"), then mutates. A concurrent retry finds the claim and waits for or replays the original outcome, it can never slip a second mutation underneath it.
- The claim binds the payload. We store a hash of the action and its normalized inputs with the key. Same key, different payload → a 409 conflict, not a silent overwrite. A retry should only ever mean "the same thing again."
Where it shows up in our apps
ArbeitszeitCheck's mobile stamp queue carries a clientRequestId through every replay; TourCheck binds the same contract to client_event_id on checkpoint confirms, where a replay compares the whole claim, note, photo, timestamp, against the stored row. The expiry matters as much as the dedupe: our claim rows live seven days, long enough to cover a long weekend of dead coverage, short enough that the table stays a queue and not a log.
The short version for your own app
If your API mutates state and your client can retry, and every client can retry, you need exactly three things: a client-generated key per action, a first-write claim row, and a payload hash so "same key" also means "same intent." That is the whole pattern. Everything else, replay windows, cleanup jobs, conflict status codes, is plumbing around those three commitments.