3
0 Comments

The importance of RESTful Idempotency

RESTful API's are everywhere. They're used by nearly all online applications, mobile applications, and even smart TV applications. But all of them have one thing in common, they are (like any technology) prone to errors such as connection timeouts or random anomalies.

For the best user experience, we want to retry a request for our users if the response was a certain error such as 500, or allow them to retry at their free will. But, we don't want to re-run that code that may have already been sent, where you can end up creating duplicates of what you were creating.

Stripe is a good example of this, since they have implemented
Idempotent Requests. This stops users being charged twice if an error occurs mid transaction and does not supply the client with a response.

Soooo, how do we implement this?

Well, it's not that hard. This can be handled both client-side and server-side. On the client, we generate a unique key (UUID is preferred) and this is sent in a header of the request.

On the server, we check that key with a cache store such as Redis. If the key exists, the user is retying and we will not run the logic again... we will wait to get a response of some kind. If the key does not exist, we run our normal logic and then insert this key and response body in the Redis store. For key buildup on large applications, we can set a TTL to something like 12 hours or even 5 minutes.

Got any questions? Ask away!

Trending on Indie Hackers
Competing with Product Hunt: a month later 33 comments Why do you hate marketing? 29 comments My Top 20 Free Tools That I Use Everyday as an Indie Hacker 19 comments $15k revenues in <4 months as a solopreneur 14 comments Use Your Product 13 comments How I Launched FrontendEase 13 comments