Note

Concurrency in transactions

There’s a temptation to make independent database operations concurrent:

await db.transaction(async (tx) => {
  await Promise.all([
    tx
      .update(accounts)
      .set({ balance: sql`${accounts.balance} - 100.00` })
      .where(eq(accounts.name, 'Dan')),
    tx
      .update(accounts)
      .set({ balance: sql`${accounts.balance} + 100.00` })
      .where(eq(accounts.name, 'Andrew')),
  ]);
});TypeScript

Inside a transaction, though, there usually isn’t any point. Even if both promises fire at once, the driver still has to send the statements down a single connection.

Anything not bound to the database connection can still run concurrently:

await db.transaction(async (tx) => {
  await Promise.all([
    otherAsyncWork(),
    tx
      .update(accounts)
      .set({ balance: sql`${accounts.balance} + 100.00` })
      .where(eq(accounts.name, 'Andrew')),
  ]);
});TypeScript

But you probably shouldn’t do other I/O in the middle of a transaction anyway if you can avoid it (especially writes). It keeps the transaction open for longer, and any external side effects won’t be rolled back.