# Race conditions in serverless apps: double bookings, oversold stock and lost updates URL: https://www.prisma.io/blog/race-conditions-in-serverless-apps Published: 2026-11-30 Authors: Kiril Urbonas Tags: orm, prisma-postgres, education Description: Why serverless apps oversell stock, double-book slots and lose updates, and four Postgres fixes with SQL and Prisma ORM 8 code: atomic updates, FOR UPDATE, version columns and constraints. > Blog posts describe Prisma as it was on the date shown and are not kept current. Before implementing from a post, check the documentation index at https://www.prisma.io/docs/llms.txt and the changelog at https://www.prisma.io/changelog.md. > For an index of every published post, fetch https://www.prisma.io/blog/llms.txt. *A guest post by [Kiril Urbonas](https://www.devopsness.com), founder of DevOpsNess.* Your checkout code is correct. It reads the stock, checks there is at least one left, and decrements it. It passes every test. Then a drop goes live, two people buy the last ticket within the same 30 milliseconds, and both get a confirmation email. Nothing crashed and nothing was logged. Postgres did exactly what it was told. This is a race condition, and serverless apps are unusually good at producing them. This post covers the three bugs you will meet most often (oversold stock, double bookings and lost updates), why serverless makes them more likely, and four Postgres-native fixes, with the SQL and the [Prisma ORM 8](https://www.prisma.io/docs/orm) code for each. It ends with a short guide to choosing between them and a test you can drop into your suite. ## Why serverless makes this worse [#why-serverless-makes-this-worse] Race conditions are not new, but three things about serverless turn a rare bug into a weekly one. **There is no single process to hold a lock.** On one long-running server you might get away with an in-memory mutex. With functions, every request can land on a different instance, and a traffic spike means dozens of instances reading the same row at once. The database is the only place where all of them meet. **Retries are built in.** Queues, cron triggers and webhook providers deliver at least once. A payment webhook that times out on the first attempt will arrive again, possibly while the first attempt is still running, so your handler sees the same event twice, concurrently. **Users double-click.** A slow cold start makes people press Submit again, and that is two concurrent requests with the same intent. A host with fast resumes makes this one rarer: [Prisma Compute](https://www.prisma.io/docs/compute), for example, resumes an idle instance from a memory snapshot in milliseconds. It does nothing about the retried webhook or the two buyers on the same drop, though. In all three cases the fix belongs in the database, because it is the one component every request goes through. ## The setup [#the-setup] The examples use a Prisma ORM 8 project with the contract at `src/prisma/contract.prisma` and a client in `src/prisma/db.ts`: ```ts // src/prisma/db.ts import 'dotenv/config'; import postgres from '@prisma/orm-postgres/runtime'; import { contractFromJson } from '@prisma/orm-postgres/static'; import type { Contract } from './contract.d.js'; import contractJson from './contract.json' with { type: 'json' }; export const contract = contractFromJson(contractJson); export const db = postgres({ contract, url: process.env['DATABASE_URL']! }); ``` Everything here is plain Postgres, so it runs on any Postgres 17 database. On [Prisma Postgres](https://www.prisma.io/docs/postgres), point `DATABASE_URL` at the pooled connection string (`pooled.db.prisma.io`), which is the one meant for application traffic. ## The bug, step by step [#the-bug-step-by-step] Here is the code almost everyone writes first: ```ts // ❌ Check-then-write: correct alone, wrong under concurrency const product = await db.orm.public.Product.first({ id }); if (!product || product.stock < 1) throw new SoldOutError(); await db.orm.public.Product.where({ id }).update({ stock: product.stock - 1 }); await db.orm.public.Order.create({ productId: id, userId }); ``` The problem is the gap between the read and the write. Two requests can both read `stock = 1`, both pass the check, and both write `stock = 0`: Postgres's [default isolation level](https://www.prisma.io/dataguide/postgresql/inserting-and-modifying-data/using-transactions), `READ COMMITTED`, does not prevent this. Each statement sees committed data, but nothing ties your `SELECT` to your later `UPDATE`. Wrapping both in a transaction does not help on its own either: the transaction makes the writes all-or-nothing, but it does not stop another transaction from reading the same row in between. We ran this exact code against PostgreSQL 17 with two concurrent requests, and it fails in two ways depending on the stock. With the stock at 1, both requests reported a sale: one ticket, two orders. With the stock at 5, both requests sold a ticket but the stock only went down to 4, because the second write overwrote the first. That is a lost update. The same shape shows up everywhere: * **Oversold stock:** check quantity, then decrement. * **Double bookings:** check that a slot is free, then insert a booking. * **Lost updates:** two people edit the same record and the second save silently overwrites the first. * **Duplicate side effects:** a retried webhook checks "has this payment been processed?", then processes it. ## Fix 1: Make the check part of the write [#fix-1-make-the-check-part-of-the-write] If the rule fits in a `WHERE` clause, put it there. Postgres locks the row while it updates it, so the second request waits, then re-checks the condition against the new value and updates zero rows. ```sql UPDATE "Product" SET stock = stock - 1 WHERE id = $1 AND stock > 0; -- 1 row updated = sold, 0 rows = sold out ``` In Prisma ORM 8, run it as raw SQL with `tx.raw.sql`, ask for the affected count, and execute it with `tx.execute()`, which returns `{ affectedRows }`. Do it [inside a transaction](https://www.prisma.io/docs/orm/fundamentals/transactions) so the order is only created if the decrement succeeded: ```ts await db.transaction(async (tx) => { const { affectedRows } = await tx.execute( tx.raw.sql`UPDATE "Product" SET stock = stock - 1 WHERE id = ${id} AND stock > 0` .affectedCount() .build(), ); if (affectedRows === 0) throw new SoldOutError(); // rolls back the transaction await tx.orm.public.Order.create({ productId: id, userId }); }); ``` Because `stock = stock - 1` is computed by the database rather than in your code, this also fixes the lost-update version of the bug. In our test, 20 concurrent buyers of the last ticket produced exactly one sale and 19 `SoldOutError`s. As a backstop, declare a `CHECK` constraint in the contract, so the database refuses to go negative even if some future code path forgets the `WHERE` clause: ```prisma model Product { id Int @id @default(autoincrement()) title String stock Int @@check(expression: sql`stock >= 0`, name: "product_stock_non_negative") } ``` Run `prisma contract emit`, then `prisma migration plan`, which adds the constraint to the next migration. A write that would make the stock negative fails with Postgres error `23514`. **Use it when** the rule is about a single row and fits in SQL. This is the cheapest fix and should be your default. ## Fix 2: Lock the row before you read it [#fix-2-lock-the-row-before-you-read-it] Sometimes the decision cannot be made in a `WHERE` clause. Maybe you need to read several columns, call a pricing function, or apply business logic in TypeScript. In that case, lock the row when you read it with `.forUpdate()`. Any other transaction that tries to lock the same row waits until yours commits, then reads the committed value. ```ts await db.transaction( async (tx) => { const seat = await tx.orm.public.Seat.where({ id: seatId }).forUpdate().first(); if (!seat || seat.status !== 'available') throw new SeatTakenError(); // price is a Decimal column, so it arrives as decimal text such as "49.90" const total = applyPromo(seat.price, promoCode); // any app logic you need await tx.orm.public.Seat.where({ id: seatId }).update({ status: 'held', heldBy: userId }); await tx.orm.public.Order.create({ seatId, userId, total }); }, { timeout: 2_000 }, // keep the lock window short ); ``` In our test, the second transaction waited until the first committed, then saw the seat as held and threw `SeatTakenError`. Only one order was created. Four rules keep this safe: * **Keep the transaction short, and set a timeout.** Every other request for that row queues behind you. Prisma ORM 8 transactions have no default timeout, so [pass one explicitly](https://www.prisma.io/docs/orm/fundamentals/transactions#options-and-isolation-level). With `{ timeout: 2_000 }`, a transaction that runs longer fails with `RUNTIME.TRANSACTION_TIMEOUT` and rolls back. * **Never call an external API while holding the lock.** If a payment provider takes 8 seconds to respond, every buyer of that seat waits 8 seconds. Hold the seat, commit, charge the card, then confirm in a second short transaction. * **Lock rows in a consistent order.** If one request locks seat 4 then seat 5, and another locks 5 then 4, they can deadlock. Postgres detects it and aborts one of them with error `40P01`, but you would rather not have to handle it. Sort IDs before locking several rows. * **`FOR UPDATE` only locks rows that already exist.** It cannot stop two requests that both check that no booking exists and then both insert one, because there is no row to lock yet. In our test, two such transactions both succeeded. For check-then-insert rules, use a constraint (Fix 4). On Prisma Postgres, the [connection pooler](https://www.prisma.io/docs/postgres/database/connection-pooling) runs PgBouncer in transaction mode. That works fine with `FOR UPDATE`, because the lock lives inside the transaction. Session-level features such as `pg_advisory_lock` (without `_xact`) do not belong on a pooled connection. If you need an advisory lock, use `pg_advisory_xact_lock`, which is released at commit. Also note that Prisma Postgres bills every statement the client sends as one operation, including `BEGIN`, `COMMIT` and `ROLLBACK`. The transaction above is five operations (`BEGIN`, lock-and-read, update, insert, `COMMIT`), not one. `FOR UPDATE` has a sibling, `SKIP LOCKED`, that skips locked rows instead of waiting for them. That is the wrong tool for a seat everyone wants, but it is exactly what a worker queue needs, as the post on [building a job queue in Postgres](https://www.prisma.io/blog/you-dont-need-a-job-queue-postgres-already-has-skip-locked) shows. **Use it when** the decision needs app logic between the read and the write, and contention on the row is real. ## Fix 3: Optimistic concurrency with a version column [#fix-3-optimistic-concurrency-with-a-version-column] Locks are pessimistic: they assume a conflict will happen and make others wait. For records that people edit by hand (a document, a profile, a settings page), conflicts are rare and edits can take minutes. Holding a lock that long is not an option. Instead, add a version column. Read the record along with its version, and when you save, only update if the version is still the one you read. ```prisma model Document { id Int @id @default(autoincrement()) title String body String version Int @default(0) } ``` ```ts // The client sent back the version it loaded const { affectedRows } = await db.execute( db.raw.sql` UPDATE "Document" SET title = ${title}, body = ${body}, version = version + 1 WHERE id = ${id} AND version = ${expectedVersion} ` .affectedCount() .build(), ); if (affectedRows === 0) { // Someone saved first. Return 409 and let the user reload or merge. throw new ConflictError('This document was changed by someone else.'); } ``` The second writer gets zero rows instead of silently overwriting the first. What you do next depends on the product: show a "this changed, reload?" message, merge the fields, or retry automatically if the operation is safe to recompute. **Use it when** conflicts are rare, the gap between read and write is long (often a human), or you cannot hold a transaction open. It also fits APIs well, where you can expose the version as an `ETag` and require `If-Match` on updates. ## Fix 4: Let a constraint decide [#fix-4-let-a-constraint-decide] The strongest fix is to make the bad state impossible to store. If your rule can be phrased as "no two rows may...", Postgres can probably enforce it directly, and then it holds for every code path, including the admin script someone writes next year. ### One booking per seat: a unique constraint [#one-booking-per-seat-a-unique-constraint] ```prisma model Booking { id Int @id @default(autoincrement()) showId Int seatNo String userId Int @@unique([showId, seatNo]) } ``` ```ts try { await db.orm.public.Booking.create({ showId, seatNo, userId }); } catch (e) { if ((e as { sqlState?: string }).sqlState === '23505') { throw new SeatTakenError(); // unique violation } throw e; } ``` No read first, no lock. Of two concurrent inserts for the same seat, one succeeds and the other fails with Postgres error `23505`, which Prisma ORM 8 passes through on `error.sqlState`. One caveat: a unique violation aborts the surrounding transaction. If the insert runs inside `db.transaction`, you cannot catch the error and carry on, because every later statement in that transaction fails with `25P02` until it rolls back. Catch the error outside the transaction, or use `ON CONFLICT DO NOTHING` (below) when the transaction must continue. ### No overlapping time slots: an exclusion constraint [#no-overlapping-time-slots-an-exclusion-constraint] Rooms, appointments and rentals are harder. The rule is "no two bookings for the same room may overlap in time", and a unique constraint cannot express overlap. Postgres has an [exclusion constraint](https://www.postgresql.org/docs/current/ddl-constraints.html) for exactly this. The contract declares the `btree_gist` extension and the `tstzrange` column. Prisma ORM 8 has no range type, so the column is a `Raw` column: ```prisma extension btree_gist {} model RoomBooking { id Int @id @default(autoincrement()) roomId Int userId Int during Raw(sql`tstzrange`) } ``` The `EXCLUDE` constraint itself is not part of the contract, so it goes into the migration by hand. Run `prisma contract emit` and `prisma migration plan --name room_booking`, then add a `rawSql` operation after the generated `createTable` in its `migration.ts`: ```ts import { Migration, MigrationCLI, col, primaryKey, rawSql } from '@prisma/orm-postgres/migration'; // ...inside the generated class: override get operations() { return [ this.createTable({ /* generated by migration plan */ }), rawSql({ id: 'constraint.RoomBooking.no_overlap', label: 'Prevent overlapping bookings of the same room', operationClass: 'additive', target: { id: 'postgres' }, precheck: [ { description: 'constraint no_overlap does not exist yet', sql: "SELECT NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'no_overlap' AND contype = 'x' AND conrelid = to_regclass('\"public\".\"RoomBooking\"'))", }, ], execute: [ { description: 'add exclusion constraint no_overlap', sql: 'ALTER TABLE "public"."RoomBooking" ADD CONSTRAINT no_overlap EXCLUDE USING gist ("roomId" WITH =, during WITH &&)', }, ], postcheck: [ { description: 'constraint no_overlap exists', sql: "SELECT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'no_overlap' AND contype = 'x' AND conrelid = to_regclass('\"public\".\"RoomBooking\"'))", }, ], }), ]; } ``` Run `node migrations/app/_room_booking/migration.ts` to re-emit the package, then `prisma db migrate`. `btree_gist` lets a GiST index combine ordinary equality (`roomId`) with range overlap (`&&`), and it is available on Prisma Postgres. A `Raw` field can be read and written through the ORM, so the insert is an ordinary `create()`. Write the range as the text Postgres reads, and catch exclusion violations (`23P01`): ```ts try { await db.orm.public.RoomBooking.create({ roomId, userId, during: `[${start},${end})`, }); } catch (e) { if ((e as { sqlState?: string }).sqlState === '23P01') { throw new SlotTakenError(); // overlaps an existing booking } throw e; } ``` The `[start, end)` form includes the start and excludes the end, so a booking from 10:00 to 11:00 and one from 11:00 to 12:00 do not overlap, while 10:00 to 11:00 and 10:30 to 11:30 do. We tested this with three concurrent overlapping inserts: exactly one booking was created and the other two failed with `23P01`. A back-to-back booking afterwards succeeded. If you are building a booking product end to end, the guide on [hosting a booking app](https://www.prisma.io/postgres/booking-app-hosting) covers the same reservation rule along with the hosting and database setup around it. ### Exactly-once webhooks: an idempotency key [#exactly-once-webhooks-an-idempotency-key] The same idea fixes duplicate side effects. Store the event ID (or a client-generated idempotency key) in a unique column: ```prisma model ProcessedEvent { id Int @id @default(autoincrement()) eventId String @unique } ``` Then make "record the event" the first write, in the same transaction as the fulfilment writes. [`ON CONFLICT DO NOTHING`](https://www.prisma.io/dataguide/postgresql/inserting-and-modifying-data/insert-on-conflict) turns a duplicate into zero affected rows instead of an error, so the transaction stays usable: ```ts await db.transaction(async (tx) => { const { affectedRows } = await tx.execute( tx.raw.sql` INSERT INTO "ProcessedEvent" ("eventId") VALUES (${event.id}) ON CONFLICT ("eventId") DO NOTHING ` .affectedCount() .build(), ); if (affectedRows === 0) return; // already handled: acknowledge and exit await fulfilOrder(tx, event); // runs once per event ID }); ``` A concurrent delivery of the same event waits on the first one's insert. If the first commits, the second inserts nothing and exits. If the first crashes partway through, its transaction rolls back the marker too, and the retry starts fresh. In our test, three concurrent deliveries of one event produced exactly one order, and a delivery that crashed during fulfilment left no marker behind. **Use it when** the rule is about uniqueness or overlap. If a constraint fits, prefer it to every other fix in this post. ## When the rule spans rows: SERIALIZABLE [#when-the-rule-spans-rows-serializable] There is one shape the fixes above do not cover well: a rule about a set of rows, where each transaction changes a different row. The classic example is an on-call rota that must always have at least one person on call. Alice and Bob are both on call. Each opens the app at the same moment, sees two people on call, and takes themselves off. Each updates only their own row, so no row lock conflicts and no constraint fires, and nobody is left on call. This is called write skew. We reproduced it on PostgreSQL 17. Under `READ COMMITTED` and under `REPEATABLE READ`, both updates succeeded and nobody was left on call. Under `SERIALIZABLE`, Postgres detected the dependency and aborted one transaction with error `40001` (serialization failure). On retry, that transaction saw only one person on call and refused, so one person stayed on call. `SERIALIZABLE` adds no blocking of its own beyond what `REPEATABLE READ` already does (two updates to the same row still wait on the row lock). It lets transactions run, then aborts one if their combined result could not have happened in some serial order, which means [you must retry](https://www.prisma.io/docs/orm/fundamentals/transactions#write-conflicts). A conflict detected during a statement arrives with `error.sqlState`. One detected at commit, which is common, arrives as `RUNTIME.TRANSACTION_COMMIT_FAILED` with the Postgres error on `error.cause`, so check both: ```ts import { IsolationLevel } from '@prisma/orm-postgres/runtime'; import { db } from './prisma/db'; type Tx = Parameters[0]>[0]; const RETRYABLE = new Set(['40001', '40P01']); // serialization failure, deadlock function isRetryable(e: unknown): boolean { const err = e as { sqlState?: string; cause?: { sqlState?: string } }; const state = err?.sqlState ?? err?.cause?.sqlState; return state !== undefined && RETRYABLE.has(state); } async function serializable(fn: (tx: Tx) => Promise, attempts = 3): Promise { for (let i = 1; ; i++) { try { return await db.transaction(fn, { isolationLevel: IsolationLevel.Serializable }); } catch (e) { if (!isRetryable(e) || i >= attempts) throw e; await new Promise((r) => setTimeout(r, 20 * 2 ** i + Math.random() * 20)); } } } await serializable(async (tx) => { const { onCall } = await tx.orm.public.Rota.where({ onCall: true }).aggregate((a) => ({ onCall: a.count(), })); if (onCall < 2) throw new LastPersonError(); await tx.orm.public.Rota.where({ doctor: me }).update({ onCall: false }); }); ``` Only run a transaction body through this wrapper if it is safe to run more than once. Do not send emails or charge cards inside it. Two caveats. First, `SERIALIZABLE` only catches write skew when every transaction involved runs at `SERIALIZABLE`. In our test, one `SERIALIZABLE` transaction racing one `READ COMMITTED` transaction still left nobody on call, so route every write to the rota through the same wrapper. Second, it has a cost: more aborted transactions under load, and the retries that come with them. Use it for the few flows that need it rather than as a global setting. ## Choosing a fix [#choosing-a-fix] Most teams only need the first two questions in this tree:
```mermaid flowchart TD Q1["Rule is no two rows may... (duplicates or overlaps)?"] -->|Yes| C["Fix 4: UNIQUE or EXCLUDE constraint"] Q1 -->|No| Q2["One row, fits in a WHERE clause?"] Q2 -->|Yes| U["Fix 1: atomic conditional UPDATE"] Q2 -->|No| Q3["Long gap between read and write, like a person editing?"] Q3 -->|Yes| V["Fix 3: version column"] Q3 -->|No| Q4["Rule spans rows, each transaction writes a different one?"] Q4 -->|Yes| S["SERIALIZABLE with retry"] Q4 -->|No| L["Fix 2: .forUpdate() row lock"] ```
| Fix | Prevents | Cost | Good for | | ------------------------------- | ---------------------------------------------------- | ----------------------------- | ---------------------------------------------- | | Atomic conditional update | Oversell, lost updates on one row | Almost none | Counters, stock, balances, quotas | | `.forUpdate()` | Read-decide-write on rows that exist | Other requests wait | Checkout with app logic, seat holds | | Version column | Lost updates | Caller handles conflicts | Documents, forms, REST APIs with ETags | | `UNIQUE` / `EXCLUDE` constraint | Duplicates and overlaps, including check-then-insert | One-time migration | Bookings, idempotency keys, one-per-user rules | | `SERIALIZABLE` + retry | Write skew across rows | Aborts and retries under load | Rules over sets of rows (rotas, limits) | These combine well. A typical checkout uses an idempotency key (constraint), an atomic stock decrement and a `CHECK (stock >= 0)` backstop, all in one short transaction. ## Prove it with a test [#prove-it-with-a-test] Race conditions hide from ordinary tests because tests run one request at a time. Fire requests concurrently instead and check the invariant afterwards. This runs against a real database: a local Postgres or your CI test database. Twenty concurrent requests need twenty connections, and the client's pool opens at most 10 by default, so raise the limit with `poolOptions`: ```ts // src/prisma/db.ts export const db = postgres({ contract, url: process.env['DATABASE_URL']!, poolOptions: { max: 20 }, }); ``` Keep creating the client from the connection URL like this rather than passing in your own `pg.Pool`. A client built from your own pool sends an extra statement after every transaction, which on Prisma Postgres adds an operation each time. A Free Prisma Postgres database allows 10 pooled connections, so run this test against a local Postgres or a paid plan. If you deploy on Prisma Compute, a preview branch gets its own new Prisma Postgres database for each database declared in your Composer module, so you can run the test there without touching production data. The test below calls `buyTicket(productId, userId)`, a function in `src/checkout.ts` that runs the purchase. Point it at the check-then-write code or at Fix 1 to compare: ```ts import { afterAll, beforeAll, expect, test } from 'vitest'; import { db } from '../src/prisma/db'; import { buyTicket } from '../src/checkout'; let productId: number; // Create the product, then open all 20 connections. A cold pool connects // one by one, which spreads the requests out and can hide the race. beforeAll(async () => { const product = await db.orm.public.Product.create({ title: 'Last ticket', stock: 1 }); productId = product.id; await Promise.all( Array.from({ length: 20 }, () => db.orm.public.Product.first({ id: productId })), ); }); afterAll(() => db.close()); test('the last ticket is sold exactly once', async () => { await db.orm.public.Order.where({ productId }).deleteAll(); await db.orm.public.Product.where({ id: productId }).update({ stock: 1 }); const results = await Promise.allSettled( Array.from({ length: 20 }, (_, i) => buyTicket(productId, i + 1)), ); const sold = results.filter((r) => r.status === 'fulfilled').length; const product = await db.orm.public.Product.first({ id: productId }); const orders = await db.orm.public.Order.where({ productId }).all(); expect(sold).toBe(1); expect(orders).toHaveLength(1); expect(product?.stock).toBe(0); }); ``` Run it against the check-then-write version from the top of this post and it fails: in our runs, all 20 requests "bought" the one ticket. Run it against Fix 1 and it passes. Without the warm-up, the check-then-write version sometimes passed, because the requests ended up running one after another while the pool opened connections. ## Key takeaways [#key-takeaways] * In serverless apps the database is the only place where concurrent requests meet, so that is where the fix goes. * A transaction alone does not prevent races at `READ COMMITTED`. It makes writes all-or-nothing, nothing more. * Default to a constraint or an atomic conditional `UPDATE`. They are the cheapest and the hardest to get wrong. * Use `.forUpdate()` when you need app logic between the read and the write, keep the transaction short, and set a timeout. * Use a version column when the "transaction" is a person editing a form. * Reach for `SERIALIZABLE` only for rules that span rows, run every competing transaction at that level, and always retry on serialization failures. * Test with concurrent requests and a warm pool, or you are not testing for this at all. *All code samples were tested with Prisma ORM 8 (`@prisma/orm-postgres` 8.0.0-rc.25, `prisma` CLI 8.0.0-rc.36) on PostgreSQL 17.11 with concurrent connections.*