A customer places an order, the server commits it, and the response never reaches the browser. The customer clicks again. Without a way to recognize the original checkout, the application can create another order.

Disabling the button helps with accidental clicks, but it cannot resolve a lost response, a page reload, or another browser tab. The server needs a durable record of the checkout attempt.

This guide uses a coffee-ordering API built with NestJS, Prisma, and PostgreSQL. It follows cash checkout: one reviewed cart becomes one order and one local payment record. Payment-provider session creation has additional recovery requirements, which are outside this walkthrough.

The snippets use Prisma Client 7 and illustrate the transaction boundaries and locking strategy. They assume existing customer, cart, order, and payment models, along with authentication and request validation. Adapt their names and relations to your application; they are not a complete checkout service.

Define what one checkout means

An idempotency key identifies one intended operation. Repeating that operation with the same key should return the order it already created.

For checkout, the request includes three values:

{
  "idempotencyKey": "5fb0905a-1b3a-4cdc-851d-79a6ff3768bc",
  "cartRevision": 7,
  "paymentProvider": "cash"
}

Here, revision 7 represents a cart the customer has reviewed. In the application, use the revision returned by the cart API.

The key belongs to a customer and is bound to the payment method and cart revision. Reusing it with different values is a conflict, rather than permission to create another order.

The example checkout endpoint is:

POST /api/customers/:customerId/cart/checkout

The customer ID in the URL is not proof of ownership. Protect the controller with JWT authentication and a customer ownership guard before calling the service. Use a DTO to validate a UUID v4 key, an integer revision within the database range, and an allowed payment provider. Keep those checks when adapting the pattern.

Persist the request identity

An in-memory map disappears on restart and cannot coordinate multiple API instances. Put the request identity in PostgreSQL.

These are the relevant fields from the checkout request model, with relations omitted:

model CheckoutRequest {
  customerId      String
  idempotencyKey  String                @db.Uuid
  paymentProvider PaymentProvider
  cartRevision    Int
  status          CheckoutRequestStatus @default(PENDING)
  orderId         String?               @unique
  createdAt       DateTime              @default(now())

  @@id([customerId, idempotencyKey])
}

The composite primary key gives each customer a separate key space. The unique order reference links a completed request to its result. Add the customer and order relations to match your schema. Define PaymentProvider values CASH and PAYMONGO, and CheckoutRequestStatus values PENDING, COMPLETED, and CANCELLED; the snippets below use those enums.

A separate request record is useful because checkout has a lifecycle beyond inserting an order: an unknown attempt may need recovery, and an unused key may need to be permanently closed before a delayed request arrives.

Do not delete completed keys independently of their orders. Removing the evidence of a completed attempt undermines retry safety.

Reserve and lock the request inside a transaction

A read followed by an insert is insufficient:

Request A: no existing request found
Request B: no existing request found
Request A: create order
Request B: create another order

Both callers can pass the first check. A database constraint and coordinated transaction must decide who proceeds.

The transaction first inserts the request if it does not exist, then locks that request row. This excerpt runs inside a Prisma interactive transaction after checking that the customer exists:

await tx.checkoutRequest.createMany({
  data: {
    customerId,
    idempotencyKey: key,
    cartRevision: revision,
    paymentProvider:
      provider === 'cash' ? PaymentProvider.CASH : PaymentProvider.PAYMONGO,
  },
  skipDuplicates: true,
});

await tx.$queryRaw`
  SELECT "idempotencyKey" FROM "CheckoutRequest"
  WHERE "customerId" = ${customerId} AND "idempotencyKey" = ${key}::uuid
  FOR UPDATE
`;

const request = await tx.checkoutRequest.findUniqueOrThrow({
  where: {
    customerId_idempotencyKey: {
      customerId,
      idempotencyKey: key,
    },
  },
  include: { order: { include: { items: true } } },
});

With PostgreSQL's default Read Committed isolation, a conflicting insert waits for the other transaction to resolve. The following statement can then read and lock the committed request. This sequence relies on that isolation behavior; changing the isolation level requires reviewing conflict handling. PostgreSQL Read Committed behavior

Use Prisma's tagged raw-query API to parameterize values. Do not build the query by concatenating customer input.

The request lock serializes callers using the same customer and key. Keep it until the transaction commits or rolls back.

Replay the result before inspecting the current cart

Once the request is loaded, check its payment method and revision against the submitted values. A mismatch returns 409 Conflict with CHECKOUT_KEY_REUSED.

If the request is completed, return its existing order. Do this before validating today's cart or whether the store is currently accepting orders.

Consider this sequence:

  1. Checkout succeeds, but the response is lost.
  2. The customer adds a drink to a new cart.
  3. The browser retries the original request.

That retry must return the original order and leave the new cart alone. It should also work if the store has closed since the first checkout.

The service has an early completed-request lookup for this path and repeats the replay check after acquiring the request lock. The second check handles callers that arrived while the original transaction was still running.

A replay returns the same order identity; it does not promise a byte-for-byte copy of the first HTTP response. Use 201 Created for a new checkout and 200 OK with a replay marker for an existing result.

Lock the cart to handle different keys

Request locking solves repeated use of one key. Two tabs could still submit different keys for the same cart.

Both transactions must also lock the cart row before reading its contents:

await tx.$queryRaw`
  SELECT "id" FROM "Cart"
  WHERE "customerId" = ${customerId}
  FOR UPDATE
`;

const cart = await tx.cart.findUnique({
  where: { customerId },
  include: { items: { include: { coffee: true } } },
});

The cart already exists in this checkout flow. A locking query cannot lock a row that does not exist.

The first transaction consumes the cart and increments its revision. After waiting, the second transaction reads the changed state and cannot consume the original cart again.

Cart mutations must follow the same locking discipline. Adding, updating, removing, or clearing items acquires the cart lock and increments the revision. Otherwise, a mutation could bypass checkout's coordination.

Keep the lock order consistent across related operations. In this service, checkout acquires the request lock, then the cart lock, then the store settings lock. PostgreSQL row locks coordinate competing writers; they do not block ordinary snapshot reads. PostgreSQL row-level locking

Validate the reviewed cart and calculate prices on the server

After acquiring the cart lock, validate the cart you actually read:

  • It exists and contains items.
  • Its revision matches the submitted revision.
  • The store accepts new orders.
  • Quantities and aggregate per-drink limits are valid.
  • The selected drinks and options are available.

A stale nonempty cart returns 409 Conflict with CART_CHANGED. An already consumed, empty cart is rejected as empty. Either outcome prevents a second order from the original contents.

A cart revision tracks cart changes. It does not freeze the catalog price. This example resolves the current catalog prices and available options during checkout. A product requiring explicit acceptance of a changed quote would need an additional quote or price-version contract.

Do not accept totals or unit prices from the browser. Calculate them from trusted catalog data using decimal arithmetic, and save the ordered drink details and prices as an order snapshot.

For example, two drinks at PHP 125.50 produce a PHP 251.00 order total. Later catalog edits should not rewrite what that order contained.

Commit the order, payment record, and cart changes together

For cash checkout, the transaction performs these writes as one unit:

  1. Create the order and its items.
  2. Create the local cash payment record.
  3. Remove the consumed cart items.
  4. Increment the cart revision.
  5. Mark the checkout request completed and attach its order ID.

Every helper participating in those writes must use the supplied tx client. A helper that writes through the root Prisma client would escape the transaction.

If payment record creation fails, roll back the order, cart changes, and newly inserted request record together. A retry using the same key can then attempt checkout again without leaving a partial order behind.

Here, “completed” describes the checkout request. It does not mean the drink has been prepared or the cash payment has been collected.

Keep external HTTP calls outside the database transaction. For an external payment provider, commit the local order and payment preparation first, then contact the provider through a separate, recoverable operation. A provider timeout can leave a committed order with an uncertain external outcome. Creating another order is not a safe response to that uncertainty.

Keep the same intent across retries and tabs

Generating a UUID on every click defeats idempotency. Save the checkout intent before sending the request, then reuse it until its outcome is resolved.

Store one unresolved intent per customer in IndexedDB. A read/write transaction reads the existing intent and creates one only when none exists. The operation resolves after the IndexedDB transaction completes, rather than after an individual write succeeds.

This coordinates cooperating tabs on the same browser origin. A simple localStorage read-then-write does not provide the same atomic operation.

The intent contains the customer ID, key, reviewed revision, and payment provider. If an unresolved intent already exists, the helper returns it unchanged. The checkout page must reconcile that attempt before starting one for a changed cart or payment method.

A network error does not prove that checkout failed. Retain the intent and recover its outcome. If storage is unavailable, show an actionable error instead of silently sending an untracked checkout.

Browser persistence improves recovery, but it is not the server's correctness boundary. Another device has separate storage; the cart lock and revision check still protect the cart.

Recover an unknown outcome without racing a delayed request

Checking for an order once and then generating a new key leaves a race: the original request might still be in transit.

Add an authenticated recovery endpoint:

POST /api/customers/:customerId/cart/checkout/recover

Send the original key, revision, and payment method. Recovery acquires the same request lock as checkout.

  • If checkout already completed, recovery returns the existing order.
  • If no order was created, recovery durably marks the request CANCELLED and returns checkoutNotCreated: true.
  • A later checkout using that closed key is rejected with CHECKOUT_REQUEST_CLOSED.

This cancelled request is a tombstone for an unused key. It does not cancel an order or modify a payment.

If recovery and checkout race, the shared request lock determines the result. Recovery either sees the committed order or closes the key before checkout can use it. Only after resolving the original intent should the client clear it and allow a newly reviewed checkout.

Test concurrency with PostgreSQL

Mocked Prisma calls cannot demonstrate database lock behavior. Use an isolated PostgreSQL database and synthetic customers, carts, and orders.

The important assertions are observable outcomes:

Scenario Expected outcome
Two simultaneous requests with the same key One order and one payment record; both receive the same order ID
Same key with a different provider or revision Conflict; no additional order
Different keys for one cart revision Only one checkout consumes the cart
Replay after refilling the cart Original order returned; new cart preserved
Replay after store closure Original order still recoverable
Stale revision No order created; cart preserved
Payment insert failure Order, request reservation, and cart changes roll back
Recovery racing checkout Existing order returned or unused key closed
Delayed request after recovery closes its key Rejected; no order created

Run these scenarios against a disposable PostgreSQL database using your application's migration and test commands. Keep test fixtures separate from live customer data.

For the same-key case, start two checkout calls concurrently and await both. Assert that both results identify the same order, then query the database to confirm exactly one order and one payment record exist for that fixture. Also assert that the cart was consumed once and the request points to the created order.

Repeat with different keys against the same cart revision: only one call may create an order. For rollback coverage, force the payment insert to fail and assert that the order and newly inserted request are absent while the original cart remains intact.

Coordinate concurrent calls at the database boundary so the test exercises overlapping transactions, rather than relying on arbitrary sleeps. Include HTTP-level tests for authentication, customer ownership, invalid request values, and creation versus replay status codes.

Keep the guarantee precise

This design makes retries of a recognized checkout return its existing order and prevents concurrent checkout from consuming the same reviewed cart twice.

It does not make every distributed side effect happen exactly once. Provider requests, notifications, inventory reservations, and fulfillment each need their own explicit consistency and recovery rules.

For the local checkout boundary, the essential pieces are a durable customer-scoped key, a bound request, coordinated cart mutations, atomic writes, and recovery that accounts for requests still in flight.

Example implementation

For the complete service, schema, browser intent storage, and database tests, see the checkout implementation in Caffeinawa. The link points to a fixed revision so the reference remains consistent with this guide.