Implementing Idempotency in Checkout APIs: A Case Study


I guess you’ve heard the term idempotency before, especially if you love referring to yourself as a software engineer like I do 😄.
At its core, idempotency means that the outcome will remain the same no matter how many times you repeat the same action, whether it’s a request, event, or message. It’s a simple yet powerful concept!
So, I will walk you through an interesting scenario I ran into recently while working on an e-commerce API. The checkout endpoint had a behavior I didn’t like: users could hit the endpoint multiple times with the same cart, which would initialize multiple orders in the database. This was not ideal, especially when dealing with payments. 😬
Then it clicked—this was the perfect opportunity to implement idempotency.
Here’s what I did:
I added an extra column to the order table for an idempotency key.
I then created a method to generate this key based on the cart items’ IDs and quantities. I hashed it using an algorithm that returns a string.
Now, whenever the checkout endpoint is hit again, the key is regenerated, and the system performs a query at the database level to check if an order with that key already exists.
The result? No more duplicate orders for the same set of cart items! ✅
It was a simple but powerful way to ensure that if a customer accidentally resubmits their cart, the system knows it’s the same order and doesn’t create a new one.
Now, let me ask you: How would you have implemented idempotency in this scenario? Do you think this was a good approach to solving the issue of duplicate orders?
Subscribe to my newsletter
Read articles from Adewuyi Taofeeq O. directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
