Learning on Web Dev Open is free for all.

Backend Engineering > HTTP, properlyDoing it twice on purpose
Phase 05HTTP, properly245 of 434

Doing it twice on purpose

Networks lose responses, not just requests. Design so that a client who never heard back can safely try again.

Concept14 minAI adversary

The failure that shapes API design is not the request that never arrives. It is the request that arrives, succeeds, and whose response is lost on the way back. The client sees a timeout and cannot distinguish that from a total failure, so it retries, and your server does the whole thing again. Every double charge and duplicate order you have ever seen is this.

The fix is to make the operation identifiable. Either derive a natural key from the content, one booking per user per showing, enforced by a unique index, or let the client generate an idempotency key, send it as a header, and store the outcome against it. On a repeat, you return the stored result rather than redoing the work. The window matters: keep the record long enough to cover realistic retries, which is hours rather than seconds.

This costs a table and a lookup, and it is the difference between an API that is fine in the demo and one that is fine on a train. It also earns its keep the first time a queue redelivers a message, which the jobs lesson later in this phase guarantees will happen.

You should now be able to

  • Explain why an at-least-once world needs idempotent handlers
  • Design an endpoint that tolerates a duplicate submission
  • Choose a natural key or an idempotency key deliberately
Ask the community

Loading…