Safe to run twice

Think of it when an action might run twice: a retry, a double click, or a script run again after a crash.

In everyday life

Like a lift call button: press it once or five times, and one lift comes. A coin slot is the opposite: every coin counts again.

One case

A customer double-clicks “Pay” for order 42, and the shop’s server receives two requests 300 milliseconds apart. Each request asks the payment service for a new $20 charge, so the customer pays $40. Had both requests carried the same idempotency key, the payment service would have made one charge and answered the second request with the first result.

Two clicks, two charges: the second request carried no key
The case, cell by cell1 cell = 1 click
Charged, as intended
$0$20$20
Charged without protection
$0$20$40
Charged with duplicate-request protection
$0$20$20
Charged without protection
$40
Charged with one key for both
$20
The second click arrived 300 milliseconds after the first. With one idempotency key, the payment service charged once.

Every case

Networks drop answers, users double-click, and jobs restart after a crash. So any action may arrive twice, and the sender often cannot tell whether the first try worked. An action that states the end result, such as “set order 42 to paid” in the shop’s own records, is safe to repeat. An action that states a change (“charge $20”, “create the folder”) stacks up or fails on the second run. A charge happens at the payment company, so the shop cannot make it safe on its own side: it sends an idempotency keyA unique id the sender attaches to one intended action, such as one payment. The receiving service does the action once and answers any repeat with the first result. with each charge, and the payment service makes only one charge per key.

The word

Engineers call this

idempotentAn action that leaves the same result whether it runs once or many times. That makes it safe to retry after a crash, a timeout or a double click.

Write each action so that a second run finds nothing left to do. Ask: what happens if this runs twice?

Where this idea leads

Skills that encode it

  • principle-make-operations-idempotent pstackAsk “what happens if this runs twice?” Read the current state, compare it with the goal, and apply only the difference.