Video in progress

What is an idempotent operation, and why is it required in a payment API?

Running an idempotent operation once or five times gives the same result. In a payment, if the network drops, the client resends — and if the operation isn't idempotent, the customer is charged twice.

📖 Answer

The situation: the client sent a "transfer 100,000 soums" request, the server moved the money, but the response got lost on the way. The client gets a timeout and doesn't know whether the transfer happened. Naturally, it resends.

The solution is an idempotency key. The client generates a unique key for each operation and sends the same key on retries:

POST /api/payments
Idempotency-Key: 7f3c2a10-5b1e-4c8e-9d2f-1a6b0e4c9d33

The server stores the key in a unique (UNIQUE) column in the database. If an operation with this key already happened, it doesn't run it again — it returns the earlier result.

By HTTP method: GET, PUT and DELETE should be idempotent by nature, POST is not. That's why the things created with POST (a payment, an order) need a key.

Important: checking the key and performing the operation must happen in one transaction or be protected by a unique constraint. Otherwise two parallel requests both see "no such key", and both pay.