Postgres pool, review round 1: nested transactions, account mail after commit

P-1: a transaction begun inside another one (a hook calling the Local API
without req) no longer queues behind its caller. An AsyncLocalStorage mark set
when a transaction begins lets the inner one through at once, without a
place, but never into the last connection (a second level may take that
one). If the mark is lost, a queue that has not moved for a second admits
its newest waiter. connectionReserve: false now admits everything, as
before. Measured on Postgres 17: 9, 12 and 30 such submissions finish
(before: stuck from 9).

P-2: Payload's "forgot password" and "verify your e-mail" through
mailAdapter() go out right after their transaction commits
(mail.accountMailAfterCommit, default on). With the relay hanging,
30 resets + 30 submissions finish in about 11 s instead of 43.5 s.

P-3: Postgres tests for the "not confirmed" file result after commit, a
caller's outer transaction rolled back or committed, the relay hanging,
and the nested rows; deployment.md has the measured table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 01:19:27 +01:00
co-authored by Claude Opus 5.5
parent 32bb542e8e
commit 4efadb21d5
18 changed files with 534 additions and 107 deletions
+100 -41
View File
@@ -1,5 +1,7 @@
import type { BasePayload, PayloadRequest } from 'payload'
import { AsyncLocalStorage } from 'node:async_hooks'
/**
* Transactions and the Postgres pool.
*
@@ -11,19 +13,31 @@ import type { BasePayload, PayloadRequest } from 'payload'
*
* `reserveConnections` keeps a few connections free of transactions: at most `pool size − reserve`
* transactions are open at once, the next one waits for a free place (its request is slower, nothing
* stops). A transaction that has waited a second (ESCAPE_MS) may use the reserve too, all but its last
* connection — so a transaction begun inside another one (a hook that calls the Local API without `req`)
* does not wait for ever on its own caller, and one connection is never held by a transaction.
* stops).
*
* A transaction begun INSIDE another one — a hook that calls the Local API without `req` writes in a
* transaction of its own while its caller's stays open — is not queued: it takes no place and goes
* straight to the pool, because its caller cannot finish without it. "Inside" is told by an
* AsyncLocalStorage mark set when the outer one begins. In case the mark is lost on the way (Node 22
* keeps such a mark per callback, not per operation), a queue that has not moved for a second
* (RESERVE_ESCAPE_MS) lets its NEWEST waiter — the one most likely begun by a waiting caller — use the
* reserve, all but the last connection.
*
* `afterCommit(req, fn)` runs `fn` right after the transaction of `req` commits, before the operation that
* began it returns — for work that must not hold a connection, such as sending e-mail.
*/
type TransactionID = number | string
type Entry = { after: (() => Promise<void> | void)[] }
type Waiter = { resolve: () => void; since: number }
type Entry = { after: (() => Promise<void> | void)[]; depth: number; slot: boolean }
/** `depth`: 0 = an outer transaction, 1 = begun inside one, 2 = inside that, … */
type Waiter = { depth: number; resolve: () => void; since: number }
type Watch = {
/** Transactions holding one of the limited places. */
active: number
/** When a place was last given back (or the watch started). */
moved: number
/** Transactions begun inside another one: no place, straight to the pool. */
nested: number
/** Open transactions begun through this watch, by id. */
open: Map<TransactionID, Entry>
queue: Waiter[]
@@ -40,9 +54,12 @@ type WatchedDb = {
}
const WATCH = Symbol.for('iapl.transactionWatch')
/** After this long in the queue a transaction may use the reserve (all but one connection). */
/** A queue that has not moved this long lets its newest waiter use the reserve (all but one connection). */
export const RESERVE_ESCAPE_MS = 1000
/** The transaction the running code is inside: set in the caller's own continuation when it begins one. */
const current = new AsyncLocalStorage<{ depth: number; id?: TransactionID }>()
const dbOf = (payload: BasePayload) => ((payload as { db?: unknown } | undefined)?.db ?? {}) as WatchedDb
/** The size of the adapter's pool (pg's default is 10), or null for an adapter without one. */
@@ -58,22 +75,52 @@ export function defaultConnectionReserve(size: number): number {
return size < 4 ? 1 : Math.max(2, Math.ceil(size / 5))
}
function drain(payload: BasePayload, watch: Watch): void {
const limitOf = (payload: BasePayload, watch: Watch) => {
const size = poolSize(payload) ?? Infinity
const limit = watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve)
const escapeLimit = Math.max(limit, size - 1)
return { limit: watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve), size }
}
/** How many transactions may be open in all when one begun at nesting `depth` (1 = inside an outer one) is let in. */
const nestedRoom = (size: number, limit: number, depth: number) => Math.max(size - 2, limit) + depth
function admit(watch: Watch, waiter: Waiter): void {
watch.queue.splice(watch.queue.indexOf(waiter), 1)
if (waiter.depth > 0) {watch.nested += 1}
else {watch.active += 1}
waiter.resolve()
}
function drain(payload: BasePayload, watch: Watch): void {
const { limit, size } = limitOf(payload, watch)
// No reserve (switched off, or an adapter without a pool): nobody waits.
if (watch.reserve === null) {
while (watch.queue.length) {admit(watch, watch.queue[0])}
return
}
const open = () => watch.active + watch.nested
// A transaction begun inside another one first, the deepest first: its caller holds a place and waits for it.
// It may use the reserve but the last connection (a second level that one too; in a pool of 3 or 4, one place
// past the limit per level), so that a connection is left for the queries that run outside transactions.
for (const waiter of [...watch.queue].filter((w) => w.depth > 0).sort((a, b) => b.depth - a.depth)) {
if (open() < nestedRoom(size, limit, waiter.depth)) {admit(watch, waiter)}
}
// Then first come, first served while there is a place.
let head = watch.queue.find((w) => w.depth === 0)
while (head && watch.active < limit && open() < size - 1) {
admit(watch, head)
head = watch.queue.find((w) => w.depth === 0)
}
if (!watch.queue.length) {return}
const now = Date.now()
// First come, first served; a waiter that has waited ESCAPE_MS may use the reserve but the last connection.
while (watch.queue.length) {
const waiter = watch.queue[0]
const room = now - waiter.since >= RESERVE_ESCAPE_MS ? escapeLimit : limit
if (watch.active >= room) {break}
watch.queue.shift()
watch.active += 1
waiter.resolve()
// The queue has not moved for a second: the places may all be held by callers waiting for a transaction of
// their own whose mark was lost. The newest waiter may use the reserve, all but the last connection.
const oldest = Math.min(...watch.queue.map((w) => w.since))
if (now - Math.max(watch.moved, oldest) >= RESERVE_ESCAPE_MS && open() < size - 1) {
admit(watch, watch.queue[watch.queue.length - 1])
watch.moved = now
}
if (watch.queue.length && !watch.timer) {
const wait = Math.max(1, watch.queue[0].since + RESERVE_ESCAPE_MS - now)
const wait = Math.max(1, Math.max(watch.moved, oldest) + RESERVE_ESCAPE_MS - now)
watch.timer = setTimeout(() => {
watch.timer = undefined
drain(payload, watch)
@@ -82,17 +129,19 @@ function drain(payload: BasePayload, watch: Watch): void {
}
}
function acquire(payload: BasePayload, watch: Watch): Promise<void> | undefined {
function acquire(payload: BasePayload, watch: Watch, depth: number): Promise<void> | undefined {
let resolve = () => {}
const done = new Promise<void>((r) => (resolve = r))
const waiter: Waiter = { resolve: () => resolve(), since: Date.now() }
const waiter: Waiter = { depth, resolve: () => resolve(), since: Date.now() }
watch.queue.push(waiter)
drain(payload, watch)
return watch.queue.includes(waiter) ? done : undefined
}
function release(payload: BasePayload, watch: Watch): void {
watch.active = Math.max(0, watch.active - 1)
function release(payload: BasePayload, watch: Watch, slot = true): void {
if (slot) {watch.active = Math.max(0, watch.active - 1)}
else {watch.nested = Math.max(0, watch.nested - 1)}
watch.moved = Date.now()
drain(payload, watch)
}
@@ -100,7 +149,7 @@ function finish(payload: BasePayload, watch: Watch, id: TransactionID): Entry |
const entry = watch.open.get(id)
if (!entry) {return undefined}
watch.open.delete(id)
release(payload, watch)
release(payload, watch, entry.slot)
return entry
}
@@ -119,29 +168,39 @@ export function watchTransactions(payload: BasePayload, reserve: false | number
drain(payload, db[WATCH])
return db[WATCH]
}
const watch: Watch = { active: 0, open: new Map(), queue: [], reserve: wanted }
const watch: Watch = { active: 0, moved: Date.now(), nested: 0, open: new Map(), queue: [], reserve: wanted }
db[WATCH] = watch
const begin = db.beginTransaction
const commit = db.commitTransaction
const rollback = db.rollbackTransaction
db.beginTransaction = async function (this: unknown, ...args: unknown[]) {
const waiting = acquire(payload, watch)
if (waiting) {await waiting}
let id: null | TransactionID
try {
id = await begin.apply(this, args)
} catch (err) {
release(payload, watch)
throw err
}
if (id === null || id === undefined) {
release(payload, watch)
// Not `async`: the mark must be set in the caller's own (synchronous) part, so that what the caller does
// next — its hooks, a Local API call without `req` — carries it.
db.beginTransaction = function (this: unknown, ...args: unknown[]) {
const outer = current.getStore()
const outerEntry = outer?.id !== undefined ? watch.open.get(outer.id) : undefined
const depth = outerEntry ? outerEntry.depth + 1 : 0
const mark: { depth: number; id?: TransactionID } = { depth }
current.enterWith(mark)
return (async () => {
const waiting = acquire(payload, watch, depth)
if (waiting) {await waiting}
let id: null | TransactionID
try {
id = await begin.apply(this, args)
} catch (err) {
release(payload, watch, depth === 0)
throw err
}
if (id === null || id === undefined) {
release(payload, watch, depth === 0)
return id
}
mark.id = id
watch.open.set(id, { after: [], depth, slot: depth === 0 })
return id
}
watch.open.set(id, { after: [] })
return id
})()
}
db.commitTransaction = async function (this: unknown, incoming) {
@@ -221,7 +280,7 @@ export function transactionsBusy(payload: BasePayload): boolean {
}
/** For tests and diagnostics: open transactions, waiting ones and the reserve in force. */
export function transactionWatchState(payload: BasePayload): { active: number; reserve: null | number; waiting: number } | null {
export function transactionWatchState(payload: BasePayload): { active: number; nested: number; reserve: null | number; waiting: number } | null {
const watch = dbOf(payload)[WATCH]
return watch ? { active: watch.active, reserve: watch.reserve, waiting: watch.queue.length } : null
return watch ? { active: watch.active, nested: watch.nested, reserve: watch.reserve, waiting: watch.queue.length } : null
}