24. APIs and Idempotency
The picture to keep in your head
Every question below is answered twice: first at the machine, so you can picture it, then in the system, so you know exactly how it works. Each answer ends with a memory code to lock it in.
The picture to keep in your head
A vending machine at a railway station. It has labelled buttons that promise what you'll get: B4 is a ₹40 water bottle. You can pay with coins, a card or a phone. When something's wrong, a light tells you: "sold out", "exact change only", "machine jammed".
Now the moment everyone fears. You tap your card. The screen freezes. Did it take the money? You can't tell. If you tap again, will you pay twice? A good machine gives every purchase a receipt number: if you tap again for the same purchase, it recognises the number and says "already paid, here's your water". You can retry without fear.
And when your bank finally settles the payment, it sends you an SMS. You didn't ask; it told you.
That's this chapter: an API is the machine's promise (the buttons and labels), and idempotency is the receipt number that makes "try again" safe.
Our running example: the bookstore's checkout calls a payment API to "charge ₹1,248 for order 881", and also offers its own API for the mobile app ("list my orders", "get book 42").
| At the machine | In the system |
|---|---|
| Labelled buttons: what you'll get | The API contract |
| Coins, card or phone | API styles: REST, gRPC, GraphQL |
| A new model with different buttons | Versioning |
| "Showing items 1-10, press ▶ for more" | Pagination |
| "Sold out", "machine jammed" lights | Errors and status codes |
| Your card or staff key | API auth: API keys, tokens |
| The frozen screen: did it take my money? | The double-charge problem |
| A receipt number for each purchase | Idempotency keys |
| Tapping again, but not too fast | Safe retries |
| The bank's SMS: "you paid ₹40" | Webhooks |
Figure: networks fail in the middle; a good API makes "try again" safe.