Skip to content

feat(preview): retry a connection while a preview's Postgres wakes - #1185

Merged
Ardnived merged 6 commits into
mainfrom
claude/feat-preview-postgres-wake
Nov 17, 2026
Merged

Ardnived merged 6 commits into
mainfrom
claude/feat-preview-postgres-wake

Conversation

@Ardnived

@Ardnived Ardnived commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Why

Letting a PR preview's Postgres sleep saves roughly $10 a month at today's preview count, but the sleep test on #1178 showed it breaks the first request after a wake: the connection that wakes Postgres is refused, @payloadcms/db-postgres does not retry, and Payload's init fails with cannot connect to Postgres. request-magic-link hides that as a 200 {"ok":true} with no token, which is how CI's fixture fill failed twice.

This is the prerequisite. #1186 adds the workflow and script that turn sleep on for each preview's app and Postgres after CI.

What

  • src/plugins/postgresWake/: on a Railway PR preview, retryWhilePostgresWakes wraps the adapter's own pg so its pool retries a connection for up to 30 s, 1 s apart. It retries ECONNREFUSED, ECONNRESET, ETIMEDOUT, EHOSTUNREACH, ENOTFOUND, EAI_AGAIN, 57P03 (database starting up), and pg's code-less "Connection terminated" and connection-timeout errors. Anything else, such as a bad password, fails at once.
    • The retrying itself is p-retry, already a dependency with two callers: maxRetryTime is the budget, shouldRetry is isPostgresWaking, and factor: 1 with minTimeout is the flat interval.
    • Both connect() forms retry. The pool's own query(), which Drizzle calls, connects through the callback form.
    • It wraps the adapter's pg rather than passing the app's through the pg option, because the two resolve to different pg versions (8.20 and 8.23). A preview keeps the driver production runs.
    • The first refused connection per attempt logs once: Postgres refused a connection; retrying while it wakes.
    • init is the seam because the adapter builds its pool later, inside its own connect(), as new this.pg.Pool(this.poolOptions) — init leaves pool undefined.
  • Production and every non-preview environment are untouched, gated the same way as jobAutoRun().
  • DEPLOYMENT.md, Cost Monitoring: one paragraph on the retry. tests/COVERAGE.md: a row for the plugin, beside the one sentryPlugin already had.

Preview

Any read of a fixture row is a connection through the wrapped pool, so each link below exercises this change — and the preview's Postgres is already asleep between visits (see Verification).

  • Region 1002001 — the fixture's country region; its editor reads through the wrapped pool
  • Images list — a list query, which Drizzle takes through the pool's own query(), the callback form the retry also covers
  • /api/health — fixture: loaded means the boot connection got through

Verification

  • Tier 2 lean gate (lint, format, typecheck, test typecheck, unit lane): passed — 275 files, 3728 tests.
  • tests/unit/postgres-wake-retry.spec.ts:
    • which errors read as a wake;
    • retry then success, in the promise and callback forms;
    • an immediate failure on a non-wake error;
    • giving up once the budget is spent;
    • a real pg pool's query() against a refused port, retrying for the whole budget;
    • the real postgresAdapter's own connect() against a refused port — it builds its pool from the pg that init left, so the retry reaches the adapter's own connect path;
    • the wrapper applies on a preview and returns the adapter untouched in production, staging and off-Railway.
  • On this PR's preview, with the app and Postgres both asleep (via feat(preview): let each PR preview sleep when idle, after CI #1186's script), /api/health answered 200 in 3.3 s, and the fixture reported loaded 4 s later. The log shows the refused connection (an AggregateError, Node's dual-stack refusal), then Postgres refused a connection; retrying while it wakes, then [fixture] loaded … 211 unchanged.

Notes for reviewer

  • The adversarial review's four findings are all built: p-retry replaces the hand-rolled loop, the ⚠ pointing at an unlanded scripts/preview-sleep.ts is gone, the db.pg seam is named from the compiled adapter and driven by a case against the real one, and this body now has a ## Preview section.
  • The coupling that ⚠ carried now lives in feat(preview): let each PR preview sleep when idle, after CI #1186, as WAKE_RETRY_PATH in scripts/preview-sleep.ts, which sleeps a preview's Postgres only at a commit holding src/plugins/postgresWake/wakeRetry.ts. Nothing here renames that file, so that check still answers.
  • origin/main is merged in — one commit, no conflicts.
  • This body keeps its own ## Why / ## What / ## Verification shape rather than the template's headings; only the missing ## Preview was added.
Detail

Why p-retry and not the loop. The loop, its deadline arithmetic and an exported WAKE_BUDGET_MS with no importer were a second implementation of a dependency this repo already calls in src/lib/mapbox/geocoder.ts and src/jobs/SyncLectureMetadata. Two of p-retry's edges are commented because they are easy to get wrong: retries must be Infinity, since the budget rather than a count is what ends the retrying; and onFailedAttempt runs on a failure nothing retries, so the one-time log repeats the wake test instead of assuming a retry followed. maxRetryTime exhaustion rethrows the original error, so the caller still sees the last refusal.

Why both connect() forms. @payloadcms/[email protected]'s compiled dist/connect.js takes the boot connection through the promise form, and Drizzle's node-postgres driver takes every query through pool.query(), which connects via the callback form. Retrying one leaves the other unprotected.

How the seam is checked without a sleep. A refused port is what a first connection to a sleeping service sees, so the new case builds the real adapter at one, replaces its pg, and asserts the adapter's own connect() retried for the whole budget before raising cannot connect to Postgres. Watched fail with the wrap removed: the adapter gave up in 10 ms and reported no wake.

🤖 Generated with Claude Code

A Railway service asleep under Serverless wakes on the first
private-network connection to it, and that connection is refused.
`@payloadcms/db-postgres` does not retry, so the request behind it
failed — and `request-magic-link` answers every failure as a 200 with no
token, which is how CI's fixture fill broke when a preview's Postgres
was allowed to sleep (#1178).

On a PR preview the adapter's own `pg` is wrapped so its pool retries a
connection for up to 30 s, 1 s apart, on the network errors a waking
service answers with and on 57P03. Both connect forms retry, since the
pool's `query()` — what Drizzle calls — connects through the callback
form. Production's adapter is untouched: its Postgres never sleeps.

This is the prerequisite for letting a preview's Postgres sleep; the
setting itself comes with the preview-sleep workflow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@railway-app

railway-app Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-1185 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Nov 17, 2026 at 6:37 pm UTC
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1185 November 17, 2026 17:49 Destroyed
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 17, 2026
@sydevs-bot

sydevs-bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🤖 no session running

recent dispatches
  • 18:18Z address-review · attempt 1 · session · done
  • 18:18Z address-review · attempt 1 · session
  • 18:09Z review-pr · attempt 1 · session · done
  • 18:09Z review-pr · attempt 1 · session

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Nov 17, 2026

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 Adversarial review

The PR is the size of its problem: a gate, a wrapper, a doc paragraph. The payload.config.ts change is a wrap plus re-indent. Placement is right: src/AGENTS.md gives src/plugins/ the modules payload.config.ts registers as db, and the gate mirrors jobAutoRun()'s. Two shape questions remain. The retry loop is hand-rolled beside p-retry, which this repo already depends on and calls twice. And the seam the change hangs on — the adapter reading db.pg after init returns — is neither stated nor tested, while the body admits no sleeping Postgres was seen. The diff also touches src/plugins/, a fixture.surfacePaths entry, with no ## Preview section in the body: the rule allows none, and a reviewer checking a wake wants the preview's admin link.

Findings

  • should-fix — the retry loop reimplements p-retry, already a dependency with two callers (src/plugins/postgresWake/wakeRetry.ts:67).
  • should-fix — the ⚠ names scripts/preview-sleep.ts, which no commit on this branch has (src/plugins/postgresWake/index.ts:25).
  • should-fix — no ## Preview link, though the diff touches a preview surface (PR body).
  • consider — the db.pg seam is unstated and untested (src/plugins/postgresWake/index.ts:37).

What was checked

Diff read whole, then each new piece against the ladder. src/AGENTS.md places the folder and makes index.ts barrel + wakeRetry.ts the convention. The gate reuses railwayEnvironmentName() and isPreviewEnvironmentName(). src/plugins/databaseErrors/ reads SQLSTATE 22P02 into a 400, a different concern. A hunt for an in-repo retry helper found only p-retry's callers. payload.config.ts read whole: no logic added there, so no whole-file pass is owed. No contract surface moves. node_modules is absent here, so the adapter's connect path went unread.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread src/plugins/postgresWake/wakeRetry.ts Resolved
Comment thread src/plugins/postgresWake/index.ts Resolved
Comment thread src/plugins/postgresWake/index.ts Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Nov 17, 2026
The wrapper's own loop, its deadline arithmetic and the exported
WAKE_BUDGET_MS reimplemented p-retry, which this repo already depends on
and calls in src/lib/mapbox/geocoder.ts and
src/jobs/SyncLectureMetadata. p-retry's maxRetryTime is the budget,
shouldRetry is isPostgresWaking, and factor: 1 with minTimeout is the
flat interval.

Two of its edges are load-bearing and now carried by comments: the
budget, not a count, is what ends the retrying, so retries must be
Infinity; and onFailedAttempt runs on an error nothing retries, so the
one-time log repeats isPostgresWaking rather than assuming a retry
followed. maxRetryTime exhaustion rethrows the original error, so a
caller still sees the last refusal.

WAKE_BUDGET_MS had no importer, so it is module-private now.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYSqZCw6hTAAaKMa6U
The ⚠ asked a reader to keep `scripts/preview-sleep.ts` in sync with
this folder, and no commit on this branch adds that file, so nobody
could act on it. The coupling it names is real but belongs beside the
script that turns sleep on, in the pull request that lands it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYSqZCw6hTAAaKMa6U
The wrapper rests on the adapter reading `db.pg` after `init` returns,
and nothing stated or checked it: the existing case asserted against a
fake adapter, and no sleeping Postgres had been observed.

`@payloadcms/[email protected]`'s compiled `dist/connect.js` builds the
pool inside `connect()`, as `new this.pg.Pool(this.poolOptions)`, while
`dist/index.js` leaves `pool: undefined` at init — so `init` is the
seam, and the docblock now says so.

The new case drives the real adapter at a refused port, which is what a
sleeping Postgres looks like to a first connection. Watched fail with
the wrap removed: the adapter gave up in 10 ms and reported no wake.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYSqZCw6hTAAaKMa6U
The plugin and its spec landed with no row, and that section already
tracks a plugin's own wiring (`sentryPlugin`), so the map had a hole
where a reader looks for one.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYSqZCw6hTAAaKMa6U
@sydevs-bot

Copy link
Copy Markdown
Contributor

Four findings, four built. Pushed e93eeaf.

Also committed: a tests/COVERAGE.md row for the plugin, which landed without one.

origin/main merged in, one commit, no conflicts. Lean gate green: 275 files, 3728 tests. No security review — this push touches no securityReview.triggerPattern path.

Anomaly: the body gained a Verification bullet at 18:30Z, after I read it. The refresh keeps it.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 17, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 17, 2026
@sydevs-bot
sydevs-bot enabled auto-merge November 17, 2026 18:44
@Ardnived
Ardnived merged commit 98c747b into main Nov 17, 2026
47 of 51 checks passed
@Ardnived
Ardnived deleted the claude/feat-preview-postgres-wake branch November 17, 2026 18:50
@sydevs-bot sydevs-bot moved this from Awaiting to Done in SYDevelopers Technical Roadmap Nov 17, 2026

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-1185 — e93eeafa Deployed Nov 17, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

3 participants