Menu

Idempotency in REST APIs: how I prevented duplicate charges with an Idempotency-Key
📰

Idempotency in REST APIs: how I prevented duplicate charges with an Idempotency-Key

DEV Community: postgres·Jhoan Sebastian Rojas Holguin·about 14 hours ago
#RlW3j5i6
#devtopostgresql#devto#dev#response#payments
Reading 0:00
15s threshold

🔥 The problem

The client sends a POST /payments , the network drops before the response arrives, and the client retries. The server had already charged the customer. Result: two charges for a single purchase.

This isn't a rare case: a timeout, a double click, or an HTTP client's automatic retry can cause it. And POST is not idempotent by definition, so the protection is up to you.

The idea: the client generates a unique Idempotency-Key per operation and sends it in the header. If the same key arrives again, you don't repeat the work: you return the saved response.

To test it, I simulated 50 simultaneous retries against the endpoint. Without idempotency: 50 records. With it: 1. Everything you need to reproduce it is below.

🧱 Step 1: the tables

The key piece is a unique constraint.…

Continue reading — create a free account

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