Idempotency: press 5 times, arrive once

Have you ever pressed the elevator button five times in a row?
I have. Everyone has. And the elevator never arrived five times faster. Five elevators didn’t show up either. Just one came, the same one that would have come if you had pressed once.
That button is idempotent.
Idempotency is the property of an operation that gives the same result whether it runs once or many times. It sounds like a classroom detail, but it’s one of the ideas that does the most to keep the digital world standing.
The problem: nobody knows if the message arrived
In distributed systems, nobody guarantees that a message arrives exactly once. The network wobbles, the response times out, and the client tries again. Did the server receive it? Did it process it? Nobody knows for sure. And when in doubt, the system repeats.
Now swap the elevator for a payment. A person clicks “pay”, the screen freezes, and they click again. Without idempotency, that’s two charges.
Or for a purchase event sent to the CRM. It arrives twice, and you get two “thanks for your purchase” emails, inflated revenue, and a dashboard telling a story that never happened.
The solution: asking “have I done this already?”
The solution is usually simple. Each operation carries a unique key, the idempotency key. Before executing, the system asks itself: “have I done this already?”. If it has, it returns the same result and moves on.
async function charge(key: string, order: Order) {
const previous = await results.get(key);
if (previous) return previous; // already done: return the same result
const result = await gateway.charge(order);
await results.set(key, result);
return result;
}
In practice, writing the key has to be atomic (a uniqueness constraint in the database, for example), so that two simultaneous attempts can’t both get past the check.
The honest premise
What I love most about idempotency is the premise behind it: things will go wrong. The message will be duplicated, the user will click twice, and the job will run again at three in the morning. Instead of pretending this doesn’t happen, you design the system so that repetition does no damage.
A reliable system isn’t one that never fails. It’s one that can fail, try again, and end up in exactly the same place.
What about you, have you ever seen a duplicate cost a lot?