Bareet
← All articles

The request timed out. Did the order go through?

Build a retry-safe order endpoint with PostgreSQL. Lose a response in the interactive demo, inspect the transaction, and reproduce a 17-request concurrency test.

The database saved the order. The connection dropped before the confirmation reached the browser. The customer sees a timeout and presses Try again.

What should the server do with that second request?

The second request needs a way to identify the order already saved. A key carried across attempts gives the server that information, including when the first response never arrives.

The PostgreSQL example below saves that key with the order and its receipt in one transaction. Try losing a response in the simulator, then inspect the SQL and reproduce the 17-request concurrency check. Inventory and payments would need their own handling.

Lose the response, then retry#

Send once in the simulator, then retry. Switch to “Insert on every attempt” and repeat. Finally, keep the saved-result mode, change the quantity, and retry with the old key.

Try losing the responseBrowser simulation · no requests sent
Requests attempted0
Orders stored0
Request keyorder-7
  1. Send the first request. The order will be saved, but its response will disappear.

Changing modes resets this model. It illustrates replay and mismatch handling; the real concurrency test below runs on PostgreSQL.

One operation can take several attempts. Each attempt carries the same request key.

After a timeout, the browser still needs to find out whether the database committed. Stripe describes this uncertainty in its engineering explanation of idempotency. Here we handle it directly in PostgreSQL.

The database commits an order, its response is lost, and a retry with the same key reads and returns the saved order result.
Time moves downward. Each arrow crosses between the browser, API or database. On a phone, scroll the diagram horizontally to inspect the labels.

Decide what the key means before writing the endpoint#

For this example, a key belongs to one authenticated account and one create-order operation. The dedicated order_requests table makes the operation scope explicit. Another endpoint should have its own scope.

Incoming requestResult in this example
New key, valid orderCreate the order and remember the result
Same account, same key, same order dataReturn the remembered result
Same account and key, different quantity or SKUReject the mismatch
Different account, same keyTreat it as a separate operation
First transaction rolls backA later attempt may create the order

Read the account ID from verified authentication and recheck authorization on every retry. Accepting an account ID from the request body would let a caller select someone else’s key space.

Create the operation object once and reuse it when retrying. To survive a page reload, you would also need to persist the pending operation or look it up on the server.

one-operation.ts
const operation = {
  key: crypto.randomUUID(),
  body: { sku: "NOTEBOOK", quantity: 1 },
};
 
async function attempt() {
  return fetch("/api/orders", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Idempotency-Key": operation.key,
    },
    body: JSON.stringify(operation.body),
  });
}
// After an uncertain result, call attempt() again for this operation.

On the backend, validate the key and payload and use bound SQL parameters. The Idempotency-Key header carries the identifier; the transaction below enforces what it means.

Claim the key and save the order in one transaction#

A separate “does this key exist?” query creates a gap. Two requests can both read “no” before either inserts anything.

two-independent-checks.txt
Request A: SELECT key → absent
Request B: SELECT key → absent
Request A: INSERT order → order 1
Request B: INSERT order → order 2

Both requests passed the check before either write reserved the key.

The winner inserts the order and saves its result before committing. The loser reads that saved result with a separate SQL statement. This example requires READ COMMITTED: a conflicting insert may wait for another transaction, and a subsequent statement can see its committed row. PostgreSQL documents this behaviour in its transaction isolation reference.

Keep the fallback read in its own statement: it needs the fresh snapshot obtained after the competing insert finishes. Combining both into one statement changes those visibility rules.

Open the complete schema and function used in the test
schema.sql
-- Run once in an empty disposable PostgreSQL database.
CREATE SCHEMA retry_demo;
CREATE TABLE retry_demo.orders (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  account_id uuid NOT NULL,
  sku text NOT NULL,
  quantity integer NOT NULL CHECK (quantity BETWEEN 1 AND 100)
);
CREATE TABLE retry_demo.order_requests (
  account_id uuid NOT NULL,
  request_key uuid NOT NULL,
  request jsonb NOT NULL,
  response jsonb,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (account_id, request_key)
);
 
CREATE FUNCTION retry_demo.create_order(
  p_account uuid, p_key uuid, p_sku text, p_quantity integer
) RETURNS jsonb LANGUAGE plpgsql VOLATILE AS $$
DECLARE
  claimed boolean := false;
  input jsonb;
  previous retry_demo.order_requests%ROWTYPE;
  order_id uuid;
  result jsonb;
BEGIN
  IF current_setting('transaction_isolation') <> 'read committed' THEN
    RAISE EXCEPTION 'This example requires READ COMMITTED';
  END IF;
  IF p_account IS NULL OR p_key IS NULL OR p_sku IS NULL
     OR length(p_sku) NOT BETWEEN 1 AND 80
     OR p_quantity IS NULL OR p_quantity NOT BETWEEN 1 AND 100 THEN
    RAISE EXCEPTION 'Invalid order input' USING ERRCODE = '22023';
  END IF;
  input := jsonb_build_object('sku', p_sku, 'quantity', p_quantity);
 
  INSERT INTO retry_demo.order_requests(account_id, request_key, request)
  VALUES (p_account, p_key, input)
  ON CONFLICT (account_id, request_key) DO NOTHING
  RETURNING true INTO claimed;
 
  IF claimed IS TRUE THEN
    INSERT INTO retry_demo.orders(account_id, sku, quantity)
    VALUES (p_account, p_sku, p_quantity)
    RETURNING id INTO order_id;
    result := jsonb_build_object('orderId', order_id, 'status', 'received');
    UPDATE retry_demo.order_requests SET response = result
    WHERE account_id = p_account AND request_key = p_key;
    RETURN result;
  END IF;
 
  -- A separate statement gets a fresh READ COMMITTED snapshot.
  SELECT * INTO STRICT previous FROM retry_demo.order_requests
  WHERE account_id = p_account AND request_key = p_key;
  IF previous.request IS DISTINCT FROM input THEN
    RAISE EXCEPTION 'Key already used with different order data'
      USING ERRCODE = '22023';
  END IF;
  IF previous.response IS NULL THEN
    RAISE EXCEPTION 'Incomplete request record';
  END IF;
  RETURN previous.response;
END;
$$;

Download schema.sql. It creates a dedicated example schema and uses PostgreSQL's built-in UUID generator. Run it in a disposable database, once.

The saved input is a small jsonb object built from validated fields. It detects reuse with a different SKU or quantity. In a real endpoint, include every field that changes the operation's meaning. Comparing only the quantity would miss a changed delivery address, for example.

Seventeen calls, one saved order#

We ran the downloadable SQL on PostgreSQL 18.3 at READ COMMITTED in an isolated local database. The check counts saved orders and compares responses; it does not measure throughput.

The test held the first transaction open after it created the order. It then started 16 other sessions with the same account, key and payload. Before committing the first transaction, it checked pg_stat_activity and observed all 16 sessions waiting on locks. After the commit, it compared every response and counted the stored orders.

observed-results.json
{
  "postgres": "18.3",
  "same_key_replay": "pass",
  "payload_mismatch": "pass",
  "account_scope": "pass",
  "rollback_then_retry": "pass",
  "overlapping_requests": 17,
  "orders_after_overlap": 1,
  "concurrent_waiters_observed": 16,
  "all_responses_match": true
}

The remaining checks exercise completed-call replay, changed payloads, account scoping and rollback. Replay models the case where the client missed a response; the test does not drop network packets. The browser simulator runs separately from this database test.

Reproduce the result#

Load schema.sql into an empty disposable database. Then run verify.py with Python 3 and psql available. The script uses the standard PostgreSQL connection environment variables and Python's standard library.

run-the-check.sh
# Point these at your disposable database, not your application database.
export PGHOST=127.0.0.1
export PGPORT=5432
export PGUSER=your_test_role
export PGDATABASE=your_test_database
# Use your normal local authentication mechanism.
psql -v ON_ERROR_STOP=1 -f schema.sql
python verify.py

The script leaves a few synthetic rows for inspection. It uses fresh account IDs on each run, so you can run the verification repeatedly without clearing the schema. It fails if it cannot observe all 16 waiting sessions within its test timeout. The role running it needs visibility of those sessions; the example uses the same role for all connections.

Where the guarantee ends#

Before adapting this endpoint, decide how long to retain its keys and which other code paths can write orders. Both affect whether a later attempt can create another row.

BoundaryWhat still needs a decision
Key retentionDeleting the saved key allows a late retry to create another order. Choose and document the retry window.
Changed business stateThis returns the original receipt, not the order's current status. Use a separate read endpoint for current state.
Slow transactionsDuplicate requests can wait on the winning transaction. Bound the wait; do not hold the transaction open during external calls.
Other isolation levelsThis function refuses them. Adapting it requires handling their snapshot and retry behaviour.
Alternate write pathsAdmin tools or other endpoints that bypass the key table can still create duplicates.
External effectsAn email or payment provider is outside this database transaction.

Keep the key rows throughout the test. Deleting a row during a retry can remove the receipt that the retry needs. Restrict direct table writes to trusted application code.

An email introduces another failure window#

If you commit the order and then send an email, the process can stop between those steps. If you send the email first, the transaction can fail afterward.

A transactional outbox saves a notification event beside the order, in the same transaction. A worker then delivers it. If the worker crashes after sending and before recording success, it can send again, so the receiver or provider also needs deduplication. See AWS’s outbox guidance for that extension; the downloadable sample stops at the database receipt.

Show the pending result in the checkout#

After a timeout, keep the checkout pending while the client checks the order status or retries with the saved key. Use the returned receipt to show the original order reference.

We haven't confirmed your order yet.

Check its status or retry this submission. Keep the same pending operation while the result is being resolved.

Before shipping a similar endpoint, make the failure cases part of its acceptance checks:

  • The same key and data return the same receipt after commit.
  • Overlapping requests cannot create two orders through this path.
  • Reusing the key with different data is rejected.
  • Keys are scoped to an authenticated account and operation.
  • A rollback leaves the next attempt able to do the work.
  • Retention, timeouts and external effects have explicit policies.

Need this behavior in your application? Tell us which operation can be retried and what a duplicate would do.

Building a system for your business?

See how we scope custom software and integrations, with a delivered project to explore.

Bareet services

Custom software development

More articles

Engineering

Java4Shell: when decoding Base64 crosses a memory boundary

Engineering

Connecting an attendance device to a web app: designing the data pipeline