Menu

What Is the Idempotency?
๐Ÿ“ฐ

What Is the Idempotency?

DEV Community: rubyยทA.Talaatยท2 days ago
#J1BZZRkO
#devtoruby#devto#dev#api#idempotency
Reading 0:00
15s threshold

๐Ÿš€ 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โ€ฆ

Continue reading โ€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.