Skip to content
← Back to all articles
For Developers

API Idempotency: How to Prevent Duplicate Orders and Payments

Imagine a customer places an order on your e-commerce website. The backend successfully creates the order, but the network connection fails before the customer receives a confirmation.

The customer tries again.

Without proper safeguards, the backend may create another order or initiate another payment.

This is where API idempotency becomes important. It helps software engineers design reliable systems that can safely handle repeated requests without unintentionally repeating business operations.

What is API idempotency?

An operation is idempotent when repeating the same operation has the same intended effect as performing it once.

In practical backend development, an idempotency mechanism can help ensure that multiple requests representing the same purchase intent do not create multiple orders.

Why duplicate API requests occur

Duplicate requests are not always caused by users clicking a button twice.

They can also occur because of network interruptions, client-side retry logic, gateway timeouts, message redelivery and distributed system failures.

Disabling a submit button improves the user experience, but it cannot guarantee that a backend operation executes only once.

The backend must enforce the relevant business invariant independently.

How idempotency keys work

An idempotency key is a unique identifier associated with a specific logical operation.

For example, a checkout application can generate a key when the customer initiates a purchase.

Generate a unique key on the frontend

const idempotencyKey = crypto.randomUUID();

async function placeOrder(order) {
  const response = await fetch("/api/orders", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Idempotency-Key": idempotencyKey
    },
    body: JSON.stringify(order)
  });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  return response.json();
}

The important detail is that retries of the same checkout intent must reuse the same key.

A genuinely new purchase should receive a new key. Applications that need to survive page reloads should persist the checkout intent appropriately rather than relying only on an in-memory variable.

Store idempotency keys in the backend

The backend needs a reliable way to identify whether an operation has already been processed.

A PostgreSQL table could store the operation key, request fingerprint, processing status and original response.

CREATE TABLE idempotency_records (
  account_id BIGINT NOT NULL,
  idempotency_key TEXT NOT NULL,
  request_hash TEXT NOT NULL,
  status TEXT NOT NULL,
  response_status INTEGER,
  response_body JSONB,
  created_at TIMESTAMPTZ DEFAULT NOW(),

  PRIMARY KEY (
    account_id,
    idempotency_key
  )
);

Scoping the key to the authenticated account helps prevent one customer from accessing another customer’s stored response.

The composite primary key also enforces uniqueness at the database level.

Avoid unsafe check-then-insert logic

Consider this simplified implementation:

const existing = await findOrder(key);

if (!existing) {
  await createOrder(order);
}

Two concurrent requests might both find that no order exists before either creates one.

A database uniqueness constraint, combined with an appropriate transaction strategy, is more reliable than an unprotected application-level check.

Design a reliable idempotency workflow

For operations entirely within one database, the application can claim the key, create the order and store the response within a transaction.

When the same key arrives again, the backend checks the stored request fingerprint and operation status.

If the operation has completed and the payload matches, it can return the previously stored response.

If the payload differs, the application should reject the request according to its documented API contract. HTTP 409 Conflict is one possible response.

Handling external payment services

Payment integrations introduce additional complexity because a local database transaction cannot atomically commit an operation in an external payment provider.

A reliable implementation should use the payment provider’s supported idempotency mechanism, persist payment state and reconcile uncertain outcomes.

For example, when a payment request times out, the backend should not automatically assume that the payment failed. The provider may already have processed it.

A stable payment intent identifier and a reconciliation workflow can help prevent unnecessary repeated charges.

Test your idempotency implementation

Automated tests should verify the actual business outcome, not merely the HTTP response.

Test repeated requests

Send the same payload and idempotency key twice. Confirm that only one order exists and successful responses reference the same order.

Test concurrent requests

const results = await Promise.all([
  sendOrder(key, order),
  sendOrder(key, order)
]);

expect(await countOrdersForIntent(key))
  .toBe(1);

This is an illustrative test fragment. The helper functions should use your actual API and test database.

Test failures and payload mismatches

Simulate a network failure after the database transaction commits. A subsequent retry should recover the existing result rather than create another order.

Also verify that using the same key with different order details produces the documented conflict response.

Common API idempotency mistakes

MistakeRecommended approach
Generating a new key for every retryReuse the key for the same logical operation
Relying only on disabled buttonsEnforce backend invariants
Using an unprotected existence checkUse atomic claims and database constraints
Ignoring changed request payloadsCompare a stable request fingerprint
Retrying uncertain payments blindlyReconcile with the payment provider
Deleting keys too earlyDefine retention based on the retry window

Frequently asked questions

Is POST automatically idempotent?

No. POST is not inherently idempotent under HTTP semantics. However, an application can implement idempotent behavior for specific POST operations.

Can Redis store idempotency keys?

Yes, but the design must account for atomic operations, expiration, durability and coordination with the underlying business transaction. A cache alone may not provide sufficient guarantees for critical financial operations.

Are idempotency and exactly-once delivery the same?

No. Idempotency helps repeated deliveries produce the intended business effect without duplication. It does not mean that a distributed system physically delivers every request exactly once.

How long should idempotency keys be stored?

There is no universal duration. Retention should reflect the application’s retry behavior, business requirements and external provider policies.

Does idempotency prevent all duplicate payments?

Not by itself. Reliable payment processing also requires correct provider integration, stable payment identifiers, reconciliation and appropriate database safeguards.

Conclusion

API idempotency is an important architectural practice for building reliable checkout systems, payment integrations, background jobs and distributed applications.

By combining stable operation identifiers, database uniqueness constraints, safe transaction boundaries and automated testing, engineering teams can reduce unintended duplicate operations.

The key is to design for failures and retries from the beginning, rather than assuming every network request will succeed exactly once.

Need help implementing reliable APIs or AI applications?

Connect with Tekody for remote engineering and AI development support, including backend architecture, API debugging, frontend integrations and production troubleshooting.

👉 Request Support: https://tekody.com/get-support/

📲 WhatsApp for Support: +91-8527854783

Need help with a similar challenge?

Discuss your requirements with Tekody and explore practical support options.