Idempotency in API
Idempotency is a property of REST APIs that ensures that performing an operation multiple times will produce the same result as performing it once.
Example:
- Multiple GET requests will result in the same response as a single get request, hence Idempotent.
- Multiple POST requests, for example a payment, if sent multiple times due to network issues, will invoke multiple payments which is not ideal, hence not Idempotent.
Solutions
- Use a unique key per request that might affect the state of the system. This can be done via the idempotent header, for payment, it can be
user_id_payment_23129KLJ
which contains the user id, the routepayment
and a unique ID at the end. The application on successful request processing, stores this key against the success response in a key value store, so if the same idempotent header is seen, the same response can be sent without any processing.- Additional: Store the hash of the request along with the idempotent key just incase a request contains the same key but with different request body. In this situation, return an error asking the user/client to change the idempotent key for the new request.