{"record":{"id":"681e1310cafb171e","repo":"mastra-ai/mastra","slug":"backgroundtaskmanager-is-shutting-down-cannot-enq","errorCode":null,"errorMessage":"BackgroundTaskManager is shutting down, cannot enqueue new tasks","messagePattern":"BackgroundTaskManager is shutting down, cannot enqueue new tasks","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/core/src/background-tasks/manager.ts","lineNumber":274,"sourceCode":"\n  /**\n   * Look up an executor by tool name. Read by the workflow-step body in\n   * `workflow.ts:runAttemptStep` as a fallback when no per-task `TaskContext`\n   * is registered (cross-process path).\n   */\n  getStaticExecutor(toolName: string): ToolExecutor | undefined {\n    return this.staticExecutors.get(toolName);\n  }\n\n  // --- Core operations ---\n\n  /**\n   * Enqueue a task for background execution.\n   * Prefer `createBackgroundTask()` which returns a self-contained handle.\n   */\n  async enqueue(payload: TaskPayload, context?: TaskContext): Promise<EnqueueResult> {\n    if (this.shuttingDown) {\n      throw new Error('BackgroundTaskManager is shutting down, cannot enqueue new tasks');\n    }\n\n    // Mastra fires `init` as fire-and-forget. If a caller hits enqueue\n    // before init completes, the dispatch publish fires before the worker\n    // subscribes and the event is dropped (or, worse, lands on a worker\n    // whose Mastra hasn't yet registered the bg-task workflow → \"Workflow\n    // with id __background-task not found\"). Await readiness up front.\n    if (this.initPromise) await this.initPromise;\n\n    const task: BackgroundTask = {\n      id: this.#mastra?.generateId() ?? randomUUID(),\n      status: 'pending',\n      toolName: payload.toolName,\n      toolCallId: payload.toolCallId,\n      args: payload.args,\n      agentId: payload.agentId,\n      threadId: payload.threadId,\n      resourceId: payload.resourceId,","sourceCodeStart":256,"sourceCodeEnd":292,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/background-tasks/manager.ts#L256-L292","documentation":"enqueue() rejects new work when the manager is shutting down. During shutdown the pubsub subscriptions and workers are being torn down, so a newly enqueued task would never be dispatched. The library fails fast rather than silently dropping the task.","triggerScenarios":"Calling manager.enqueue() (directly or via createBackgroundTask) after shutdown() started; a task tool executing concurrently with process shutdown; graceful-drain logic overlapping with new agent/tool calls.","commonSituations":"Load balancer still routing requests during SIGTERM drain; long-running agent loops scheduling background tasks while the server deploys; dev hot reloads triggering shutdown while a request is in flight.","solutions":["Check manager.shuttingDown before enqueueing and fall back to synchronous tool execution.","Add readiness gating: stop accepting requests (return 503) before calling shutdown().","Retry after redeploy/restart, or persist the task externally and enqueue post-restart.","Await in-flight createBackgroundTask dispatches in your shutdown handler before tearing down."],"exampleFix":"// before\nawait manager.shutdown();\nawait manager.enqueue(payload); // throws\n// after\nif (!manager.shuttingDown) {\n  await manager.enqueue(payload);\n} else {\n  const result = await tool.execute(payload); // fallback sync\n}","handlingStrategy":"fallback","validationCode":"if (manager.shuttingDown) {\n  return syncExecuteTask(task); // run inline instead of enqueueing\n}","typeGuard":null,"tryCatchPattern":"try {\n  return await manager.enqueue(payload);\n} catch (e) {\n  if ((e as Error).message.includes('shutting down, cannot enqueue')) {\n    return tool.execute(payload); // fallback to sync\n  }\n  throw e;\n}","preventionTips":["Stop intake (503/readiness off) before calling shutdown().","Check manager.shuttingDown before every enqueue.","Fallback to synchronous tool execution during drain.","In shutdown handlers, await in-flight task creations first."],"tags":["background-tasks","shutdown","backpressure"],"backgroundTag":"manager-already-shutting-down","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}