Skip to content

WorkerManager

Signature

export declare class WorkerManager extends Map<number, ManagedWorker>

Private types

ManagedWorkerTypeAlias
type ManagedWorker = (ClusterWorker | WorkerThreadsWorker | {    ready?: boolean;}) & WorkerState;
WorkerManagerRuntimeOptionsTypeAlias
WorkerManagerConstructorOptionsTypeAlias
type WorkerManagerConstructorOptions = WorkerManagerOptions extends infer Options ? Options extends WorkerManagerOptions ? Omit<Options, WorkerManagerConstructorOptionalKeys | 'resharding'> & Partial<Pick<Options, WorkerManagerConstructorOptionalKeys>> & {    resharding?: PickPartial<NonNullable<WorkerManagerOptions['resharding']>, 'getInfo'>;} : never : never;
CustomWorkerTypeAlias
type CustomWorker = {    ready?: boolean;} & WorkerState;
WorkerStateTypeAlias
type WorkerState = {    ready?: boolean;    disconnected?: boolean;    resharded?: boolean;};
WorkerManagerNativeOptionsTypeAlias
type WorkerManagerNativeOptions = Exclude<WorkerManagerOptions, {    mode: 'custom';}>;
WorkerManagerRuntimeOptionalKeysTypeAlias
type WorkerManagerRuntimeOptionalKeys = 'adapter' | 'handleWorkerMessage' | 'handlePayload' | 'getRC' | 'workerEnv';
WorkerManagerCustomOptionsTypeAlias
type WorkerManagerCustomOptions = Extract<WorkerManagerOptions, {    mode: 'custom';}>;
WorkerManagerCustomRuntimeOptionalKeysTypeAlias
type WorkerManagerCustomRuntimeOptionalKeys = 'handleWorkerMessage' | 'handlePayload' | 'getRC' | 'workerEnv';
WorkerManagerConstructorOptionalKeysTypeAlias
type WorkerManagerConstructorOptionalKeys = 'token' | 'intents' | 'info' | 'handlePayload' | 'handleWorkerMessage';

Properties

promises: Map<string, {    resolve: (value: any) => void;    timeout: NodeJS.Timeout;}>;
private generations;

The instance each worker id currently routes to; unset means generation 0.

private standbyWorkers;

Replacements still connecting and workers draining after a hot reload, by `workerId:generation`.

private switchingWorkerId?;

The worker being switched by a hot reload; heartbeat respawns leave it alone meanwhile.

private allWorkersReady;

Set once BOT_READY was sent; hot reload waits for it.

private launchWorker;

Starts a worker process for `workerData` without registering it as the active worker. Custom workers are tracked before their adapter spawns them, so messages sent while spawning already find their entry.

Methods

static prepareSpaces(options: {    shardStart: number;    shardEnd: number;    shardsPerWorker: number;}, logger?: Logger): number[][];
setCache(adapter: Adapter): void;

Configure the backend before starting workers; optional cache capabilities are negotiated at worker startup.

syncLatency({ shardId, workerId, }: {    shardId: number;    workerId?: number;} | {    shardId?: number;    workerId: number;}): Promise<number>;
prepareWorkers(shards: number[][], rawResharding?: boolean): void;
spawn(workerId: number, shardId: number, resharding?: boolean, generation?: number): Promise<void>;

Queues a shard connection for a worker. `generation` targets a specific worker instance, such as a hot reload replacement; it defaults to the instance active when the connection is queued.

handleWorkerMessage(message: WorkerMessages, generation?: number): Promise<void>;

Handles a message from a worker. `generation` identifies the instance that sent it (see {@link CustomManagerAdapter.postMessage }); when omitted the message is treated as coming from the active instance. Replies go back to the instance that sent the request.

hotReload(options?: HotReloadOptions): Promise<HotReloadResult>;

Replaces running workers with freshly spawned ones that load all code from disk again, one worker at a time, while each replacement prepares. The manager process itself is not reloaded. For each worker, a replacement with the same id and shards identifies new gateway sessions (through the connect queue, with the configured presence) and builds its cache while the old worker keeps handling everything. Once all of its shards are ready, the old worker stops handling events and the replacement starts; its skipped `ready`, `workerShardsConnected`, `workerReady` and, on the first worker, `botReady` handlers run then. The old worker finishes in-flight work for up to `drainTimeout`, requests normal (1000) shard closure and exits. This is a best-effort rolling restart. Independent gateway sessions can lose or duplicate events around the switch, including cache updates. It provides no lossless or exactly-once delivery guarantee, as with resharding. Applications that require those guarantees must not rely on hot reload for them. If a replacement crashes, fails to load or is not ready within `readyTimeout`, it is stopped and the old worker keeps running untouched; the reload then stops unless `continueOnError` is set. The replacement is built from the manager's configuration: it identifies with the configured presence, so a presence set at runtime is reset, and it connects the worker's configured shards, not ones added at runtime. Collectors, cooldowns and other application state in the old process are not transferred. Each replacement identifies new sessions and consumes the gateway session-start allowance. A memory cache belongs to its worker, so the replacement builds its own. Any other adapter is treated as shared and is left to the active worker: the replacement doesn't write to it until it takes over, and the old worker stops admitting new dispatches once it is replaced; already accepted work may still finish while draining. Plugin setup, dispatch interceptors and cache adapter startup run during preparation. Event handlers, collectors and the user handlePayload hook wait for activation. Plugin teardown is attempted after draining before normal shard close requests and termination; the manager's retirement deadline still applies. Custom mode needs an adapter that implements {@link CustomManagerAdapter.terminate } and routes messages by generation. The replacement is a whole new process or thread, so it also runs the app's own startup while it prepares next to the old worker: services, timers, database or Redis subscribers, anything started before or around `client.start()`. Work that must not run twice, like answering requests or background jobs, should check `client.hotReloadState` or `client.isHotReloadReplacement`, or start and stop in the `hotReload` client hooks (`onStandby`, `onActivate`, `onStop`, `onDrain`; see `WorkerHotReloadHooks`). The old and replacement workers can run their hooks concurrently. Jobs that require one owner across workers need app-level coordination. In `'clusters'` mode a drained worker ends with `worker.kill()`, which disconnects it and sends SIGTERM; the process often exits on the disconnect before a SIGTERM handler runs, and on Windows it is terminated outright. Shutdown work for a hot reload, such as final saves, belongs in `onDrain`. An app's own SIGTERM or exit handlers that announce a restart should check `client.hotReloadState === 'stopped'` and skip that, since the bot isn't going down. With `trackMemberCount`, a replacement with its own memory cache takes each guild's member count from the GUILD_CREATE it receives when it connects; a shared cache keeps the counts the active worker maintains.

Examples
const client = new WorkerClient({
	hotReload: {
		// The replacement starts its jobs once it handles events, and so does an old worker taking them back.
		onActivate: () => jobs.start(),
		onStop: () => jobs.stop(),
		// Awaited up to drainTimeout while REST still works.
		onDrain: () => players.saveAll(),
	},
});
// A worker started normally runs its jobs right away; a replacement waits for onActivate.
if (!client.isHotReloadReplacement) jobs.start();
process.on('SIGTERM', async () => {
	// Retired by a hot reload, not a real shutdown: its saves already ran in onDrain.
	if (client.hotReloadState !== 'stopped') await announceRestart();
	process.exit(0);
});
@throws{SeyfertError} `HOT_RELOAD_IN_PROGRESS` while another reload runs, `HOT_RELOAD_UNSUPPORTED` before every worker is ready (BOT_READY), during resharding, or in custom mode without `terminate`, and `WORKER_NOT_FOUND` for an unknown worker id.
handleWorkerExit(workerId: number, generation: number, error?: unknown): void;

Reports that a worker instance exited. A hot reload replacement that exits before it takes over fails its reload. Thread and cluster workers are watched automatically; custom adapters call this themselves.