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
+25
View File
@@ -131,6 +131,31 @@ 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; one that has
waited a second may use all but the last connection. `false` = as before. Building blocks `reserveConnections`,
`watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`,
`poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a).
- **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 fixed here: Payload's own "forgot password" and "verify your e-mail" still send inside their transaction, so a
hanging mail server makes them hold a place until the SMTP time-out (others wait; nothing stops).
### 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
+3
View File
@@ -1246,6 +1246,9 @@ 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; one waiting a second may use all but 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`, `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) |
| 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)
+3
View File
@@ -120,6 +120,9 @@ 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 (forms answer, logins and saves wait) | Payload's "forgot password" sends inside its transaction and holds a place until the SMTP time-out | fix the mail server; shorter `mailAdapter({ smtp: { timeouts } })`; form e-mails are not affected (sent after the commit unless `forms.emailsInTransaction: true`) |
| 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
+4
View File
@@ -580,6 +580,10 @@ 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`), form e-mails go out right after the submission is saved (`forms.emailsInTransaction`),
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
+39
View File
@@ -351,6 +351,45 @@ 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 that has waited a second (`RESERVE_ESCAPE_MS`) may use the reserve too, all but one connection — so a
transaction begun inside another one (a hook without `req`) does not wait for ever on its caller, and one connection
is never held by a transaction;
- form e-mails go out **after** the submission's transaction commits ([forms.md](./forms.md) "When e-mails go out"),
so a slow mail server holds no connection; Payload's own account mail ("forgot password", "verify your e-mail") is
still sent inside its transaction — with a mail server that hangs, those requests hold a place until the SMTP
time-out ([email.md](./email.md) "SMTP": 10 s to connect, 30 s for the greeting by default).
```ts
iapl({ connectionReserve: 3 }) // keep three connections free
iapl({ connectionReserve: false }) // no limit, as before 1.17.0 (not recommended)
```
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),
`poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`.
**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, 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
+11 -3
View File
@@ -423,6 +423,11 @@ 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" — holds a connection that long ([deployment.md](./deployment.md) §4.3a). Change them:
`mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })` or `panelSmtpAdapter({ timeouts })`
(type `SmtpTimeouts`).
SMTP only, without the dispatcher:
@@ -438,7 +443,8 @@ export default buildConfig({
})
```
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`).
Options: `fallbackFromAddress` (`'noreply@localhost'`), `fallbackFromName` (`'Website'`), `timeouts`
(`{ connectionMs: 10000, greetingMs: 30000, socketMs: 60000 }`).
## Dependency
@@ -685,7 +691,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
@@ -724,7 +731,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: