Merge claude/postgres-mail-deadlock: Postgres keeps connections free of transactions; form and account mail go out after the commit

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 01:38:31 +01:00
co-authored by Claude Opus 5.5
30 changed files with 1431 additions and 27 deletions
+33
View File
@@ -132,6 +132,39 @@ once there are more than 20.
Not a switch for a live site: it would start visitors' histories and the running 2FA counts again.
- `EnvRule.aliases` for `assertEnv`: older names of a variable, read when the main one is missing.
### Fixed — Postgres: many requests at once no longer stop the site (draft; release decided by the owner)
- **Ten or more form submissions at the same moment, or ten "forgot password" requests, stopped the whole site on
Postgres** — every request, also pages that only read, waited for good (older than 1.17.0; MongoDB sites were not
affected). Each transaction holds a pool connection, and code inside it that runs without its `req` (Payload's own
"forgot password", the e-mail adapter reading Site integrations and writing the send status, `payload.kv`) needs a
second one; the default pool has 10. Measured on Postgres 17: 12 submissions or 12 resets at once never finished;
now 30 of each, also against an SMTP server that never answers, finish while an ordinary request answers at once.
- **`connectionReserve`** (new plugin option, default on): a fifth of the pool, at least 2, stays free of
transactions; at most `pool size − reserve` transactions are open at once and the next one waits. A transaction
begun inside another one (a project hook that calls the Local API without `req`) takes no place and goes at once,
but never takes the last connection — 9, 12 and 30 such submissions at once finish (before: 12 stopped the site).
`false` = as before. Building blocks `reserveConnections`, `watchTransactions`, `afterCommit`,
`inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, `poolSize`, `defaultConnectionReserve`,
`RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a, with the measured table).
- **Payload's "forgot password" and "verify your e-mail" go out after their transaction commits** when sent through
`mailAdapter()` (`mail.accountMailAfterCommit`, default on; same request, nothing sent on a rollback). The message is
matched to its request by its token (Payload's `generateEmailSubject` is wrapped; a project's own one is kept). With the mail
service hanging, 30 resets and 30 submissions at once finish in about one send budget (11 s) instead of 43.5 s.
Building blocks `withAccountMailAfterCommit`, `sendAccountMailAfterCommit`, `holdAccountMail`,
`releaseAccountMail`.
- **Form e-mails go out after the submission's transaction commits** — same request, same answer to the visitor
(a file that could not be sent is still reported). A submission rolled back by a later hook now sends nothing; a
send that fails after the commit leaves the submission stored (as a failed e-mail always did). Sites without
transactions (MongoDB without a replica set, SQLite) send at once, as before. The old way:
`forms: { emailsInTransaction: true }`. Building blocks `sendAfterCommit`, `sendFormEmails`
([forms.md](./forms.md) "When e-mails go out").
- **The panel's send status** (`recordIntegrationStatus`): many sends failing at once write it once; while the pool
is busy the write is not waited for.
- **SMTP time-outs**: 10 s to connect (was nodemailer's 2 min), 30 s for the greeting, 60 s of silence (was 10 min);
`mailAdapter({ smtp: { timeouts } })` / `panelSmtpAdapter({ timeouts })`, `SMTP_TIMEOUT_DEFAULTS`, `SmtpTimeouts`.
- Not covered: an e-mail adapter of your own (not `mailAdapter()`) still gets Payload's account mail inside the
transaction unless it calls `sendAccountMailAfterCommit` first.
### Deprecated
- **Microsoft Graph as an e-mail transport** — `graphAdapter`, `GraphAdapterArgs`, `mailAdapter({ graph })`,
`iaplEnvRules({ emailGraph })` and the four `GRAPH_*` variables. Nothing new is built on it; it gets fixes only and
+4
View File
@@ -1246,6 +1246,10 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
| Account e-mails through the mail service: at most 5 to one address and 10 asked for by one visitor an hour | `mail: { relay: { accountMail: false } }` | `accountMail: { perAddress, perVisitor, windowMinutes }` |
| Every message says what it is (form notification, form confirmation, account, test, system) | — (other transports ignore the mark) | `withMailKind`, `runWithMailKind`, `expectMailTo`, `mail.relay.kind`, `buildFormMailKindHook` |
| Microsoft Graph as transport: deprecated, one warning per start, removed in 2.0 | `mail: { graphDeprecationWarning: false }` (the warning only) | move off it: email.md "Moving off Microsoft Graph" |
| Postgres: a fifth of the pool (at least 2) stays free of transactions — at most `pool size − reserve` open at once, the next waits; a transaction begun inside another one (a hook without `req`) takes no place and goes at once, but never the last connection. Without it ten form submissions or "forgot password" requests at once stopped the site | `connectionReserve: false` | `connectionReserve: <number>`; `reserveConnections(payload, n)` in your own `onInit` (without `iapl()`); `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) |
| Payload's "forgot password" / "verify your e-mail" through `mailAdapter()` go out right after their transaction commits (same request); a rolled-back operation sends nothing | `mail: { accountMailAfterCommit: false }` | your own adapter: `sendAccountMailAfterCommit(message, send)`; `withAccountMailAfterCommit(collection)`, `holdAccountMail`, `releaseAccountMail` (email.md "Payload system mail") |
| Form e-mails go out right after the submission's transaction commits (same request, same answer); a rolled-back submission sends nothing; a send that fails after the commit leaves the submission stored. No transactions (MongoDB without a replica set, SQLite): at once, as before | `forms: { emailsInTransaction: true }` | `sendAfterCommit(prepare, deliver)`, `sendFormEmails(req, emails)`, `afterCommit(req, fn)` (forms.md "When e-mails go out") |
| SMTP time-outs: 10 s to connect, 30 s greeting, 60 s silence | — | `mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })`, `panelSmtpAdapter({ timeouts })`; `SMTP_TIMEOUT_DEFAULTS`, type `SmtpTimeouts` (email.md "SMTP") |
### 7.2 E-mail — the mail service (default), SMTP (on request), Graph (deprecated)
+4
View File
@@ -121,6 +121,10 @@ through this procedure. Ask only when you are missing something you cannot get y
| replies to the site's mail are lost | "Sender address" is empty: the service's own address has no mailbox | fill it in (doctor: `mail-reply-address`) |
| the site enrols again and again (`reverify` in the log) | requests leave from many changing addresses (serverless, a pool of egress addresses) | Intecion raises the site's limit of server addresses, or SMTP |
| start log: "Microsoft Graph as the e-mail transport is deprecated" | `GRAPH_*` is set | email.md "Moving off Microsoft Graph"; silence only: `mail: { graphDeprecationWarning: false }` |
| Postgres: under load (many form submissions or "forgot password" requests at once) the whole site stops answering, also pages that only read; `pg_stat_activity` shows the pool's connections "idle in transaction" | each transaction holds a connection and waits for a second one (code inside it without `req`); before 1.17.0, or with `connectionReserve: false` | upgrade / remove `connectionReserve: false`; without `iapl()` call `reserveConnections(payload)` in `onInit`; your own hooks: pass `req` to every Local API call; `transactionWatchState(payload)` shows `{ active, waiting, reserve }` (deployment.md §4.3a) |
| Postgres: requests are slow while a mail server hangs (logins and saves wait behind "forgot password") | the account mail is sent inside its transaction: `mail: { accountMailAfterCommit: false }`, `forms.emailsInTransaction: true`, or an e-mail adapter of your own that does not call `sendAccountMailAfterCommit` | remove the option / call it in your adapter; fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })` |
| Postgres: a project hook writes without `req` and the log row stays when its submission is rolled back | a Local API call without `req` is a transaction of its own (it no longer blocks the pool, but it is not rolled back with its caller) | pass `req` to every Local API call in a hook |
| a submission is stored but its e-mail never arrived, nothing in the panel status | the transaction was rolled back after the e-mail was composed (then nothing is stored either), or the process ended right after the commit | server log `[iapl] A step that runs after a transaction commits failed` / form-builder's "Error while sending email"; forms.md "When e-mails go out" |
| old email sender | mail client cache | check the raw headers |
| form: `unknown_fields` | field outside the definition (honeypot not removed) | `iapl-form` → actions.ts |
| an account logs in to `/admin` and sees "Unauthorized" (its API calls still work) | `accounts.panelRole`: the panel opens for `editor` and above; the account has only `user`, or no role | give it `editor` (an admin edits the account), or `accounts: { panelRole: 'user' }`; nobody can get in: a script with the Local API sets `roles: ['admin']`, or `accounts: { panelRole: false }` + redeploy |
+6
View File
@@ -120,6 +120,12 @@ Tell the client plainly: **there is no antivirus scan** (the e-mail says so), th
files is best-effort, and when the e-mail cannot be sent the file is gone — the visitor sees "We could not send the
file …" at the File field, staff get a notice without the file, and the submission shows **File delivery: Not sent**.
### E-mails go out after the save (1.17.0)
A form's e-mails are composed inside the submission's transaction and sent right after it commits, in the same
request (`submitForm` answers as before). A submission rolled back by a hook of yours sends nothing. Keep the old way
only on the owner's word: `forms: { emailsInTransaction: true }` (forms.md "When e-mails go out"). Check on Postgres:
a submission arrives; your own `afterChange` hooks on form-submissions pass `req` to every Local API call.
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
```tsx
+6
View File
@@ -584,6 +584,12 @@ PROGRAMISTA §6, item 73; email.md; AGENT.md §7.2) — nothing to run; read whi
service returns `{ sent, transport: 'relay', … }`; `sent: false` with `confirmed: false` means "may have been sent".
5. Your own account mail (invitations): mark it — `withMailKind(message, 'account')`. Form mail and Payload's
"forgot password" are marked by the plugin.
6. **Postgres sites** (nothing to run): at most `pool size − reserve` transactions are open at once (default reserve 2 of
10; `connectionReserve`; a transaction begun inside another one takes no place), form e-mails and Payload's
"forgot password" / "verify your e-mail" go out right after their transaction commits (`forms.emailsInTransaction`,
`mail.accountMailAfterCommit`),
SMTP gives up sooner (10 s to connect, 60 s of silence; `smtp.timeouts`). A site that set its own `pool.max`: the
reserve follows it. MongoDB and SQLite sites: no change. deployment.md §4.3a, forms.md "When e-mails go out".
**Check:** `pnpm exec iapl-doctor --deep --url <site>` → no `mail-transport` / `mail-relay-state` / `mail-reply-address` /
`mail-relay-route` finding (or only `mail-graph-deprecated` on a Graph site); Site integrations → E-mail sending →
**Send test e-mail** names the transport you expect; a form submission arrives. **The service has to be live for a site
+57
View File
@@ -356,6 +356,63 @@ with `NODE_ENV=production` — also during `next build` when the build reaches t
schema: add columns/tables first, drop or rename in a later release (`iapl-migrate-fields` skill). Take a
**Backup now** (§4.6) before a large migration.
### 4.3a Postgres: the connection pool
Payload holds one pool connection for the whole of a transaction (a form submission, "forgot password", a save in
the panel). Code inside it that runs **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,
`payload.kv`, a project hook that calls the Local API without `req`. With the default pool of 10, **ten such requests
at the same moment held all ten connections and each waited for an eleventh — the whole site stopped, for good**
(measured on 1.16.8 and the 1.17.0 branch: 12 form submissions or 12 "forgot password" requests at once, an ordinary
page got no answer).
Since 1.17.0 the plugin keeps a few connections free of transactions (`connectionReserve`):
- at most `pool size − reserve` transactions are open at once; the next one waits for a place — its request is
slower, nothing stops. Default reserve: a fifth of the pool, at least 2 (1 in a pool of fewer than 4): with the
default pool of 10, eight transactions at once and two connections for everything else;
- 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 is open — does not queue: it takes no place, because its caller cannot
finish without it. It may use the reserve but the last connection (a second level inside it that one too), so one
connection stays free for the queries outside transactions. "Inside" is told by a mark the plugin sets when a
transaction begins (`AsyncLocalStorage`); in case the mark is lost on the way, a queue that has not moved for a
second (`RESERVE_ESCAPE_MS`) lets its newest waiter use the reserve, all but the last connection;
- form e-mails go out **after** the submission's transaction commits ([forms.md](./forms.md) "When e-mails go out"),
and so do Payload's own "forgot password" and "verify your e-mail" sent through `mailAdapter()`
(`mail.accountMailAfterCommit`, default on): a slow or hanging mail server holds no connection and no place; the
request still ends when the mail is out. A rolled-back operation sends nothing.
Measured on Postgres 17, default pool of 10 (`test/transactionPool*.test.ts`):
| At the same moment | 1.16.8 / `connectionReserve: false` | 1.17.0 |
|---|---|---|
| 12 or 30 form submissions, or 12 or 30 "forgot password" | site stops for good, pages too | all finish, a page answers in milliseconds |
| 9 / 12 / 30 submissions whose hook writes without `req` | 9 finish (363 ms); 12 and 30 stop the site | all finish (under 2 s) |
| 30 "forgot password" + 30 submissions, the mail service hanging (10 s budget a send) | site stops for good | all finish in about 11 s (one budget); with the reset mail inside its transaction (`accountMailAfterCommit: false`) the last waited 43.5 s |
| the same with an SMTP server that never answers (2 s time-outs in the test) | site stops for good | all finish in a few seconds |
```ts
iapl({ connectionReserve: 3 }) // keep three connections free
iapl({ connectionReserve: false }) // no limit, as before 1.17.0 (not recommended)
iapl({ mail: { accountMailAfterCommit: false } }) // "forgot password" mail inside its transaction, as before
```
MongoDB, SQLite and other adapters without a pool: no effect. A larger pool (`postgresAdapter({ pool: { max: 20 } })`)
moves the reserve with it; the Postgres server's own `max_connections` must allow every instance's pool.
Without `iapl()` (building blocks only): `onInit: (payload) => { reserveConnections(payload) }`.
Building blocks: `reserveConnections`, `watchTransactions`, `afterCommit` (run work right after a transaction
commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route:
`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`; for account mail
`withAccountMailAfterCommit(collection)` (what the plugin does to every auth collection: wraps its
`generateEmailSubject`, which Payload calls with the request and the token right before the send),
`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMail`,
`releaseAccountMail`. Still true: a hook that writes without `req` is a transaction of its own — it is not rolled
back with its caller's. Pass `req`.
**Check** (staging, Postgres): send 30 submissions of a form at once (or 30 "forgot password" requests for different
accounts) while loading a page — the page answers at once, every request finishes. `transactionWatchState(payload)`
shows `{ active, nested, waiting, reserve }`.
### 4.4 Health check and rolling updates
Coolify → the application → **Health Checks**: HTTP, path `/api/health`, port 3000, a start period long enough
+20 -4
View File
@@ -455,6 +455,12 @@ and password switches the site to the client's server.
- Missing SMTP config or a send error → the adapter **does not throw**, it returns `{ sent: false, error }` and logs.
- Port 465 → implicit TLS, others → STARTTLS.
- The adapter reads the config on every send, so changing the mailbox in the panel works without a restart.
- **Time-outs** (since 1.17.0): 10 s to connect, 30 s for the server's greeting, 60 s of silence during the
dialogue (`SMTP_TIMEOUT_DEFAULTS`; nodemailer's own were 2 min and 10 min). A send inside a database transaction —
Payload's "forgot password" with `mail: { accountMailAfterCommit: false }` — holds a connection that long
([deployment.md](./deployment.md) §4.3a; by default that mail goes out after its transaction commits). Change them:
`mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })` or `panelSmtpAdapter({ timeouts })`
(type `SmtpTimeouts`).
SMTP only, without the dispatcher:
@@ -470,7 +476,8 @@ export default buildConfig({
})
```
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`).
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`), `timeouts`
(`{ connectionMs: 10000, greetingMs: 30000, socketMs: 60000 }`).
## Dependency
@@ -520,7 +527,14 @@ if (result.sent) {
Password reset and e-mail verification go through Payload's built-in mechanism (`config.email`). With
`mailAdapter()` wired they take the same transport as everything else; with the mail service they are sent as
account mail ("What a message is").
account mail ("What a message is"). Payload sends them inside the operation's database transaction; `mailAdapter()`
sends them right **after** it commits instead (still in the same request; nothing when it is rolled back), so a slow
mail server holds no database connection — `mail: { accountMailAfterCommit: false }` keeps them inside
([deployment.md](./deployment.md) §4.3a). The message is matched to its request by the token it carries (and the
account's address), never by the address alone: a form's mail to the same address goes out as usual. A project's own
`forgotPassword.generateEmailSubject` / `verify.generateEmailSubject` is kept; an own `generateEmailHTML` must put the
token in the body (any working reset link does), or that mail is sent inside the transaction as before. An e-mail adapter of your own does the same by calling
`sendAccountMailAfterCommit(message, () => send(message))` first.
## Masking secrets in the panel (MaskedField)
@@ -717,7 +731,8 @@ Save your changes before the test — the endpoint reads from the database, not
## Send status in the panel
`mailAdapter()` stores the send result in Site integrations (at most once per 10 min
while an error persists, immediately when the state changes). When sending fails:
while an error persists, immediately when the state changes; many sends failing at once write it once, and while a
Postgres pool is busy the write goes on in the background — [integrations.md](./integrations.md)). When sending fails:
- **Dashboard** — a red alert with the cause and a link to Site integrations,
- **Site integrations → E-mail sending** — a banner with the error (e.g. `SMTP: connect ECONNREFUSED …`,
`SMTP: Invalid login: 535 …`, `Microsoft Graph: Graph sendMail failed (403).`, or the text of a mail service
@@ -756,7 +771,8 @@ SDK); you then skip the panel's SMTP fields, the mail service and the send statu
integrations and the endpoint `POST /api/ipal/test-email` are always added.
- **Choosing the transport:** `mailAdapter()` (decided per send) or a fixed `relayAdapter()` /
`panelSmtpAdapter()` / `graphAdapter()`; any other Payload adapter also works.
- **Override:** `fallbackFromAddress` / `fallbackFromName`; in `mailAdapter` separately `relay`, `smtp` and `graph`
- **Override:** `fallbackFromAddress` / `fallbackFromName`; in `mailAdapter` separately `relay`, `smtp` (with
`smtp.timeouts`) and `graph`
(`graph.largeAttachments: false` keeps Graph to attachments under 3 MB — "Attachments"); every option of the
mail service ("Options"); panel texts through `i18n.translations` (keys `mailRelay…`, `statusEmailRelay…`);
the tab's fields through `integrationsFields`.
+27 -2
View File
@@ -453,7 +453,8 @@ Limits are kept in memory by default, separately for each instance. Several inst
`turnstile`, rejected **before** storing. Keys not set → the widget does not
show, and the check is skipped. Details: [turnstile.md](./turnstile.md).
3. **Validation** against the form definition from the panel (+ enforced GDPR consent).
4. **Storing** the submission (form-submissions) → the form-builder sends the emails from the Emails tab.
4. **Storing** the submission (form-submissions) → the form-builder composes the emails from the Emails tab;
they go out right after the submission is saved ("When e-mails go out").
**A stored submission = success, even when the email fails** — Payload logs the sending error,
the submission data is not lost (it is in Form Submissions).
@@ -474,6 +475,29 @@ body (placeholders: `{{field}}`, `{{*}}`, `{{*:table}}`) without touching the co
`submitForm` is responsible only for Turnstile verification and storing. It stores the submission in the page's language
(`locale` from `createSubmitAction`), so the form-builder takes the email texts and labels in that language.
### When e-mails go out (`emailsInTransaction`)
By default (since 1.17.0) a form's e-mails go out **right after the submission is saved**: they are composed inside
the submission's database transaction (layout, `forms.beforeEmail`, the kind marks, all with the transaction's
`req`), and handed to the mail server once that transaction has committed and given its connection back — still
within the same request, so `submitForm` answers as before (a file that could not be sent is still reported to the
visitor). What this changes:
- a slow or hanging mail server holds **no database connection** — on Postgres, many submissions at once used to stop
the site ([deployment.md](./deployment.md) §4.3a);
- a submission whose transaction is **rolled back** (a later hook of yours throws) sends **nothing**; before, its
e-mails had already gone out;
- **a failure after the commit leaves a stored submission without its e-mail** (the mail server refused it, or the
process ended in between) — as an e-mail failure always did: the submission is in Form Submissions, the error in
the log and the panel status, a file marked **File delivery: Not sent**;
- `payload.create` of a submission inside **your own transaction** (`req` passed from a hook or a script): the e-mails
go out when that transaction commits, and not at all when it is rolled back;
- **MongoDB without a replica set, SQLite** (no transactions): sent at once, exactly as before.
`forms: { emailsInTransaction: true }` sends them inside the transaction, as before 1.17.0 (not recommended on
Postgres). Building blocks: `sendAfterCommit(prepare, deliver)` (the `beforeEmail` that does this),
`sendFormEmails(req, emails)` (form-builder's own send loop), `afterCommit(req, fn)` (deployment.md §4.3a).
### Nice emails (`emailLayout`)
```ts
@@ -848,6 +872,7 @@ filter it out on the client.
site-wide consent field name: `forms.consentFieldName`; shared limit store: `setRateLimitStore`; missing IP: `setUnknownIpFactor`.
- **Check:** `POST /api/form-submissions` without a session = 403; a `user` account → `PATCH /api/forms/<id>` = 403;
submits without an IP header → past `maxPerMinute × 20` per minute (100 by default) you get `rate_limited`.
- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template.
- **Emails:** `forms.beforeEmail` modifies emails (after the layout), `emailLayout: true` turns on the template,
`emailsInTransaction: true` sends them inside the submission's transaction ("When e-mails go out").
- **Your own front end:** `BuilderForm` (`renderField`), `useBuilderForm`, pure logic (`splitSteps`,
`visibleFields`, `validateBuilderFields`…), `useForm` / `useContactForm`, validators, `buildFormsPlugin` (root).
+3 -1
View File
@@ -34,7 +34,9 @@ The state block above it reads `GET /api/iapl/mail-relay/status` and acts throug
- **Write:** `mailAdapter()` on every send (`emailStatus`) and Turnstile verification on a
form (`turnstileStatus`) call `recordIntegrationStatus`. It writes only when the state changes,
or at most every 10 min while an error lasts; it never throws.
or at most every 10 min while an error lasts; it never throws. The same change already being written (many sends
failing at once) is written once; while every transaction place of a Postgres pool is taken
([deployment.md](./deployment.md) §4.3a) the write goes on in the background instead of holding the caller.
- **Changing keys in the admin panel** (Turnstile, `emailTransport` / `smtp*`) clears that integration's old status.
- **`emailStatus.code`** of a send through the Intecion mail service is one of the `relay-…` codes (`relay-pending`,
`relay-quota`, `relay-unreachable`, …), each with a text in the editor's language — the list and what to do: