{"record":{"id":"55c65629ed8d8312","repo":"discordjs/discord.js","slug":"shardingprocessexists","errorCode":"ShardingProcessExists","errorMessage":"ShardingProcessExists","messagePattern":"ShardingProcessExists","errorType":"error_code","errorClass":"DiscordjsError","httpStatus":null,"severity":"error","filePath":"packages/discord.js/src/sharding/Shard.js","lineNumber":142,"sourceCode":"    /**\n     * Listener function for the {@link ChildProcess}' `exit` event\n     *\n     * @type {Function}\n     * @private\n     */\n    this._exitListener = null;\n  }\n\n  /**\n   * Forks a child process or creates a worker thread for the shard.\n   * <warn>You should not need to call this manually.</warn>\n   *\n   * @param {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready\n   * before resolving (`-1` or `Infinity` for no wait)\n   * @returns {Promise<ChildProcess>}\n   */\n  async spawn(timeout = 30_000) {\n    if (this.process) throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id);\n    if (this.worker) throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id);\n\n    this._exitListener = this._handleExit.bind(this, undefined, timeout);\n\n    switch (this.manager.mode) {\n      case 'process':\n        this.process = childProcess\n          .fork(path.resolve(this.manager.file), this.args, {\n            env: this.env,\n            execArgv: this.execArgv,\n            silent: this.silent,\n          })\n          .on('message', this._handleMessage.bind(this))\n          .on('exit', this._exitListener);\n        break;\n      case 'worker':\n        this.worker = new Worker(path.resolve(this.manager.file), {\n          workerData: this.env,","sourceCodeStart":124,"sourceCodeEnd":160,"githubUrl":"https://github.com/discordjs/discord.js/blob/a81ed8a306d37fdc746e26a634b6a42164ba2c8c/packages/discord.js/src/sharding/Shard.js#L124-L160","documentation":"ShardingProcessExists is thrown by Shard.spawn() when a shard already has a live child process attached (this.process is set). discord.js guards spawn() to prevent launching a second ChildProcess for the same shard, which would orphan the first and corrupt manager state. Each Shard must have at most one process in 'process' mode.","triggerScenarios":"Calling manager.spawn() or shard.spawn() while the shard's process is already running; calling spawn() again after a previous spawn() resolved without the process exiting; manually invoking respawn() concurrently with spawn() so both pass the guard check in a race.","commonSituations":"Double-invoking ShardingManager.spawn() (e.g., an init routine running twice on hot reload); awaiting respawn() while the old process has not fully exited; custom orchestration code calling spawn() per shard inside an interval without checking shard.process.","solutions":["Check shard.process is null/undefined before calling spawn(), or rely on manager.spawn() which skips already-spawned shards","Use await shard.respawn() instead of a raw spawn() when you intend to restart - it kills the existing child first","Ensure the previous spawn()/process exit is fully awaited before re-spawning (await the promise, don't fire-and-forget)","If the process handle is stale after a crash, remove the exit listener and set shard.process = null before respawning"],"exampleFix":"// before\nfor (const shard of manager.shards) {\n  shard.spawn(); // throws ShardingProcessExists on running shards\n}\n// after\nfor (const shard of manager.shards) {\n  if (!shard.process) await shard.spawn();\n}","handlingStrategy":"validation","validationCode":"function canSpawn(shard) { return shard.process == null && shard.worker == null; }\nif (canSpawn(shard)) await shard.spawn();","typeGuard":"function isSpawnable(shard) { return !('process' in shard && shard.process) && !('worker' in shard && shard.worker); }","tryCatchPattern":"try {\n  await shard.spawn();\n} catch (err) {\n  if (err.code === 'ShardingProcessExists' || err.name === 'DiscordjsError' && /ShardingProcessExists/.test(err.message)) {\n    return shard.process; // already running\n  }\n  throw err;\n}","preventionTips":["Prefer manager.spawn() / shard.respawn() over raw spawn() for restarts","Guard with shard.process/shard.worker checks before spawning","Never spawn the same ShardingManager from two code paths","Track spawn state in your own orchestrator and treat spawn as idempotent"],"tags":["sharding","discordjs","process-lifecycle","double-spawn"],"backgroundTag":"already-spawned-shard","analyzedSha":"a81ed8a306d37fdc746e26a634b6a42164ba2c8c","analyzedAt":"2026-08-30T04:07:22.193Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}