Is your API idempotent?
Idempotent, pronounced ahy-duhm-poht-nt
Idempotent operations are those that, when executed once or multiple times, give you the same result.
Have you used this two-way switch? If yes, do you think it is idempotent? (My senior engineers were not happy with the designer of this switch. Apparently, the switch designer skipped the review meeting ;)
If your answer is no, you are right. This two-way switch is not idempotent. Because you can not guarantee that pressing this switch down will always light up the room.
Now, consider the switch in the image above. Is this idempotent? Yes. Because if you press it down, it will always switch on the light, irrespective of how many times you do it. That’s not the case in the first example of the two-way switch.
But why is idempotency important?
It’s important because one has to plan for failure. Assume you are making a payment and you see this loading screen.
You wait for the payment confirmation but the loader goes round and round. After a minute (or the set timeout), the app shows a pending status for the payment and you are unsure of what has happened.
You will likely wonder:
If the amount was deducted from the bank
If so, why would the payment be shown as pending?
Should you retry the payment?
And what could have gone wrong?
Did the e-commerce app fail to get a payment confirmation from the payment partner?
Did the request fail from the e-commerce app to the payment partner?
Did the e-commerce backend fail to notify the front end?
Any of these scenarios may have happened, potentially due to high load, a network glitch, or a host of other factors.
Let’s assume that the e-commerce app failed to get the payment confirmation from the payment partner. Now, if you retry and the money was deducted from your account, idempotency at the bank’s end could prevent you from a double payment of the same order.
But how could banks achieve such idempotency?
One possible way is to use the idempotency-key.
Consider the curl below:
curl https://api.bankabc.com/v1/payment \
-H “Idempotency-Key: SDFGHJKL123456fgh” \
-d amount=1000 \
-d currency=INR \
The Idempotency-Key in the header here will likely be a unique key in the bank database table. It will not allow double payments against the same key. However, it is the responsibility of the e-commerce company to ensure that it generates the same Idempotency-Key for the same order (or order Id).
How to use idempotency to your advantage?
Retry, whenever you don’t get a response from the remote service. Because if you don’t, you would have your transaction hanging in an undesirable state.
Make sure that you retry using an idempotency key, which would safeguard you from the risk of a double transaction or entry.
So, is your API idempotent?
Read about timeouts here.
Loved this blog? Stay tuned for more such articles. Next up - “Timeouts are Important“