skip to content

In Prisma 7, two concurrent guest checkouts use connectOrCreate on the same new email and one fails with P2002 - why, and what is the fix?

level: seniorimportance: should knowfreq 35%

answer

  1. look first, then insert
  2. both lookups miss
  3. the unique index decides the winner
  4. the whole nested write rolls back
  5. catch the code and retry

basics

~20 s

connectOrCreate is a lookup then an insert, not one atomic statement. Two concurrent checkouts both miss the email and both insert; the unique index rejects one with P2002, rolling back its whole order. The documented fix is catching P2002 and retrying.

solid answer

~50 s

A nested `connectOrCreate` runs as two steps inside the nested write's transaction: find the user by the unique `where`, and if nothing matches, insert from `create` and link it. When two checkouts for a new `[email protected]` overlap, both lookups miss because neither insert has committed. Both then insert, and the unique index on `User.email` lets only one succeed. The other call throws `Prisma.PrismaClientKnownRequestError` with code `P2002`, and because it is one nested write, its order and order lines roll back with it. The unique constraint is doing its job: without it you would get two users with that email. The Prisma docs recommend catching `P2002` and retrying; on the retry the lookup finds the committed user and simply connects it. Bound the retries, since a `P2002` from a different constraint will never succeed on a second try.

go deeper

for a junior

Recall that connectOrCreate links an existing record by a unique field or creates it when none matches.

for a middle

Explain that connectOrCreate is a lookup then an insert inside one nested write, and that P2002 is Prisma's unique-constraint error code.

for a senior

Diagnose the concurrent-insert race from intermittent P2002 errors, explain why the whole nested write rolls back, and add a bounded retry that rethrows other unique violations.

for a principal

Decide where get-or-create logic lives across a codebase, a shared retry helper or a database upsert first, so every concurrent path handles P2002 the same way.

## What connectOrCreate actually does `connectOrCreate` is a **nested write** operation on a relation field. You give it a unique `where` and a `create` payload: ```ts user: { connectOrCreate: { where: { email }, create: { email }, }, } ``` It reads like an atomic "get or create", but Prisma Client carries it out as **two steps** inside the transaction of the surrounding nested write: 1. Look for a `User` matching the unique `where`. 2. If none exists, insert one from `create`; then link it to the parent record. The `where` is typed as a unique input (an `@id`, `@unique` or compound unique), so the field behind it always has a unique constraint in the database. That constraint is what turns a race into an error instead of a duplicate. ## How the race unfolds Two guest checkouts for the same new email arrive together. The Prisma docs walk through exactly this interleaving: | Checkout A | Checkout B | | --- | --- | | starts its transaction | starts its transaction | | | looks up `[email protected]`: not found | | looks up `[email protected]`: not found | | | | inserts the user, links the order | | inserts the user | | | **unique violation**: B created it first | commits | Neither lookup can see the other's uncommitted insert, so both decide to create. The database's unique index on `email` accepts one insert and rejects the other. In Prisma ORM 7 the PostgreSQL driver adapter reports the unique violation, and Prisma Client throws a **`PrismaClientKnownRequestError` with code `P2002`**. Because everything happened inside one nested write, checkout A's order and its order lines are rolled back as well: nothing half-written remains. ## The documented fix: catch and retry The reference documentation for `connectOrCreate` recommends catching the unique-violation exception (`P2002`) and retrying the query. On the second attempt the user row is committed, the lookup finds it, and `connectOrCreate` takes the connect path. ```ts import { Prisma } from "./generated/prisma/client"; async function placeGuestOrder(email: string, sku: string) { for (let attempt = 1; ; attempt++) { try { return await prisma.order.create({ data: { user: { connectOrCreate: { where: { email }, create: { email } } }, items: { create: [{ quantity: 1, product: { connect: { sku } } }] }, }, }); } catch (e) { const unique = e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002"; if (!unique || attempt === 3) throw e; } } } ``` Points that make the retry safe: - **Retry the whole call.** The failed transaction is already rolled back, so re-running the complete nested write cannot double-insert the order. - **Bound it.** `P2002` also fires for other unique constraints, such as the same product added twice to an explicit join model with `@@id([orderId, productId])`. That never succeeds on a retry, so cap the attempts and rethrow. - **Keep the error class from the generated client.** In Prisma 7 the `Prisma` namespace is imported from the generator's output path, here `./generated/prisma/client`, not from a fixed package path. ## Alternatives and what they do not fix - **Create the user first, then connect by id.** A top-level `prisma.user.upsert` can be handed to PostgreSQL as `INSERT ... ON CONFLICT` when it meets Prisma's database-upsert criteria, and then cannot raise the unique error. The order is then created with `user: { connect: { id } }`. This trades one call for two, so the user can exist without the order if the second call fails. - **Dropping `@unique` on email** makes both calls succeed and leaves two users with the same email. That is worse than an error. - **Nested `createMany` with `skipDuplicates`** is not an option here: it exists only on one-to-many lists, not on a to-one relation such as an order's user. - **Wrapping the call in `prisma.$transaction`** adds nothing. The nested write is already one transaction; the race is between two transactions. ## Recognising it in production The signature is low-rate `P2002` errors on a `connectOrCreate` path that line up with traffic spikes or client double-submits, never with sequential tests. Log the failing model and constraint, add the bounded retry, and treat a `P2002` that survives the retries as a real conflict to report.

  • Why does retrying the same call work instead of failing again?
    The losing transaction was rolled back, so nothing from it persists, while the winner's user row is now committed. On the retry `connectOrCreate` runs its lookup again, finds the email, and takes the connect path instead of inserting. The same email cannot collide twice once it is committed; the bound exists because a `P2002` from another constraint would repeat on every attempt.
  • Is a top-level upsert on the user race-free?
    Only when Prisma hands it to the database. On PostgreSQL, an `upsert` with no nested writes or nested reads that touches one model, has a single unique field in `where` and the same value in `create` becomes `INSERT ... ON CONFLICT`, which cannot raise the unique error. Otherwise Prisma Client runs it as find-then-write, with the same race and the same advice: catch `P2002` and retry.

Two clerks each check the guest list, find no entry for Ana, and both reach for the pen; the list only has room for one Ana, so the second clerk is refused, looks again, and simply ticks the entry that is now there.

  • connectOrCreate is a single atomic database statement, so it cannot race.
  • A P2002 from connectOrCreate means the where filter was not unique.
  • The failed checkout leaves its order saved without a user.
  • Wrapping the nested write in $transaction removes the race.
  • Removing @unique from email is an acceptable way to stop the error.