rollstarts
v1.2.0
Published
A simple Node.js package to implement zero-downtime rolling restarts within your application.
Maintainers
Readme
rollstarts
rollstarts preloads a replacement Node.js process before retiring the process that is currently serving traffic. It is designed for applications with expensive startup work and a small set of exclusive resources—such as a listening port or WebSocket connection—that must never be owned by two processes at once.
The public API remains deliberately small: master(), start(), ready(), restart(), and exit().
Automatic file watching is disabled by default. Set watch: true explicitly when file-change restarts are desired.
Installation
npm install rollstartsQuick start
Use the same entry file for the manager and the application. Perform slow, non-contending initialization before ready(), and claim ports or other exclusive resources only after it resolves.
const http = require('node:http');
const rollstarts = require('rollstarts');
async function main() {
if (rollstarts.master()) {
const manager = await rollstarts.start({
path: __filename,
recover: true,
});
manager.on('active', (child) => {
console.log(`Process ${child.pid} is active`);
});
manager.on('error', console.error);
return;
}
// Expensive work that can safely overlap with the currently active process.
const application_state = await load_application_state();
// On a rolling restart, this resolves only after the old process has exited.
await rollstarts.ready();
const server = http.createServer((request, response) => {
response.end(JSON.stringify(application_state));
});
server.listen(3000);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});Call rollstarts.restart() from an active child when configuration or application state requires a refresh:
async function restart_after_refresh() {
await refresh_configuration();
rollstarts.restart();
}Handoff lifecycle
A rolling restart follows this sequence:
- The manager spawns a replacement while the current child continues serving.
- The replacement loads data and performs other non-contending initialization.
- The replacement calls
await RollStarts.ready()and pauses. - The manager sends
SIGTERMto the old child and waits for itsexitevent. - If the old child does not exit within
shutdown_timeout_ms, the manager sendsSIGKILL. - Only after the old PID has exited does the manager release the replacement's
ready()promise. - The replacement can now bind ports, open exclusive connections, and serve traffic.
Concurrent calls to manager.restart() return the same in-flight promise. File changes received during a restart are coalesced into one follow-up restart, so an edit is not silently lost while a replacement is loading.
The initial child has no predecessor, so its ready() resolves as soon as its readiness message has been sent.
Graceful shutdown
Node exits on SIGTERM by default. If the application installs its own signal handler, that handler must eventually exit:
process.on('SIGTERM', () => {
server.close(() => process.exit(0));
});The manager force-kills an old process that outlives shutdown_timeout_ms. Set that value high enough for the application's normal cleanup path.
Options
| Option | Default | Description |
| --- | ---: | --- |
| path | required | Root JavaScript file to watch and, by default, execute. |
| watch | false | Restart when path changes. Watching is opt-in. |
| recover | true | Automatically replace an unexpectedly exited active process. |
| recover_attempts | 100 | Maximum consecutive automatic recovery attempts. 0 disables retries. |
| recover_ttl_ms | 1000 | Time a child must remain active before the recovery-attempt budget resets. |
| ipc_timeout_ms | 5000 | Timeout for an individual manager/child IPC operation. |
| shutdown_timeout_ms | 5000 | Grace period between SIGTERM and SIGKILL during handoff. |
| startup_timeout_ms | 0 | Maximum time for a child to call ready(). 0 allows unbounded preload time. |
| command | "node" | Executable used to launch a child. |
| args | [path] | Full argument array for command; supplying it replaces the default. |
| options | {} | Options passed to child_process.spawn(). |
The child must have an IPC channel. The default stdio value is ['inherit', 'inherit', 'inherit', 'ipc']. If options.stdio is supplied, it must include 'ipc' exactly once. options.env is merged over the manager environment; Rollstarts' private coordination variables are always set by the manager.
startup_timeout_ms is disabled by default because long preload work is the primary use case. Set it in production if a child that never reaches ready() should be considered failed.
API
rollstarts.master(): boolean
Returns true in the manager process and false in a managed child. Use it before calling start().
rollstarts.start(options): Promise<RollStartsManager>
Validates options.path, constructs a manager, and begins the initial child launch. The promise resolves with the manager immediately; it does not wait for the child to become active. When enabled, watching begins after a child first becomes active. Observe the manager's active event when readiness matters.
rollstarts.ready(): Promise<void>
Called by a managed child after preload work. In a recurring child it resolves only after the previous child exits and the manager authorizes this child to serve. Calls from the manager process reject.
rollstarts.restart(): void
Requests a rolling restart from a managed child. Calls from the manager process throw. Manager-side code should use manager.restart() instead.
rollstarts.exit(code?): void
Requests termination of the manager and all managed children. Calls from the manager process throw. The default exit code is 0.
manager.restart(): Promise<void>
Starts a rolling restart, or returns the existing promise if one is already running. It resolves after the replacement has been authorized to serve and rejects if that replacement fails. A failed replacement does not stop a healthy active process.
manager.watch(): Promise<fs.FSWatcher | void>
Starts the configured file watcher, returns the existing watcher if already active, or returns undefined when watching is disabled.
manager.destroy(): void
Idempotently closes the watcher, disables recovery, and sends SIGTERM to managed children. A restart pending at destruction is rejected.
manager.active and manager.in_flight
active is the currently serving ChildProcess, or null. in_flight is true while a replacement is starting or while the old child is shutting down.
Manager events
| Event | Arguments | Meaning |
| --- | --- | --- |
| active | (child) | A child has been authorized to serve. |
| exit | (child, code) | A managed child exited. Signal exits have a null code; inspect child.signalCode when needed. |
| recover | (attempts_remaining) | An unexpected exit entered the recovery path or exhausted its budget. |
| error | (error) | A watcher, spawn, IPC, or internally requested restart failed. |
Attach an error listener. Like other Node.js EventEmitter instances, an unhandled error event terminates the process.
Recovery behavior
Recovery is limited to unexpected loss of service:
- If a replacement fails before handoff, the healthy active child remains in place and the explicit restart promise rejects.
- If the active child dies while a replacement is already loading, that replacement continues and becomes the recovery path.
- If a replacement dies after the old child has begun shutting down, recovery starts after the old child exits.
- Each automatic spawn consumes one recovery attempt. The budget resets only after the current child remains active for
recover_ttl_ms. destroy()androllstarts.exit()disable recovery before terminating children.
Testing
The test suite uses real child processes and IPC rather than mocked process objects:
npm testIt covers initial startup, duplicate restart requests, strict exit-before-serve ordering, graceful and forced shutdown, failed replacements, handoff races, recovery exhaustion and TTL reset, startup timeout, file-watch coalescing, child-requested restart, and full application exit.
License
MIT
