Lesson 1 of 17
24. APIs and Idempotency

The picture to keep in your head

3 min read+10 XP

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 machineIn the system
Labelled buttons: what you'll getThe API contract
Coins, card or phoneAPI styles: REST, gRPC, GraphQL
A new model with different buttonsVersioning
"Showing items 1-10, press ▶ for more"Pagination
"Sold out", "machine jammed" lightsErrors and status codes
Your card or staff keyAPI auth: API keys, tokens
The frozen screen: did it take my money?The double-charge problem
A receipt number for each purchaseIdempotency keys
Tapping again, but not too fastSafe retries
The bank's SMS: "you paid ₹40"Webhooks

the vending machine mapped to contracts, API styles, status codes, idempotency keys and webhooks.

Figure: networks fail in the middle; a good API makes "try again" safe.