Skip to content

TypeScriptCode Help: Prisma transaction deadlock on concurrent updates

Solved
Started byDuneRunner207views5repliesnextjspostgres
  1. L11
    #1

    Two requests update the same two rows in a transaction and one fails with a deadlock about once a day:

    ts
    await db.$transaction(async (tx) => {
      await tx.account.update({ where: { id: fromId }, data: { balance: { decrement: amount } } });
      await tx.account.update({ where: { id: toId }, data: { balance: { increment: amount } } });
    });
    

    Transfer A→B and B→A at the same time deadlock. How do I avoid this?

    Accepted answer by ByteNomad

    Go to answer

    Retries hide it; the fix is lock ordering. Always lock rows in the same order (for example ascending id), regardless of direction:

    ts
    await db.$transaction(async (tx) => {
      const [a, b] = [fromId, toId].sort((x, y) => x - y);
      await tx.$queryRaw`SELECT id FROM "Account" WHERE id IN (${a}, ${b}) ORDER BY id FOR UPDATE`;
      // now do the two updates in any order
    });
    

    Both transactions now try to lock the lower id first, so one waits instead of deadlocking. Keep a small retry for serialization failures as a safety net.

  2. L3
    #2

    Maybe retry on deadlock errors?

  3. Accepted answer
    1 year at OasisL22
    #3

    Retries hide it; the fix is lock ordering. Always lock rows in the same order (for example ascending id), regardless of direction:

    ts
    await db.$transaction(async (tx) => {
      const [a, b] = [fromId, toId].sort((x, y) => x - y);
      await tx.$queryRaw`SELECT id FROM "Account" WHERE id IN (${a}, ${b}) ORDER BY id FOR UPDATE`;
      // now do the two updates in any order
    });
    

    Both transactions now try to lock the lower id first, so one waits instead of deadlocking. Keep a small retry for serialization failures as a safety net.

    ByteNomad Dev Studio · Next.js, Postgres, bots · milestone escrow

  4. 1 year at OasisL9
    #4

    Sorting the ids fixed it. Zero deadlocks in a week. Thank you!

  5. L3
    #5

    Bookmarked. Add a minimal reproduction and you'll get an answer in minutes.

  6. L11
    #6

    Write the test for the bug before fixing it. Future you will thank you.

Sign in to reply

Join the conversation: sign in or create an account to reply.