CSE Roadmap

Core tier · about 5 hours · 8 parts

Part 4 of 8 · 2 min read

Idempotency

One order, one reservation.

Problem 1: the same user submits twice. A double click, a retry after a slow response, or a refresh could create two reservations for one wish.

Two defences:

  • Client side: disable or hide the book button after the first click. It helps, but a user can bypass it, for example by turning off JavaScript, so it is not enough alone.
  • Idempotent API. An API call is idempotent if calling it many times gives the same result as calling it once. The book does it with a reservation id used as an idempotency key.

The flow:

  1. The customer fills in the details and clicks continue.
  2. The reservation service generates a reservation id (using a method from Level 10, such as the ID generator) and shows the booking page with that id in it.
  3. The customer clicks "book". The request carries the reservation id.
  4. The service inserts a row in the reservation table with that id as the primary key.
  5. If the customer submits again, the same id is sent. The insert fails because the key already exists, and the service reports the original reservation instead of making a new one.

A worked example (made up). The user clicks "book" twice, 200 ms apart. Both requests carry reservation id R-55. The first inserts a row. The second gets a duplicate key error, and the service answers "already booked: R-55". One reservation exists.

The key does not have to be the reservation id, but using the primary key makes the database enforce it for free.

Idempotency key

An idempotency key is a unique id sent with a request, so that repeats of the same request can be recognised and answered without doing the work twice.

Example: a booking request with id R-55 that arrives twice creates one reservation.

Check yourself: 1. Why is a disabled button not enough? 2. What makes the second submit fail? 3. What does the user see on the repeat?