Repository navigation
fix(platform): hold up under a load burst and a database restart - #4853
Merged
Merged
Conversation
postgres.js tells begin() which connection its BEGIN runs on through the `onexecute` hook, and calls the hook last in an `&&` chain behind `sent.length < max_pipeline`. When the pool had pipelined 100 plain statements onto a busy connection and the BEGIN filled it, the hook was skipped though the BEGIN was written: its CommandComplete found no reservation (UNSAFE_TRANSACTION) and the connection went back to the pool inside the transaction. The next begin on it logged "already a transaction in progress" or failed with 25001, the aborted transaction never returned to idle, and its slot leaked. The 4,000-user spike of the load run hit it in every run (19 and 5 HTTP 500s, a lost api_key.created audit row, four leaked `idle in transaction (aborted)` sessions); a steady 4,000-user run did not, because pipelines stay shallow. Instrumented, all six captured failures showed the same chain: write ok, sent.length 100, onexecute not called. The patch now calls `onexecute` once the statement is written, in all three builds, keeping its return value. It is porsager/postgres#1189. `begin-fills-the-pipeline` (a pool of two, max_pipeline 3, the begin the seventh statement) fails unpatched with UNSAFE_TRANSACTION in the ESM and CJS builds and passes patched.
Better Auth reads the session in its middleware and, when the read throws, logs the database error and carries on without a session. With the database away, POST /api/auth/organization/set-active and GET /api/auth/api-key/list answered a 401 UNAUTHORIZED for a perfectly good session, and GET /api/auth/get-session a bare 500. The app reads a 401 UNAUTHORIZED as "this session ended" and takes the tab to sign-in (auth-client-error.ts), so a database restart signed people out of the page they were using; PERF-B5 promises a 503, never a 401. The auth logger already notes the database error it saw for the request. The /api/auth mount now swaps a 401 or a 5xx for the retryable 503 DATABASE_UNAVAILABLE (Retry-After) when one was noted. A request with no session never meets the database and keeps its 401. app.auth-outage.test.ts runs the real library against a closed port through the real app: unfixed it answers 401, 401 and 500.
A REST chat turn (`chat.api_turn`) holds its worker slot for the whole reply and spends nearly all of it waiting on the model's stream, yet it ran in the worker's five default slots. The same chat in the app runs in the API process, unbounded, so API clients saturated first: under the load run an API client's first token took 1.3 s with 14 users, 6.2 s with 1,000 and 49 s with 4,000 (p95 95 s), while the app's own chat stayed under a second. `chat.api_turn` now has a floor of sixteen slots, like an agent drive window (`TASK_WORKER_MIN_SLOTS`), and its idle slots poll every five seconds instead of two, so the extra slots add little polling. The poll only surfaces the one turn the deploy drain hands on five seconds late; every other send is woken by its insert. The API reference and the rate-limit page still described batches of `WORKER_CONCURRENCY` turns whose next batch waits for the current one. That has not been true since the queue became independent slots; they now say what runs. The environment reference and the backend README list the new floor. EN, DE and FR.
Better Auth hashes with scrypt (32 MiB, 100-150 ms each) on libuv's four shared threads, a single FIFO queue that file reads and DNS lookups use too. Unbounded, a wave of sign-ins queued thousands of hashes ahead of everything. In a test, 3,000 people signing in over a minute left 138 sign-ins served and the rest timed out, other routes timed out behind the backlog, and a sign-in sent after the storm waited 215 seconds. A client that gave up did not cancel its hash. Every hash and check of the process now runs through one bounded hasher: at most half the pool at once (2 by default, from UV_THREADPOOL_SIZE), about sixteen waiting per slot, a wait of at most four seconds. Past that the check is refused before any hashing with 503 PASSWORD_CHECK_BUSY and a Retry-After, in milliseconds. The refusal is an APIError, so the sign-in hooks read it as a check that was not attempted and never count it toward an account's lockout. The sign-in page worded every non-429 failure as "wrong email or password" with the lockout advisory; a 5xx now reads as "Signing in isn't possible right now" (EN, DE, FR) and warns about nothing. The pool's state is exported as tale_backend_password_checks_active, _waiting and _refused_total, and UV_THREADPOOL_SIZE is documented in .env.example and the environment reference. The browser's auth client replays any 5xx four times, 0.5 to 4 seconds apart; it no longer replays this refusal (lib/auth-retry.ts), which would put five requests from every browser into the queue the cap protects, long before the wait Retry-After asked for. The admin and recovery doors that write a new password themselves still hash it directly, at a person's pace.
A chat reply that is cut by a restart stayed `pending` until the generation sweep took it for dead ten minutes after its last heartbeat (about eleven in practice). Two ordinary events caused it. A database restart of three seconds that caught a reply as it ended: the usage booking, the reply's settle, the failure settle and the generation's end all failed at once, `transactSerializable` reruns a dropped connection five times 20 ms apart, and nothing was left to mark the placeholder. These four writes now wait out an unavailable database on a clock of their own (`waitOutDatabaseOutage`, the boot wait's backoff and classification) and rerun, each being idempotent. A graceful stop of a process running replies: an app reply runs in the api process, an API-key reply in a worker, and the shutdown sequence settled automation turns only, for workers only. The process now tracks the turns it runs (`live-turns.ts`), lets them finish for the rest of its drain budget, and settles the ones still going as interrupted - the same terminal state the sweep writes, through the same function - before it closes its pools. A killed process cannot do either; the sweep stays the recovery for it, with its ten minutes, which the deploy drain and the tool deadlines are measured against. The real-Postgres watchdog lane gains the case: a process settles its own live turn at once and touches a turn it did not run not at all. The environment reference says what a stopping replica does with a reply. The settle of a stopping process (the generation row, the thread, the placeholder) rides one transaction, so a database that fails between them leaves the row for the sweep instead of a turn nothing would settle. The usage booking prices the turn inside the same wait; the price lookup used to swallow an outage and book the turn at 0 cents, so it lets one through now (estimateTurnCostCents) and the booking reruns whole.
After a database restart the hint streams measured "database back after 3s" on one api process and "after 20s" on its sibling, and requests between answered 503 the database no longer deserved. postgres.js reconnects a dropped connection after a backoff that climbs to twenty seconds, and its retry count belongs to the whole pool: twenty connections failing to reconnect through a few seconds of restart put the count at its ceiling, so each then waited up to twenty seconds past the moment the database answered. Real hint latency followed: p99 17 s, worst 18.5 s. The application and knowledge pools now open with postgres.js's own backoff (jittered between half and all of `3 ** retries` hundredths of a second) capped at two seconds. The jitter still spreads a pool's reconnects; a dead database is polled at no cost worth the wait. The event stream's own ceiling while the database is away drops from ten to five seconds, for the same reason.
A serializable transaction that lost to concurrent writers was rerun five times, 20 ms apart and doubling: about 300 ms. Against a burst of 200 writers over 20 hot rows that failed 4-9% of them, and against 300 over five rows 77%. The load run's spike exhausted it on its worst day, and the caller saw a plain 500 with the error's whole stack on the console and nothing to say which write kept losing. transactSerializable now reruns eight times (SERIALIZABLE_ATTEMPTS, about two and a half seconds on average and 3.8 at worst, jittered): the same bursts fail about 0% and under a fifth. Rows hotter than that are the retry queue's job (markRetryQueueKey). A retry warning now names the call site - "(domains/chat/store.ts:655)" - read from the error's stack only when a retry is logged, since postgres.js builds a statement's error with the stack of the place that wrote it. A write that still runs out of reruns answers 503 with Retry-After and a requestId, in each door's flat envelope with the generic HTTP_ERROR code (a client that does not know a code reads the status), one warn line naming the write instead of a stack, and a warning-level report tagged tale.reason=write_conflict. No new contract code: the REST reference says what a 503 can mean. isSerializationFailure moves into retry.ts, which imports nothing, and serializable.ts re-exports it: the error handler classifies a lost write with it, and a test that replaces serializable.ts must not take that with it.
The backend's resolve hook retries a specifier that does not resolve as `.ts`, `.js`, then `/index.ts`, and logged every candidate that did not exist through `console.debug`. In Node `console.debug` is `console.log`, so each api and worker process printed 26 "candidate failed" lines to STDOUT at start, for specifiers that resolve one step later; anything reading the process's stdout got them mixed into its own output. The trail is now a `NODE_DEBUG=tale-loader` section (`util.debuglog`), on stderr and off by default. node-loader.test.ts runs the real hook in a child process against a directory import: it prints nothing, resolves, and shows its candidates under NODE_DEBUG.
A database restart fails every query in flight at once, and the worker printed each one's whole error object: nine to twenty stack frames from postgres.js internals per line of news, for the audit sealer, the title job, the usage writes, the chat stream poll and the auth cache's invalidation log. A deployment with no sandbox has no spawner token, and `sandbox.workspace_gc` printed the "SANDBOX_TOKEN is not set" stack on every sweep. `logDetail` (db/unavailable.ts) hands the logger the one line `describeDatabaseError` writes when the database is away, and the error itself - stack and all - for anything else, so a defect keeps the evidence it needs. The cleanup sweep prints the sentence of a plain Error and keeps the stack of one the runtime raised. It trusts only what is unmistakably the database's - a statement postgres.js rejected, a SQLSTATE, a driver's own code - unless a catch that holds database calls alone says so: a model provider's refused socket keeps its cause and its stack.
Two virtual users naming a project alike meet PROJECT_KEY_TAKEN (409), which the report counted as an error of the platform; a person picks another name. It is a refusal now, counted as projects.key_taken. So is a sign-in the platform refuses as busy (503 PASSWORD_CHECK_BUSY): the storm profile sheds load by design, and the report counts the refusals by status. The server section reads tale_backend_password_checks_active and _waiting, and the README explains what the load run taught: signin-storm needs --forwarded-for (all users otherwise share one source address and meet the sign-in flood guard by design), a refused sign-in is a 503 outcome, soak holds its peak for an hour at least, and net_ETIMEDOUT / connect timeouts are the target's listen backlog, not the platform.
.agents/repo.md says what the second hunk of the postgres patch fixes (a begin() that fills a connection's pipeline) and where the patches README keeps its proof. It also records two pieces of debt this work leaves behind. A hard-killed chat turn (SIGKILL, the out-of-memory killer, a lost host) is still swept after ten minutes, and the entry says what paying that down takes. A deployment with no sandbox token still logs a stack per leftover session at the watchdog and light-session sites.
Six boxes in the performance suite: PERF-P18 (a 4,000-user spike), P19 (a sign-in storm), P20 (REST turns on a worker), B11 (a reply when the api restarts), B12 (a reply as the database restarts) and B13 (a database restart does not sign you out). The error-code reference gains the rows for PASSWORD_CHECK_BUSY and the 503 write conflict and amends DATABASE_UNAVAILABLE for the Better Auth routes; the retry warning quoted by B7 and B10 carries its call site now; the automation reference gets one row per spec that took over a slice.
yannickmonney
added this pull request to the merge queue
Oct 12, 2026
This was referenced Oct 12, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A perf/stress/chaos pass over
main(a disposable stack fromtools/load: 5,000 seeded users, two api processes and a worker) found seven faults in how the platform behaves under a load burst or while its database restarts. This fixes all of them, each with a regression test that fails without the fix, and re-runs the failing scenarios on the fixed code.The faults and the fixes
idle in transaction (aborted)sessions piled up. postgres.js 3.4.7 skippedonexecutewhen aBEGINfilled a connection's 100-statement pipeline, so the transaction ran on a connection the pool had already handed to the next caller.patches/[email protected]gets a second hunk (execute()runsonexecutewhatever the pipeline answers);db/connection-loss.test.tsproves it against the real driver (ESM and CJS builds).auth/password-hasher.ts): half the libuv pool runs at once, a bounded queue waits at most four seconds, and the rest are refused in milliseconds with a retryable503 PASSWORD_CHECK_BUSY+Retry-After, which counts toward no lockout. The browser does not replay that refusal on its own, gauges and a refusal counter are exported, the sign-in page tells a 5xx from a wrong password (EN/DE/FR), andUV_THREADPOOL_SIZEis documented.401while the database restarted, which the SPA reads as a lost session and signs the tab out (get-sessionanswered a bare 500). They answer the same retryable503 DATABASE_UNAVAILABLEas every other door.rest.first_textmedian 1.3 s with 14 users, 6.2 s with 1,000, 49 s with 4,000). A worker now runs at least sixteen at once.pendingfor ten minutes when the api stopped, or the database restarted as a reply ended. The closing writes (final message, generation row, usage booking) wait out an outage for up to a minute, the booking in one transaction so a rerun cannot count a turn twice; a stopping process lets its running turns finish for the rest of its drain budget and settles the others as interrupted (eight at a time, one transaction each, within five seconds) before it closes its pools.503withRetry-After: 1.Smaller items: the module loader printed 26 lines on every start; an unavailable database and a missing spawner token were logged as stacks; the load harness counted a taken project key as a failure, and now a busy sign-in as one too, and its README did not say how to read the profiles.
Checklist
bun run check, run as its parts on the final tree:oxfmt --check, commitlint,lint:conflicts,lint:links,lint:manualandcheck-guide.ts, platform / shared / load lint and typecheck, knip, shared, load, docs,@tale/uii18n, the platform UI (jsdom) project, and the platform backend and lib tests (1,025 files, 14,397 tests). The full server + pii run on the tree before the last rebase passed 88,156 of 88,157 tests; its one red, a 5 ms timing budget of the diff engine that this branch does not touch, took 4 s on a machine at load average 125 and passes alone. Not run here: the browser project (the merge queue runs it).bun run lint:sast— 0 findings on the changed files.login.temporarilyUnavailablein theauthtopic ofen,deandfr.docs/{en,de,fr}/(environment reference, API reference, rate limits) and.env.example.services/platform/backend/README.md,tools/load/README.mdandpatches/README.mdupdated; the root READMEs N/A.Test plan
Unit and component tests per fix, plus the new manual boxes
PERF-P18–PERF-P20andPERF-B11–PERF-B13(lint:manualandcheck-guide.tsclean). Observed on the fixed code, on a laptop shared with other agents (load average 40–140, so absolute times are pessimistic):http_5xxerror kind (before: 19 and 5 genuine 500s in two runs); noUNSAFE_TRANSACTION,already a transaction in progressor25001in any api or worker log; no sessionidle in transactionafterwards (116 idle, none in a transaction; before: aborted ones); serialization failures are one-line retries (transient error on attempt 1/8, retrying in 20ms (domains/tasks/service.ts:865)). What is left is the host's listen backlog (net_ETIMEDOUTand connect timeouts; macOSkern.ipc.somaxconnis 128) and 7 REST401s for keys the harness revokes when a virtual user stops (106 revocations in that minute; no live user saw a 401).503 PASSWORD_CHECK_BUSY(tale_backend_password_checks_refused_total{reason="queue_full"}307);/api/health/readystayed under 0.23 s (p99) and a sign-in right after the storm took 85 ms. Before: 138 of 5,580 sign-ins served and ~4.5 minutes of brown-out. With one hashing slot per process (UV_THREADPOOL_SIZE=2): 1,296 served, 9,377 refused withRetry-After2–5 s,/readyp99 0.57 s, whole-platform http p95 0.8 s, a sign-in after the storm 100 ms.get-sessionandset-activeanswered503 DATABASE_UNAVAILABLE(Retry-After: 5) and never401(before: 401 for valid sessions); the REST door answered200again at the first poll after the database accepted connections (half a second apart); the hint stream stayed open; a one-second restart logged/events: database back after 1s(before, a three-second restart left one process's stream stalled for 20 s).failed— "interrupted by a restart" — at +19.6 s (the 15 s drain), the generation row was gone, the thread idle,[backend] 1 chat turn(s) still running at shutdown — settled as interruptedwas logged, nothing was booked. A short reply in the same drain finishes normally.failed— interrupted — at +96 s, after the 90 s drain.completewith its whole text within two seconds of the database coming back, booked once, at its price. (This run found a defect in the first version of the fix: the price lookup swallowed the outage and would have booked 0 cents. An independent read of the diff found another: a rerun adding to the period buckets twice. Both are fixed and tested.)rest.first_textmedian 1.3 s, p95 2.7 s, against the browser'schat.ttftmedian 0.85 s; before: 6.2 s and 15.5 s.chat.ttftmedian 0.67 s,rest.first_textmedian 1.2 s; no pool-corruption signature in any log.backend:integration, filtered to 11 lanes: files, small domains, message slots, REST door and pagination, turn re-attach, stuck sends, control drain, recovery sweeps, arena, watchdogs): 138 of 138 checks, including a new one for the stopping-process settle.Not changed, on purpose
.agents/repo.mdas debt.HTTP_ERROR503, so the contract and the OpenAPI document keep their version.SANDBOX_TOKENis unset (the load stack has no spawner); they belong to the in-flight chat-sandbox work, and the debt is recorded in.agents/repo.md.401 Invalid API keyseen in the spikes is not a platform fault: the requests were in flight when the harness revoked their virtual user's key at the end of a stage (no live user saw one); the door answers503for every recognised database failure, as the restart runs above show.password-hasher.ts).queuedAhead, the macOS listen backlog and the Bun version drift are environmental or already on the ledger.