Postgres: many requests at once no longer stop the site

Each Payload transaction holds a pool connection; code inside it that runs
without its req needs a second one (Payload's own forgotPassword, the mail
adapter's settings read and status write, payload.kv). With the default pool
of 10, ten form submissions or ten "forgot password" requests at once held
every connection and waited for good.

- connectionReserve (default on): at most pool size − reserve transactions
  open at once; a waiter older than a second may use all but the last
  connection. Building blocks in modules/database/transactions.ts.
- Form e-mails go out right after the submission's transaction commits, in
  the same request (forms.emailsInTransaction: true = the old way).
- recordIntegrationStatus merges identical writes and does not hold its
  caller while the pool is busy.
- SMTP time-outs: 10 s connect, 30 s greeting, 60 s silence (smtp.timeouts).

Tests on Postgres 17: 30 submissions, 30 forgot-password, and both against
an SMTP server that never answers, finish while a page answers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 00:33:07 +01:00
co-authored by Claude Opus 5.5
parent acfcf72c03
commit 32bb542e8e
25 changed files with 916 additions and 23 deletions
+5 -2
View File
@@ -206,6 +206,8 @@ export {
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js'
// Postgres: connections kept free of transactions, work run after a commit (docs/deployment.md "Postgres: the connection pool").
export { afterCommit, defaultConnectionReserve, inWatchedTransaction, poolSize, RESERVE_ESCAPE_MS, reserveConnections, transactionsBusy, transactionWatchState, watchTransactions } from './modules/database/transactions.js'
// Files on panel forms (forms.attachments): checked, e-mailed, never stored.
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
@@ -215,8 +217,8 @@ export type { MailAdapterArgs, MailTransport } from './modules/email/mailAdapter
// Imported straight from the file, NOT from ./modules/email/index.js — that
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
export { panelSmtpAdapter, SMTP_TIMEOUT_DEFAULTS } from './modules/email/panelSmtpAdapter.js'
export type { PanelSmtpAdapterArgs, SmtpTimeouts } from './modules/email/panelSmtpAdapter.js'
// The Intecion Notifications Webservice (docs/email.md): the transport of a site with no SMTP server.
// Every piece is exported, so a project can use the transport alone, enrol from a script, mark its own
// mail, build its own panel, or test against the fake service.
@@ -280,6 +282,7 @@ export type { MailPanelState } from './modules/email/relay/panel.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, checkDatabaseName, databaseNameFromUri, databaseNamesFor, iaplEnvRules, ipalEnvRules, legacyEnvName, readEnv } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IaplEnvFeatures, IpalEnvFeatures } from './modules/env/index.js'
export { sendAfterCommit, sendFormEmails } from './modules/forms/afterCommit.js'
export type { FormAttachmentsOption, FormFileScanInput, FormFileScanResult, FormSubmitEndpointOptions } from './modules/forms/attachments/config.js'
export { buildFormMailKindHook } from './modules/forms/attachments/delivery.js'
export { buildFileBlock, fileBlock } from './modules/forms/attachments/fileBlock.js'
+227
View File
@@ -0,0 +1,227 @@
import type { BasePayload, PayloadRequest } from 'payload'
/**
* Transactions and the Postgres pool.
*
* Payload holds one pool connection for the whole of a transaction. Code inside it that reads or writes
* WITHOUT the transaction's `req` needs a second connection: Payload's own "forgot password" (it reserves
* the request interval outside the transaction), an e-mail adapter reading its settings, the key-value
* store, a project's hook that forgot `req`. With the default pool of 10, ten such requests at the same
* moment hold all ten connections and each waits for an eleventh: the whole site stops, for good.
*
* `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.
*
* `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 Watch = {
active: number
/** Open transactions begun through this watch, by id. */
open: Map<TransactionID, Entry>
queue: Waiter[]
/** Connections kept free; `null` = no limit (not Postgres, or switched off). */
reserve: null | number
timer?: ReturnType<typeof setTimeout>
}
type WatchedDb = {
beginTransaction?: (...args: unknown[]) => Promise<null | TransactionID>
commitTransaction?: (id: Promise<TransactionID> | TransactionID) => Promise<void>
pool?: { options?: { max?: number } }
rollbackTransaction?: (id: Promise<TransactionID> | TransactionID) => Promise<void>
[WATCH]?: Watch
}
const WATCH = Symbol.for('iapl.transactionWatch')
/** After this long in the queue a transaction may use the reserve (all but one connection). */
export const RESERVE_ESCAPE_MS = 1000
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. */
export function poolSize(payload: BasePayload): null | number {
const pool = dbOf(payload).pool
if (!pool) {return null}
const max = pool.options?.max
return typeof max === 'number' && max > 0 ? max : 10
}
/** Connections kept free by default: a fifth of the pool, at least 2 (1 in a pool of fewer than 4). */
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 size = poolSize(payload) ?? Infinity
const limit = watch.reserve === null ? Infinity : Math.max(1, size - watch.reserve)
const escapeLimit = Math.max(limit, size - 1)
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()
}
if (watch.queue.length && !watch.timer) {
const wait = Math.max(1, watch.queue[0].since + RESERVE_ESCAPE_MS - now)
watch.timer = setTimeout(() => {
watch.timer = undefined
drain(payload, watch)
}, wait)
watch.timer.unref?.()
}
}
function acquire(payload: BasePayload, watch: Watch): Promise<void> | undefined {
let resolve = () => {}
const done = new Promise<void>((r) => (resolve = r))
const waiter: Waiter = { 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)
drain(payload, watch)
}
function finish(payload: BasePayload, watch: Watch, id: TransactionID): Entry | undefined {
const entry = watch.open.get(id)
if (!entry) {return undefined}
watch.open.delete(id)
release(payload, watch)
return entry
}
/**
* Wraps the adapter's begin / commit / rollback once (idempotent). `reserve`: connections kept free of
* transactions (Postgres only), `false` = no limit; the watch for `afterCommit` is installed either way.
* Returns the watch, or null when the adapter has no transactions to watch.
*/
export function watchTransactions(payload: BasePayload, reserve: false | number = defaultConnectionReserve(poolSize(payload) ?? 10)): null | Watch {
const db = dbOf(payload)
if (typeof db.beginTransaction !== 'function' || typeof db.commitTransaction !== 'function' || typeof db.rollbackTransaction !== 'function') {return null}
const size = poolSize(payload)
const wanted = reserve === false || size === null ? null : Number.isFinite(reserve) ? Math.max(0, Math.floor(reserve)) : defaultConnectionReserve(size)
if (db[WATCH]) {
db[WATCH].reserve = wanted
drain(payload, db[WATCH])
return db[WATCH]
}
const watch: Watch = { active: 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)
return id
}
watch.open.set(id, { after: [] })
return id
}
db.commitTransaction = async function (this: unknown, incoming) {
const id = incoming instanceof Promise ? await incoming : incoming
try {
await commit.call(this, id)
} catch (err) {
finish(payload, watch, id)
throw err
}
const entry = finish(payload, watch, id)
for (const fn of entry?.after ?? []) {
try {
await fn()
} catch (err) {
payload.logger.error({ err, msg: '[iapl] A step that runs after a transaction commits failed.' })
}
}
}
db.rollbackTransaction = async function (this: unknown, incoming) {
const id = incoming instanceof Promise ? await incoming : incoming
try {
await rollback.call(this, id)
} finally {
finish(payload, watch, id)
}
}
return watch
}
/**
* Keeps `reserve` pool connections free of transactions (Postgres; does nothing on an adapter without a
* pool). `iapl()` calls it at start; a project that uses only the building blocks calls it in its own
* `onInit`:
* onInit: (payload) => { reserveConnections(payload) }
* `reserve`: a number, or the default (a fifth of the pool, at least 2). Calling it again changes the number.
*/
export function reserveConnections(payload: BasePayload, reserve?: number): void {
watchTransactions(payload, reserve ?? defaultConnectionReserve(poolSize(payload) ?? 10))
}
/**
* Runs `fn` right after the transaction of `req` commits — still inside the operation that began it, so
* that operation returns only once `fn` is done — and drops it when the transaction is rolled back.
* Returns `false` when there is no transaction to wait for (none open, an adapter without transactions,
* one this watch did not see begin): then nothing is scheduled and the caller does the work at once.
* A caller's OUTER transaction counts: `fn` runs when that one commits.
* An error thrown by `fn` is logged; it does not undo the commit.
*/
export function afterCommit(req: Pick<PayloadRequest, 'payload' | 'transactionID'>, fn: () => Promise<void> | void): boolean {
const id = req.transactionID
if (id === undefined || id === null || id instanceof Promise) {return false}
const entry = dbOf(req.payload)[WATCH]?.open.get(id)
if (!entry) {return false}
entry.after.push(fn)
return true
}
/** True when `req` is inside a transaction that `afterCommit` can wait for. */
export function inWatchedTransaction(req: Pick<PayloadRequest, 'payload' | 'transactionID'>): boolean {
const id = req.transactionID
return id !== undefined && id !== null && !(id instanceof Promise) && Boolean(dbOf(req.payload)[WATCH]?.open.has(id))
}
/**
* True while every place for a transaction is taken or a transaction waits for one (Postgres with the
* reserve on). Work that would open a transaction of its own and is not needed for the caller's answer —
* the panel status of an integration — runs in the background then instead of holding its caller, which
* may itself be inside a transaction.
*/
export function transactionsBusy(payload: BasePayload): boolean {
const watch = dbOf(payload)[WATCH]
if (!watch || watch.reserve === null) {return false}
const size = poolSize(payload) ?? Infinity
return watch.queue.length > 0 || watch.active >= Math.max(1, size - watch.reserve)
}
/** 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 {
const watch = dbOf(payload)[WATCH]
return watch ? { active: watch.active, reserve: watch.reserve, waiting: watch.queue.length } : null
}
+16 -1
View File
@@ -20,8 +20,19 @@ export type PanelSmtpAdapterArgs = {
*/
fallbackFromAddress?: string
fallbackFromName?: string
/**
* How long a send waits for the SMTP server, in milliseconds: `connectionMs` to connect (default 10 000),
* `greetingMs` for its greeting (default 30 000), `socketMs` of silence during the dialogue (default 60 000).
* A send that runs inside a database transaction (Payload's "forgot password") holds a connection that long.
*/
timeouts?: SmtpTimeouts
}
export type SmtpTimeouts = { connectionMs?: number; greetingMs?: number; socketMs?: number }
/** nodemailer's own defaults are 2 minutes to connect and 10 minutes of silence. */
export const SMTP_TIMEOUT_DEFAULTS: Required<SmtpTimeouts> = { connectionMs: 10_000, greetingMs: 30_000, socketMs: 60_000 }
/**
* Payload email adapter backed by the SMTP settings in the SiteIntegrations
* global.
@@ -83,11 +94,15 @@ export const panelSmtpAdapter =
const { default: nodemailer } = await import('nodemailer')
const timeouts = { ...SMTP_TIMEOUT_DEFAULTS, ...args.timeouts }
const transporter = nodemailer.createTransport({
auth: { pass, user },
connectionTimeout: timeouts.connectionMs,
greetingTimeout: timeouts.greetingMs,
host,
port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
socketTimeout: timeouts.socketMs,
})
try {
+48
View File
@@ -0,0 +1,48 @@
import type { BeforeEmail } from '@payloadcms/plugin-form-builder/types'
import type { PayloadRequest } from 'payload'
import { isolateObjectProperty } from 'payload'
import { afterCommit } from '../database/transactions.js'
type Emails = Parameters<BeforeEmail>[0]
type HookArgs = Parameters<BeforeEmail>[1]
/** The same request outside its (committed) transaction: reads in the hooks take a connection of their own. */
function outsideTransaction(req: PayloadRequest): PayloadRequest {
const own = isolateObjectProperty(req, 'transactionID')
own.transactionID = undefined
return own
}
/** form-builder's own loop: every e-mail through the project's adapter, a failure logged, never thrown. */
export async function sendFormEmails(req: PayloadRequest, emails: Emails): Promise<void> {
const { payload } = req
await Promise.all(
emails.map(async (email) => {
try {
await payload.sendEmail(email as never)
} catch (err) {
payload.logger.error({ err, msg: `Error while sending email to address: ${String(email.to)}. Email not sent.` })
}
}),
)
}
/**
* A form-builder `beforeEmail` that composes the e-mails at once (`prepare`: inside the submission's
* transaction, with its `req`) and hands them to the mail server right after that transaction commits
* (`deliver` — the file delivery — then the send). form-builder gets an empty list back and sends
* nothing itself. Inside a caller's outer transaction they go out when that one commits; with no
* transaction to wait for (MongoDB without a replica set, SQLite) everything happens at once, as before.
*/
export function sendAfterCommit(prepare: BeforeEmail, deliver: BeforeEmail): BeforeEmail {
return async (emails, args: HookArgs) => {
const prepared = await prepare(emails, args)
const later = afterCommit(args.req, async () => {
const req = outsideTransaction(args.req)
await sendFormEmails(req, await deliver(prepared, { ...args, req }))
})
return later ? [] : deliver(prepared, args)
}
}
+7 -3
View File
@@ -7,6 +7,7 @@ import type { AdminText } from '../admin-i18n/define.js'
import type { FormsOption } from './types.js'
import { userMeetsRole } from '../access/predicates.js'
import { sendAfterCommit } from './afterCommit.js'
import { resolveFormAttachments } from './attachments/config.js'
import { buildFileDeliveryHook, buildFileNoticeHook, buildFormMailKindHook } from './attachments/delivery.js'
import { buildFormSubmitEndpoint } from './attachments/endpoint.js'
@@ -221,13 +222,16 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
// Every e-mail of a form says what it is (notification to the addresses written in the panel, or
// confirmation to an address the visitor typed): the Intecion mail service limits the two differently.
const markKinds = buildFormMailKindHook({ formsSlug })
const beforeEmail: BeforeEmail = async (emails, args) => {
const prepare: BeforeEmail = async (emails, args) => {
const noticed = fileNotice ? await fileNotice(emails, args) : emails
const laidOut = layout ? await layout(noticed, args) : noticed
const changed = forms.beforeEmail ? await Promise.resolve(forms.beforeEmail(laidOut, args)) : laidOut
const marked = await markKinds(changed, args)
return fileDelivery ? fileDelivery(marked, args) : marked
return markKinds(changed, args)
}
const deliver: BeforeEmail = (emails, args) => (fileDelivery ? fileDelivery(emails, args) : emails)
// Composed inside the transaction (the hooks read the form with its `req`); sent after it commits
// (forms.emailsInTransaction), so a slow mail server holds no database connection.
const beforeEmail: BeforeEmail = forms.emailsInTransaction ? async (emails, args) => deliver(await prepare(emails, args), args) : sendAfterCommit(prepare, deliver)
const fileBlockOption = forms.fields?.file
const formHooks = forms.formOverrides?.hooks
const builder = formBuilderPlugin({
+10
View File
@@ -53,6 +53,16 @@ export type FormsOption = {
* with the logo, accent colour and footer from Site Settings → Emails. Default false.
*/
emailLayout?: boolean
/**
* When a form's e-mails go out. Default (`false`): right AFTER the submission is saved — its database
* transaction has committed and given its connection back — still within the same request, so the
* visitor's answer (and a file that could not be sent) is reported as before. A mail server that is
* slow or hangs then holds no database connection, and nothing is sent for a submission that was not
* saved. A submission saved without its e-mail (the mail server refused it) stays stored, as it always
* did. `true` = inside the transaction, as before 1.17.0. Databases without transactions (MongoDB
* without a replica set, SQLite by default) send at once either way. docs/forms.md "When e-mails go out".
*/
emailsInTransaction?: boolean
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
checkbox?: boolean
+38 -10
View File
@@ -3,6 +3,8 @@ import type { BasePayload, Field } from 'payload'
import type { AdminTextKey } from '../admin-i18n/texts/index.js'
import type { IntegrationLabel } from './texts.js'
import { transactionsBusy } from '../database/transactions.js'
/**
* Health of a third-party integration (Turnstile today, SMTP/Graph later),
* stored on the SiteIntegrations global so the panel can show it:
@@ -88,7 +90,8 @@ export function buildIntegrationStatusBanner(
/**
* Persist a status change. Never throws — a status write must not break the
* request that triggered it.
* request that triggered it. The same change already being written is not
* written twice; under database load the write is not waited for.
*/
export async function recordIntegrationStatus(
payload: BasePayload,
@@ -106,6 +109,15 @@ export async function recordIntegrationStatus(
if (!changed && !stale) {return}
if (next.state === 'ok' && !previous?.state) {return}
// The same change already on its way (many sends failing at once): wait for that write, do not repeat it.
const key = `${field}|${next.state}|${next.code ?? ''}`
const pending = inFlight(payload)
// Under load (every transaction place taken, src/modules/database/transactions.ts) the caller may be
// inside a transaction itself: the write — a transaction of its own — is not waited for then.
const busy = transactionsBusy(payload)
const running = pending.get(key)
if (running) {return busy ? undefined : running}
const status: IntegrationStatus = {
checkedAt: now.toISOString(),
code: next.code ?? null,
@@ -113,14 +125,30 @@ export async function recordIntegrationStatus(
since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()),
state: next.state,
}
try {
await payload.updateGlobal({
slug: SITE_INTEGRATIONS as never,
context: { ipalIntegrationStatus: true },
data: { [field]: status } as never,
depth: 0,
})
} catch (err) {
console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err)
const write = (async () => {
try {
await payload.updateGlobal({
slug: SITE_INTEGRATIONS as never,
context: { ipalIntegrationStatus: true },
data: { [field]: status } as never,
depth: 0,
})
} catch (err) {
console.warn(`[iapl] could not record ${field}:`, err instanceof Error ? err.message : err)
} finally {
pending.delete(key)
}
})()
pending.set(key, write)
return busy ? undefined : write
}
const writes = new WeakMap<object, Map<string, Promise<void>>>()
function inFlight(payload: BasePayload): Map<string, Promise<void>> {
let map = writes.get(payload)
if (!map) {
map = new Map()
writes.set(payload, map)
}
return map
}
+4
View File
@@ -30,6 +30,7 @@ import { buildCookieScanEndpoints } from './modules/consent/scanner/endpoint.js'
import { mergeCookieScanLabels } from './modules/consent/scanner/labels.js'
import { buildConstructionFields } from './modules/construction/fields.js'
import { buildArchiveFields } from './modules/content/index.js'
import { defaultConnectionReserve, poolSize, watchTransactions } from './modules/database/transactions.js'
import { buildDoctorEndpoint } from './modules/doctor/status.js'
import { GRAPH_DEPRECATION_NOTICE, graphAvailable } from './modules/email/mailAdapter.js'
import { withAccountMailMark } from './modules/email/relay/accountMail.js'
@@ -939,6 +940,9 @@ export const iapl = (options: IaplOptions): Plugin => {
)
}
adoptConfig(payload)
// Postgres: keep a few pool connections free of transactions (connectionReserve), and watch commits so
// that form e-mails go out after the submission's transaction (forms.emailsInTransaction).
watchTransactions(payload, options.connectionReserve === false ? false : (options.connectionReserve ?? defaultConnectionReserve(poolSize(payload) ?? 10)))
// Microsoft Graph is deprecated (removed in 2.0): one warning per start while its variables are set.
if (graphAvailable() && options.mail?.graphDeprecationWarning !== false) {payload.logger.warn(GRAPH_DEPRECATION_NOTICE)}
// Payload's dev reload swaps `payload.config` and runs no onInit: adopt the new config at once.
+12
View File
@@ -75,6 +75,18 @@ export type IaplOptions = {
*/
agency?: AgencyOption | false
/**
* Postgres: pool connections kept free of transactions. Payload holds a connection for the whole of a
* transaction, and code inside it that runs without the transaction's `req` (Payload's own "forgot
* password", an e-mail adapter reading its settings, a hook that forgot `req`) needs a second one: with
* the default pool of 10, ten such requests at once used to stop the whole site. With the reserve, at
* most `pool size − reserve` transactions are open at once and the next one waits for a place.
* Default: a fifth of the pool, at least 2 (1 in a pool of fewer than 4). A number sets it; `false`
* switches it off (as before 1.17.0). Other adapters: no effect. Building block: `reserveConnections`.
* docs/deployment.md "Postgres: the connection pool".
*/
connectionReserve?: false | number
/** Internationalization — locales, default locale, fallback behavior */
/**
* Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records`