From 0e30d9dbe4114462ebd373b90e632ec3c1bb892f Mon Sep 17 00:00:00 2001 From: Nikolas Date: Mon, 25 Nov 2024 15:37:32 +0100 Subject: [PATCH] Update 058-transactions.mdx (#6422) * Update 058-transactions.mdx * Update content/200-orm/200-prisma-client/100-queries/058-transactions.mdx Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com> --------- Co-authored-by: Jon Harrell <4829245+jharrell@users.noreply.github.com> Co-authored-by: Ankur Datta <64993082+ankur-arch@users.noreply.github.com> --- .../100-queries/058-transactions.mdx | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/content/200-orm/200-prisma-client/100-queries/058-transactions.mdx b/content/200-orm/200-prisma-client/100-queries/058-transactions.mdx index 68225fa387..4f5409d729 100644 --- a/content/200-orm/200-prisma-client/100-queries/058-transactions.mdx +++ b/content/200-orm/200-prisma-client/100-queries/058-transactions.mdx @@ -491,6 +491,36 @@ To avoid transaction write conflicts and deadlocks on a transaction: } ``` +### Using `$transaction` within `Promise.all()` + +If you wrap a `$transaction` inside a call to `Promise.all()`, the queries inside the transaction will be executed _serially_ (i.e. one after another): + +```ts +await prisma.$transaction(async (prisma) => { + await Promise.all([ + prisma.user.findMany(), + prisma.user.findMany(), + prisma.user.findMany(), + prisma.user.findMany(), + prisma.user.findMany(), + prisma.user.findMany(), + prisma.user.findMany(), + prisma.user.findMany(), + prisma.user.findMany(), + prisma.user.findMany(), + ]) +}) +``` + + This may be counterintuitive because `Promise.all()` usually _parallelizes_ the calls passed into it. + +The reason for this behaviour is that: +- One transaction means that all queries inside it have to be run on the same connection. +- A database connection can only ever execute one query at a time. +- As one query blocks the connection while it is doing its work, putting a transaction into `Promise.all` effectively means that queries should be ran one after another. + + + ## Dependent writes Writes are considered **dependent** on each other if: