API correctness · 1 / 4
Make retries safe
Your challenge
A client retries POST /orders after a timeout. The first request may have committed. Prevent a second order while allowing safe retries.
Try it first. Write down your assumptions and explain your reasoning.
1.Define the idempotency contract
Accept a client-generated idempotency key scoped to the authenticated account and operation. Store a normalized request hash and the resulting order reference or response. Reusing a key with a different payload must fail rather than silently changing the original operation.
2.Use a database constraint and transaction
Create a unique constraint on account_id and key. In one transaction, reserve the key, create the order and record the completed result. Concurrent requests must converge on one winner. A memory cache cannot provide this guarantee across application instances or restarts.
3.Handle external side effects separately
If payment or email runs outside the transaction, record durable work using an outbox and make the worker idempotent too. Do not promise exactly-once delivery across arbitrary external systems. Define key retention and in-progress behavior so a retry can receive the same committed result or a clear pending response.
Take it one step further
- 1.What if the client never receives the successful response?
- 2.How should a reused key with a different request behave?
Self-review
Can you explain each point without looking at the solution?
- Account-scoped unique key
- Atomic order and key persistence
- Recognize the external side-effect boundary
