What is idempotency, and how do you make a POST request safe to retry?
MediumConceptAPIs & Communication
Answer
An operation is idempotent if performing it several times has the same effect as performing it once. Retries are unavoidable in distributed systems, because a timeout does not tell the client whether the server processed the request, so non-idempotent operations such as payments need protection against duplicates.
- Idempotency key: the client generates a unique ID (for example, a UUID) per logical operation and sends it in a header such as
Idempotency-Key. - The server stores the key with the result; a repeated request with the same key returns the stored result instead of executing again.
- Use a unique constraint or an atomic insert on the key so that two concurrent retries cannot both run.
- Expire stored keys after a suitable window, such as 24 hours.
More in APIs & Communication
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is a REST API, and what makes an API RESTful? | Concept | Easy | Read the answer to What is a REST API, and what makes an API RESTful? | |||
| 2 | When would you choose REST, GraphQL or gRPC? | Concept | Medium | Read the answer to When would you choose REST, GraphQL or gRPC? | |||
| 3 | What is idempotency, and how do you make a POST request safe to retry? | Concept | Medium | Read the answer to What is idempotency, and how do you make a POST request safe to retry? | |||
| 4 | How do short polling, long polling, WebSockets and Server-Sent Events differ? | Concept | Medium | Read the answer to How do short polling, long polling, WebSockets and Server-Sent Events differ? |