How to Prevent Duplicate Orders When Retrying API Requests

On this page

Quick Answers

How do you prevent duplicate orders in API requests?
Reuse an idempotency key for retries, enforce uniqueness in the database, and save the order and its response in one transaction. Keep a separate, persistent checkout identity to prevent a second order when the response record expires or a client sends a new key.

Can a timed-out API request still create an order?
Yes. The server may commit the order before the response reaches the client. A timeout tells the client that it stopped waiting, not that the order failed.

Is an idempotency key enough on its own?
No. The server must enforce it. A header containing a unique string does not prevent duplicate writes unless the API recognizes that string and handles repeated requests safely.

What happens when an idempotency record expires?
The API may treat the key as new. A retained checkout reference with a database uniqueness constraint can still prevent another order for the same purchase.

Why a Timeout Can Leave a Completed Order

Consider this illustrative checkout scenario.

A customer submits checkout checkout_456. Your API creates an order and commits it to PostgreSQL. Before the response reaches the browser, the connection drops.

The customer sees an error. Your client retries.

If the endpoint creates a new order for every request, the second attempt creates a duplicate. Both database rows are valid. The server simply had no rule connecting the two requests to one intended purchase.

Stripe’s error-handling documentation describes this uncertainty: losing a response does not establish whether the original operation succeeded.

Disabling the checkout button helps prevent repeated clicks. It cannot protect against background retries, another browser tab or a request sent directly to the API.

The protection needs to exist where the order is written.

Give the Retry and the Purchase Separate Identities

Two identifiers make this design easier to reason about.

The idempotency key identifies an operation

The client generates a key when an operation begins and preserves it across retries.

POST /orders
Idempotency-Key: request_123
Content-Type: application/json
{  
“checkoutId”: “checkout_456”,  “checkoutVersion”: 1
}

If the request times out, the retry sends the same key and body.

Do not generate a new UUID inside the retry loop. That makes each attempt look like a separate operation.

AWS recommends caller-provided request identifiers because identical parameters alone do not establish identical intent. A customer can legitimately make two purchases with the same items. aws.amazon.com

The checkout ID identifies the intended purchase

The checkout reference provides a second line of protection.

Suppose the client accidentally retries checkout_456 with a new key. The response-cache lookup will not recognize the request, but the database can still enforce:

This tenant can have only one order for this checkout.

Use a checkout identity that represents one intended purchase. A reusable shopping-cart ID is not necessarily suitable. A legitimate repeat purchase should receive a new checkout identity.

The checkout version identifies the frozen snapshot being ordered. Its items, prices and delivery details must not silently change while retaining the same identity and version.

What Each Protection Actually Does

ProtectionResponsibilityLimitation
Idempotency keyIdentifies repeated attempts of one operationRequires server-side enforcement
Request fingerprintDetects changed input under an existing keyDoes not decide whether two purchases are legitimate
Unique constraintPrevents duplicate rows for a defined identityDoes not replay an HTTP response
Database transactionCommits related local writes togetherDoes not roll back an external payment
Persistent checkout identityPrevents another order after a new key or cache cleanupMust remain retained and must not be reused

PostgreSQL unique constraints enforce uniqueness, while transactions group related changes into an all-or-nothing operation. These are complementary guarantees. www.postgresql.org

Implement the Database Layer With Node.js and PostgreSQL

The following example demonstrates order identity creation and response replay. It does not implement a complete checkout system.

Before calling it, your application must:

  • Authenticate the caller and obtain the tenant from trusted server-side context.
  • Verify access to the referenced checkout.
  • Validate that the checkout version represents an immutable, authorized purchase snapshot.
  • Calculate prices on the server and enforce applicable business rules.

The function checks the request’s shape. It does not perform those business checks.

Verification status: Thirteen mocked-database Node.js checks passed for the prototype’s validation and control flow. The PostgreSQL integration tests shown later have not been executed for this article.

1. Create separate order and response tables

CREATE TABLE orders (  
  id uuid PRIMARY KEY, 
  tenant_id text NOT NULL,   
  checkout_id text NOT NULL, 
  request_hash text NOT NULL,   
UNIQUE (tenant_id, checkout_id)
);

CREATE TABLE api_results ( 
   tenant_id text NOT NULL,    
operation text NOT NULL,   
 key text NOT NULL,   
  request_hash text NOT NULL, 
   response_status integer, 
   response_body jsonb,  
   created_at timestamptz NOT NULL DEFAULT now(),

 PRIMARY KEY (tenant_id, operation, key),

    CHECK ( 
       (response_status IS NULL) =
       (response_body IS NULL)
    )
);

The first constraint protects the purchase identity. The second protects the request identity.

These are minimal teaching tables. A real order also needs its immutable purchase data or a durable reference to that data.

2. Validate and fingerprint the input

Save the following JavaScript sections together as core.mjs.

The fingerprint uses an explicit sequence of accepted fields. Changing JSON property order does not change it. Unknown fields are rejected rather than silently excluded.

import { createHash, randomUUID } from “node:crypto”;

export class ApiError extends Error {
 constructor(status, code) { 
   super(code);  
   this.status = status; 
   this.code = code; 
 }
}

export function fingerprint(input) { 
 if ( 
   !input ||   
 Array.isArray(input) ||   
 typeof input !== “object” || 
   Object.keys(input).sort().join(“,”) !==  
    “checkoutId,checkoutVersion” ||   
 typeof input.checkoutId !== “string” || 
   !/^[A-Za-z0-9_-]{1,100}$/.test(input.checkoutId) ||
    !Number.isSafeInteger(input.checkoutVersion) || 

   input.checkoutVersion < 1 
 ) { 
   throw new ApiError(400, “invalid_checkout_reference”); 
 }

  return createHash(“sha256”) 
   .update(JSON.stringify([  
    “create-order:v1”,   
   input.checkoutId,   
   input.checkoutVersion
    ])) 
   .digest(“hex”);
}

This fingerprint is sufficient only for this narrow input contract. If the endpoint accepts additional order-changing fields, validate and include them, or reference a frozen server-side snapshot containing them.

3. Claim the key and write the order in one transaction

The function below accepts a node-postgres pool. Every transactional statement uses the same checked-out connection, as required by the driver’s documentation. node-postgres transaction documentation.

export async function createOrder(pool, tenant, key, input) {
  if (
    typeof tenant !== “string” ||
    !tenant ||
    typeof key !== “string” ||
    !/^[A-Za-z0-9_-]{1,128}$/.test(key)
  ) {
    throw new ApiError(400, “invalid_identity”);
  }

  const hash = fingerprint(input);
  const client = await pool.connect();

  let transaction = false;
  let committing = false;
  let discard = false;

  try {
    await client.query(
      “BEGIN ISOLATION LEVEL READ COMMITTED”
    );
    transaction = true;

    // Illustrative limits. Tune for your workload.
    await client.query(“SET LOCAL lock_timeout = ‘500ms'”);
    await client.query(“SET LOCAL statement_timeout = ‘2000ms'”);

    const claimed = await client.query(
      `INSERT INTO api_results
         (tenant_id, operation, key, request_hash)
       VALUES ($1, ‘create-order:v1’, $2, $3)
       ON CONFLICT (tenant_id, operation, key)
       DO NOTHING
       RETURNING key`,
      [tenant, key, hash]
    );

    let status;
    let body;

    if (!claimed.rowCount) {
      const prior = await client.query(
        `SELECT request_hash, response_status, response_body
         FROM api_results
         WHERE tenant_id = $1
           AND operation = ‘create-order:v1’
           AND key = $2`,
        [tenant, key]
      );

      if (!prior.rowCount) {
        throw new ApiError(503, “result_unavailable”);
      }

      const record = prior.rows[0];

      if (record.request_hash !== hash) {
        throw new ApiError(422, “idempotency_payload_mismatch”);

  }

      if (
        record.response_status == null ||
        record.response_body == null
      ) {
        throw new ApiError(503, “result_incomplete”);
      }

      status = record.response_status;
      body = record.response_body;
    } else {
      const inserted = await client.query(
        `INSERT INTO orders
           (id, tenant_id, checkout_id, request_hash)
         VALUES ($1, $2, $3, $4)
         ON CONFLICT (tenant_id, checkout_id)
         DO NOTHING
         RETURNING id, request_hash`,
        [randomUUID(), tenant, input.checkoutId, hash]
      );

      let order = inserted.rows[0];

      if (!order) {
        const existing = await client.query(
          `SELECT id, request_hash
           FROM orders
           WHERE tenant_id = $1 AND checkout_id = $2`,
          [tenant, input.checkoutId]
        );

        order = existing.rows[0];

        if (!order) {
          throw new ApiError(503, “order_unavailable”);
        }

        if (order.request_hash !== hash) {
          throw new ApiError(409, “checkout_already_used”);
        }
      }

status = inserted.rowCount ? 201 : 200;
      body = { orderId: order.id };

      await client.query(
        `UPDATE api_results
         SET response_status = $3, response_body = $4
         WHERE tenant_id = $1
           AND operation = ‘create-order:v1’
           AND key = $2`,
        [tenant, key, status, body]
      );
    }

    committing = true;
    await client.query(“COMMIT”);
    transaction = false;
    committing = false;

    return { status, body };
  } catch (error) {
    if (committing) {
      discard = true;
      throw new ApiError(503, “commit_outcome_unknown”);
    }

    if (transaction) {
      try {
        await client.query(“ROLLBACK”);
      } catch {
        discard = true;
      }
    }

    if (
      [“55P03”, “57014”, “40001”, “40P01”].includes(error.code)
    ) {
      throw new ApiError(503, “database_retry_required”);
    }

    if (!(error instanceof ApiError)) {
      discard = true;
      throw new ApiError(503, “database_unavailable”);
    }

  throw error;
  } finally {
    client.release(discard);
  }
}

The HTTP layer should send the returned status and body only after the function completes. It should map ApiError values to documented responses and handle connection-acquisition failures without exposing database details.

Connection-pool limits and an overall request deadline also need configuration. A statement timeout does not limit the entire request.

What the Client Should Receive

For our illustrative checkout_456, the contract is:

RequestExpected response
First successful request201, with the new order ID
Same key and matching bodySaved status and body
Same key, changed checkout version422 idempotency_payload_mismatch
New key, same checkout and version200, with the existing order ID
Checkout already used with different input409 checkout_already_used
Database contention or unavailable resultDocumented 503 error

Example successful response:

HTTP/1.1 201 Created
Content-Type: application/json

{
  “orderId”: “7f652819-26bc-45bf-8d47-5f0d401a6bd6”
}

A matching retry with the retained key returns the same order ID and saved status.

These status codes are choices for this endpoint. Do not assume every provider uses the same conventions.

Handle Concurrent Requests and Unknown Outcomes

Two requests can reach the database together

The unique constraint coordinates competing inserts. A second request can wait for the first transaction to commit or roll back.

After a conflict, the code performs a separate lookup. This matters because PostgreSQL documents that ON CONFLICT DO NOTHING can skip an insert due to a transaction whose row was not visible in the original statement’s snapshot. A subsequent Read Committed statement gets a fresh snapshot. postgresql.org

The example bounds database waiting. It does not label every lock timeout as “your order is processing,” because unrelated locks can produce the same error.

A failed commit acknowledgement does not prove rollback

The database may commit successfully and then lose its connection before the application receives confirmation.

The handler treats an error during COMMIT as an unknown outcome and discards the connection. It does not tell the client to create a new purchase.

A controlled retry must preserve the same key, checkout identity and input. If the transaction committed, the existing result can be recovered. If it did not, the operation can be attempted again.

Use a bounded retry policy with backoff and jitter. If the retry budget is exhausted, preserve an unresolved state and reconcile it. Do not convert uncertainty into a fresh order.

Prevent Duplicates After the Response Record Expires

The response table is not the permanent source of purchase identity.

Suppose request_123 is removed during cleanup. A late retry can claim that key again, but it still references checkout_456. The order table’s unique constraint prevents another row for that checkout.

The handler retrieves the existing order and stores a new response record.

That is order recovery, not necessarily exact replay of the original HTTP response. In this example, recovery returns 200; the original creation returned 201.

Retention rules must be explicit. Stripe API v1, for example, permits pruning keys once they are at least 24 hours old and treats reuse after pruning as a new request. That is a provider-specific policy, not a universal expiry rule. docs.stripe.com

For your own endpoint:

  • Retain the checkout-to-order identity for as long as duplicate prevention is required.
  • Preserve a uniqueness record or tombstone when archiving orders.
  • Do not reuse a completed checkout identity.
  • Coordinate response cleanup with active requests.
  • Never interpret a missing response record as permission to bypass the order constraint.

Deleting both the response record and the business identity removes the protection.

Test the Database Effect, Not Just the Response

A request returning 200 or 201 does not prove that only one order exists.

The following integration test checks concurrent attempts, changed input and recovery after response-record removal. Save it as integration.test.mjs alongside core.mjs.

Run it only against a dedicated test database containing the schema above. It leaves uniquely named test fixtures for inspection.

import test from “node:test”;
import assert from “node:assert/strict”;
import { randomUUID } from “node:crypto”;
import pg from “pg”;

import { createOrder } from “./core.mjs”;

const { Pool } = pg;

test(“retries preserve one order identity”, async () => {
  assert.ok(
    process.env.TEST_DATABASE_URL,
    “Set TEST_DATABASE_URL to a dedicated test database”
  );

  const pool = new Pool({
    connectionString: process.env.TEST_DATABASE_URL,
    max: 10,
    connectionTimeoutMillis: 3000
  });

  const tenant = `test_${randomUUID()}`;
  const key = randomUUID();
  const input = {
    checkoutId: `checkout_${randomUUID()}`,
    checkoutVersion: 1
  };

  try {
    const attempts = await Promise.allSettled(
      Array.from({ length: 10 }, () =>
        createOrder(pool, tenant, key, input)
      )
    );

    // Contention can legitimately produce retryable errors.
    for (const attempt of attempts) {
      if (attempt.status === “rejected”) {
        assert.equal(
          attempt.reason.code,
          “database_retry_required”
        );
      }
    }

    const completed = await createOrder(
      pool, tenant, key, input
    );

 for (const attempt of attempts) {
      if (attempt.status === “fulfilled”) {
        assert.equal(
          attempt.value.body.orderId,
          completed.body.orderId
        );
      }
    }

    await assert.rejects(
      createOrder(pool, tenant, key, {
        …input,
        checkoutVersion: 2
      }),
      error => error.code === “idempotency_payload_mismatch”
    );

    // Simulate removal of the retained response.
    await pool.query(
      `DELETE FROM api_results
       WHERE tenant_id = $1
         AND operation = ‘create-order:v1’
         AND key = $2`,
      [tenant, key]
    );

    const recovered = await createOrder(
      pool, tenant, key, input
    );

    const newKeyRetry = await createOrder(
      pool, tenant, randomUUID(), input
    );

    assert.equal(
      recovered.body.orderId,
      completed.body.orderId
    );
    assert.equal(
      newKeyRetry.body.orderId,
      completed.body.orderId
    );

  const count = await pool.query(
      `SELECT count(*)::int AS total
       FROM orders
       WHERE tenant_id = $1 AND checkout_id = $2`,
      [tenant, input.checkoutId]
    );

    assert.equal(count.rows[0].total, 1);
  } finally {
    await pool.end();
  }
});

Install the driver and run the test after configuring the test connection:

npm install pg
node –test integration.test.mjs

This test is provided for execution; its results are not claimed here. It also does not replace controlled crash testing.

Before deployment, add these failure-injection checks:

TestHow to trigger itRequired result
Concurrent rollbackHold the first transaction, start a duplicate, then roll back the firstThe duplicate can proceed; only one order commits
Process crash before commitTerminate the worker after order insertion but before commitNo partial order/result pair remains
Response loss after commitCommit, then drop the HTTP connection before sending the responseSame-key retry retrieves the existing order
Unrelated lock contentionHold a conflicting table lockBounded service error; no false success
Tenant isolationUse the same key under separate authenticated tenantsNo cross-tenant response disclosure
Cleanup overlapRemove an eligible response while a duplicate is being resolvedSafe failure or recovery; no unclaimed order creation

Keep these tests with the application. Preventing recurring integration incidents is part of reducing software maintenance costs, especially when failures otherwise require manual order cleanup.

Why One Order Does Not Automatically Mean One Payment

The sample protects local order rows. It does not charge a card.

An external payment introduces a separate failure boundary:

  1. Your application sends a payment request.
  2. The provider processes it.
  3. The response is lost.
  4. Your application does not know whether the charge succeeded.

A PostgreSQL rollback cannot undo that charge.

Use the payment provider’s supported idempotency mechanism, retain the payment-operation identity, and reconcile uncertain outcomes before starting a different payment attempt. Follow the specific endpoint’s documented retention and error behavior.

For events such as “order created,” an outbox record can be written in the same transaction as the order. A worker publishes it afterward. AWS notes that outbox delivery can still produce duplicate messages, so consumers may need their own deduplication. AWS Prescriptive Guidance

Production Requirements Beyond This Example

The sample’s intended protection is narrow: one retained order identity per tenant and checkout, with response replay for matching retained keys.

A production implementation also needs:

  • Checkout ownership checks before returning either new or stored results.
  • Immutable purchase snapshots and server-side pricing.
  • Inventory and order-state rules appropriate to the business.
  • Request-size, key-length and rate limits.
  • Database permissions that prevent other write paths from bypassing the design.
  • Defined response retention, archival and reconciliation policies.
  • Monitoring for repeated conflicts, unknown outcomes and database contention.

The transaction protects database work included inside it. Any additional side effect needs its own explicit treatment.

Frequently Asked Questions

Can the server generate the idempotency key?

Yes, if it gives the client a stable operation identifier before the retry-sensitive action, or derives one from an established business operation. Generating a new server-side key for every incoming request does not connect retries.

Can I use a hash of the request body as the key?

A body hash is useful for detecting changed input, but it is not always a suitable operation identity. Two legitimate purchases can contain identical data. Keep intent separate from payload equality.

Should every HTTP 500 response be retried?

No. Retry behavior depends on the endpoint’s contract and the original operation’s outcome. For example, Stripe API v1 can replay a saved 500 responses for the same key. Changing the key just to escape that response can initiate a different operation. docs.stripe.com

Can this work if I only consume a third-party API?

Only to the extent that the provider supports safe deduplication or reliable reconciliation. Follow its documented key, external-reference and status-check mechanisms. Adding an unsupported header does not change how its backend processes requests.

Does this provide exactly-once processing?

No end-to-end exactly-once claim is made. Requests and handler code can run more than once. The design uses retained identities and database constraints to prevent a second local order for the same checkout under the stated conditions.

Make Your Order API Safe to Retry

UGS Technology’s API development and integration services can help you review order creation, retry behavior and payment-provider integration.

Talk to our team about the failure scenarios your application needs to handle.

Keep reading

Related posts

Stay tuned. Subscribe to our newsletter.

Product notes, engineering write-ups and releases — once a month, no noise.