๐ What Happens When Your API Receives the Same Request Twice?
Imagine a customer clicks โPay Nowโ twice because the page freezes.
Or a payment gateway retries a request because it never received your response.
๐ฅ Without proper protection, your application might charge the customer twice!
This is where Idempotency becomes essential.
๐ What Is Idempotency?
Idempotency means that performing the same operation multiple times produces the same result as performing it once.
For example, if a client retries a payment request, the system should return the original result instead of creating another payment.
๐ ๏ธ How Do We Implement It in Ruby on Rails?
A common approach is using an Idempotency-Key .
The client sends a unique key with the request:
POST /api/v1/payments Idempotency-Key: order-123-payment
Enter fullscreen mode
Exit fullscreen mode
Rails can use that key to identify duplicate requests.
Step 1: Add a database constraint
add_index :payments , :idempotency_key , unique: true
Enterโฆ