-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
fix(webapp): auto-recover replication services after stream errors #3613
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ericallam
wants to merge
2
commits into
main
Choose a base branch
from
fix/replication-auto-recover-on-stream-error
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| area: webapp | ||
| type: fix | ||
| --- | ||
|
|
||
| Runs and sessions replication services now auto-recover from stream errors (e.g. after a Postgres failover) instead of silently leaving replication stopped. Behaviour is configurable per service — reconnect (default), exit so a process supervisor can restart the host, or log. |
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
194 changes: 194 additions & 0 deletions
194
apps/webapp/app/services/replicationErrorRecovery.server.ts
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| import { Logger } from "@trigger.dev/core/logger"; | ||
|
|
||
| // When the LogicalReplicationClient's WAL stream errors (e.g. after a | ||
| // Postgres failover) it calls stop() on itself and stays stopped. The host | ||
| // service has to decide how to recover. Three strategies are available: | ||
| // | ||
| // - "reconnect" — re-subscribe in-process with exponential backoff. Default; | ||
| // works without a process supervisor. | ||
| // - "exit" — exit the process so an external supervisor (Docker | ||
| // restart=always, ECS, systemd, k8s, ...) replaces it. Recommended when a | ||
| // supervisor is present because it gets a clean slate every time. | ||
| // - "log" — preserve the historical no-op behaviour. Useful for | ||
| // debugging or in test environments where you want to observe the | ||
| // silent-death failure mode. | ||
| export type ReplicationErrorRecoveryStrategy = | ||
| | { | ||
| type: "reconnect"; | ||
| initialDelayMs?: number; | ||
| maxDelayMs?: number; | ||
| // 0 (or undefined) means retry forever. | ||
| maxAttempts?: number; | ||
| } | ||
| | { | ||
| type: "exit"; | ||
| exitDelayMs?: number; | ||
| exitCode?: number; | ||
| } | ||
| | { type: "log" }; | ||
|
|
||
| export type ReplicationErrorRecoveryDeps = { | ||
| strategy: ReplicationErrorRecoveryStrategy; | ||
| logger: Logger; | ||
| // Re-subscribe the underlying replication client. Implementations should | ||
| // call client.subscribe(...) and resolve once the stream is started. | ||
| reconnect: () => Promise<void>; | ||
| // True once the host service has begun graceful shutdown — recovery | ||
| // suppresses all work in that state. | ||
| isShuttingDown: () => boolean; | ||
| }; | ||
|
|
||
| export type ReplicationErrorRecovery = { | ||
| // Called from the replication client's "error" event handler. | ||
| handle(error: unknown): void; | ||
| // Called from the replication client's "start" event handler. Resets the | ||
| // reconnect attempt counter so the next failure starts from initialDelayMs. | ||
| notifyStreamStarted(): void; | ||
| // Cancel any pending reconnect/exit timer. Called from shutdown(). | ||
| dispose(): void; | ||
| }; | ||
|
|
||
| export function createReplicationErrorRecovery( | ||
| deps: ReplicationErrorRecoveryDeps | ||
| ): ReplicationErrorRecovery { | ||
| const { strategy, logger, reconnect, isShuttingDown } = deps; | ||
| let attempt = 0; | ||
| let pendingReconnect: NodeJS.Timeout | null = null; | ||
| let pendingExit: NodeJS.Timeout | null = null; | ||
| let exiting = false; | ||
|
|
||
| function scheduleReconnect(error: unknown): void { | ||
| if (strategy.type !== "reconnect") return; | ||
| if (pendingReconnect) return; | ||
|
|
||
| attempt += 1; | ||
| const maxAttempts = strategy.maxAttempts ?? 0; | ||
| if (maxAttempts > 0 && attempt > maxAttempts) { | ||
| logger.error("Replication reconnect exceeded maxAttempts; giving up", { | ||
| attempt, | ||
| maxAttempts, | ||
| error, | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| const initialDelay = strategy.initialDelayMs ?? 1_000; | ||
| const maxDelay = strategy.maxDelayMs ?? 60_000; | ||
| const delay = Math.min(initialDelay * Math.pow(2, attempt - 1), maxDelay); | ||
|
|
||
| logger.error("Replication stream lost — scheduling reconnect", { | ||
| attempt, | ||
| delayMs: delay, | ||
| error, | ||
| }); | ||
|
|
||
| pendingReconnect = setTimeout(async () => { | ||
| pendingReconnect = null; | ||
| if (isShuttingDown()) return; | ||
|
|
||
| try { | ||
| await reconnect(); | ||
| // Success path is handled by notifyStreamStarted, which fires from | ||
| // the replication client's "start" event after the stream is live. | ||
| } catch (err) { | ||
| // subscribe() can throw without first emitting an "error" event — | ||
| // notably when the initial pg client.connect() fails because Postgres | ||
| // is still unreachable mid-failover. Schedule the next attempt | ||
| // ourselves so recovery doesn't silently stop. If subscribe() did | ||
| // also emit an "error" event, handle() will call scheduleReconnect() | ||
| // first; the guard on pendingReconnect makes this idempotent. | ||
| logger.error("Replication reconnect attempt failed", { | ||
| attempt, | ||
| error: err, | ||
| }); | ||
| scheduleReconnect(err); | ||
| } | ||
| }, delay); | ||
| } | ||
|
|
||
| function scheduleExit(): void { | ||
| if (strategy.type !== "exit") return; | ||
| if (exiting) return; | ||
| exiting = true; | ||
|
|
||
| const delay = strategy.exitDelayMs ?? 5_000; | ||
| const code = strategy.exitCode ?? 1; | ||
|
|
||
| logger.error("Fatal replication error — exiting to let process supervisor restart", { | ||
| exitCode: code, | ||
| exitDelayMs: delay, | ||
| }); | ||
|
|
||
| pendingExit = setTimeout(() => { | ||
| // eslint-disable-next-line no-process-exit | ||
| process.exit(code); | ||
| }, delay); | ||
| // Don't hold a clean shutdown back on this timer. | ||
| pendingExit.unref(); | ||
| } | ||
|
|
||
| return { | ||
| handle(error) { | ||
| if (isShuttingDown()) return; | ||
| switch (strategy.type) { | ||
| case "log": | ||
| return; | ||
| case "exit": | ||
| return scheduleExit(); | ||
| case "reconnect": | ||
| return scheduleReconnect(error); | ||
| } | ||
| }, | ||
| notifyStreamStarted() { | ||
| if (attempt > 0) { | ||
| logger.info("Replication reconnect succeeded", { attempt }); | ||
| attempt = 0; | ||
| } | ||
| }, | ||
| dispose() { | ||
| if (pendingReconnect) { | ||
| clearTimeout(pendingReconnect); | ||
| pendingReconnect = null; | ||
| } | ||
| if (pendingExit) { | ||
| clearTimeout(pendingExit); | ||
| pendingExit = null; | ||
| } | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| // Shape of the env-driven configuration object the instance bootstrap files | ||
| // build from process.env. Kept separate from the strategy union above so the | ||
| // instance code can pass a single object regardless of which strategy is set. | ||
| export type ReplicationErrorRecoveryEnv = { | ||
| strategy: "reconnect" | "exit" | "log"; | ||
| reconnectInitialDelayMs?: number; | ||
| reconnectMaxDelayMs?: number; | ||
| reconnectMaxAttempts?: number; | ||
| exitDelayMs?: number; | ||
| exitCode?: number; | ||
| }; | ||
|
|
||
| export function strategyFromEnv( | ||
| env: ReplicationErrorRecoveryEnv | ||
| ): ReplicationErrorRecoveryStrategy { | ||
| switch (env.strategy) { | ||
| case "exit": | ||
| return { | ||
| type: "exit", | ||
| exitDelayMs: env.exitDelayMs, | ||
| exitCode: env.exitCode, | ||
| }; | ||
| case "log": | ||
| return { type: "log" }; | ||
| case "reconnect": | ||
| default: | ||
| return { | ||
| type: "reconnect", | ||
| initialDelayMs: env.reconnectInitialDelayMs, | ||
| maxDelayMs: env.reconnectMaxDelayMs, | ||
| maxAttempts: env.reconnectMaxAttempts, | ||
| }; | ||
| } | ||
| } | ||
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
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
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
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.