SOFTWARE ENGINEERING

How to prevent duplicate API transactions with idempotency

Design safe API retries so a repeated request does not create a second payment, booking or customer record.

Illustrative Nigerian engineering team reviewing an API transaction flow
01

Understand the retry problem

A mobile client submits an order, then loses its connection before seeing the response. The server may have completed the order even though the phone reports a timeout. If the user taps again, a naive endpoint can charge twice or create two records. The solution begins by distinguishing a request's delivery from the operation's outcome. A retry is expected behaviour in a distributed system; the business action needs a stable identity.

Idempotency means that repeating a specified operation has the same intended effect as doing it once. It is not a promise that every HTTP response byte will be identical, and it does not make every API method safe automatically. OWASP's API testing guidance recommends repeating an operation and observing whether the resource's state changes unexpectedly: https://wstg.owasp.org/latest/4-Web_Application_Security_Testing/12-API_Testing/00-API_Testing_Overview/.

02

Assign a unique key to one business intent

For an operation such as 'create this booking', let the client generate an unpredictable idempotency key when the user first commits. Reuse that key for retries of the same intent, including after a timeout; use a new key for a genuinely new booking. Scope the key to the authenticated account and operation. Do not let a different customer reuse it to retrieve another person's result.

Store a fingerprint of the canonical request parameters alongside the key. If a retry presents the same key with a different amount, recipient or booking slot, reject it and explain that a new operation needs a new key. Never accept an amount or owner from the client without server-side validation. OWASP's business logic guidance discusses scoping keys and binding them to original request parameters at https://cheatsheetseries.owasp.org/cheatsheets/Business_Logic_Security_Cheat_Sheet.html.

03

Make the reservation atomic

A common implementation inserts a row with a unique constraint on account, operation and idempotency key before executing the side effect. The first request reserves the key. A concurrent identical request sees the existing row and waits for or retrieves its outcome; it must not perform the side effect again. A simple 'check then insert' in application memory has a race when two workers run together.

Use a transaction where your datastore supports it and define states such as pending, completed and failed. Keep enough information to return a safe prior result or tell the caller to retry later. Decide how long records remain based on your clients' retry window and the financial or operational consequences of reuse. Retention policy and error handling are product decisions, not a universal constant.

04

Coordinate external side effects

An internal unique row cannot reverse an external payment already sent. Where the provider supports its own idempotency mechanism, pass a stable provider key for the same underlying action and keep the mapping in durable storage. If a downstream call times out, query the provider's operation status before initiating another. The same principle applies to sending a contract for signature or creating a shipment.

For webhook consumers, deduplicate by the provider's event identity and bind the recorded identity to its payload. Events may be delivered again or out of order. Verify the event's signature before processing and keep the handler's downstream effects idempotent. OWASP describes these controls in its webhook security guidance at https://cheatsheetseries.owasp.org/cheatsheets/Webhook_Security_Cheat_Sheet.html.

05

Return useful outcomes without leaking data

A successful retry may return the original resource identifier and state. A concurrent retry while processing can return a documented in-progress response and a retry interval. A conflicting payload should return a clear client error. Avoid revealing an earlier customer's transaction because a key happened to match. Logs should record correlation identifiers and state transitions without storing payment credentials or sensitive enquiry text.

Consider a Lagos property platform in which a buyer books an inspection and the network stalls. A retry should identify the same booking, not reserve a second slot or send two confirmation emails. The notification itself may require a separate delivery key or outbox record. Treat the booking, payment and email as distinct side effects, each with its own recovery path.

06

Test the failure cases that matter

Send the same request twice in sequence and simultaneously. Repeat it after the server has committed but before the simulated response reaches the client. Change one protected parameter while retaining the key. Use two customer accounts with the same key. Restart the worker during processing and verify that durable records let it recover safely. Check what happens after the key expires.

In staging, inspect database rows and provider sandbox records to prove there was one business action. Test partial failures: the booking commits but the notification fails, or a payment succeeds while the response times out. The correct result may be reconciliation and a delayed notification, not repeating the payment. Record these cases as automated regression tests for future deploys.

07

Set ownership and operational checks

Document who generates keys, their scope, storage period, conflict behaviour and observable metrics. Monitor duplicate attempts, stuck pending rows and provider mismatches. An unusually high retry rate may point to unstable connectivity or a user interface that invites double clicks. A daily reconciliation process can catch the rare case in which systems disagree after a crash.

ChamanTech Solutions can design and test transaction workflows for payments, bookings and CRM intake, including failure recovery and audit trails. Start with a map of the business action and every external service it touches. Idempotency is most valuable when it is demonstrated under timeout and concurrency, rather than simply declared in an API specification.

08

Further reading and editorial accountability

For broader production QA, read https://chamantech.com/blog/how-to-test-website-forms-before-a-production-launch. Editorial review: ChamanTech Solutions technical editorial team; adapt the pattern to your provider and data model.

← Explore more ChamanTech articles

LET'S WORK TOGETHER

Ready to make progress?

Tell us what you are planning. We will review your enquiry and discuss a practical way forward.

Discuss Your Project