Question

What is idempotency and why does it matter for APIs?

Vault Verified
Curated Intelligence
Definitive Source
Answer

An operation is idempotent when performing it more than once has the same effect as performing it once. Setting a value to ten is idempotent; adding ten is not. The property matters because networks fail in a specific, awkward way: a client can send a request, never receive the response, and have no way to know whether the server processed it.

Without idempotency the client faces an unpleasant choice. Retrying risks doing the work twice, which for a payment or an order is a real problem. Not retrying risks losing the operation entirely. Idempotency removes the dilemma, because retrying is simply safe.

Several HTTP methods are idempotent by definition. Reading, replacing and deleting a specific resource all have the property naturally, since repeating them lands on the same final state. Creating a resource by posting to a collection does not, because each call is meant to make a new one.

The standard solution for the create case is an idempotency key. The client generates a unique value per logical operation and sends it as a header. The server records the key alongside the result, and if the same key arrives again it returns the stored response instead of doing the work a second time. Retries then converge on one outcome no matter how often the request is repeated.

Getting this right requires a few details. The key must be stored atomically with the effect, or a crash between the two reopens the same hole. It needs an expiry, or the store grows forever. And the same key arriving with a different payload should be rejected rather than silently served the old response, since that indicates a client bug.

Any API touching money or sending messages should treat this as a requirement rather than a refinement.

Related Questions