{"slug": "building-a-parallel-incident-investigation-system-with-upstash-box", "title": "Building a Parallel Incident Investigation System with Upstash Box.", "summary": "A developer built a parallel incident investigation system that gives each AI agent its own isolated execution environment, using Upstash Box for sandboxed containers and Upstash QStash for asynchronous job dispatch. Each Box runs an agent harness (Codex with an OpenAI model) that inspects logs, metrics, traces and code, then returns a structured report, letting multiple investigations run concurrently without interfering. The full implementation is published on GitHub.", "body_md": "When an incident happens in distributed systems, figuring out what went wrong can involve looking at several different things. You might need to inspect application logs, check metrics, follow traces across services, and compare what you find against the relevant parts of the codebase.\n\nThe challenge is that this investigation is not always straightforward. Different incidents require different evidence, and investigating multiple incidents at the same time introduces another problem: how do you run these investigations independently without having them interfere with one another?\n\nI wanted to explore what this could look like with AI agents. Rather than having an agent run inside the main application, I wanted each investigation to have its own execution environment. That environment would have access to the evidence required for the investigation, perform its analysis, and return a structured report.\n\nBuilding this required solving two related problems: providing isolated environments in which the agents could execute, and reliably dispatching investigation jobs to those environments.\n\nThis is where [Upstash Box](https://upstash.com/docs/box/overall/quickstart?utm_source=abdulrahmon-adenuga) and [Upstash QStash](https://upstash.com/docs/qstash?utm_source=abdulrahmon-adenuga) come in. Box provides the execution environment for each investigation, while QStash handles the asynchronous delivery of investigation jobs.\n\nIn this article, I'll walk through how I put these pieces together to build a parallel incident investigation system within a microservice architecture. The complete implementation is available in the [GitHub repository](https://github.com/Rahmannugar/incident-system). We'll look at how individual investigations execute, how they access operational evidence, and how the distributed application coordinates multiple investigations.\n\n[Upstash Box](https://upstash.com/docs/box/overall/quickstart?utm_source=abdulrahmon-adenuga)provides cloud-based execution environments that applications can create and manage programmatically. Each Box runs as an isolated cloud container with its own filesystem, process tree, and network stack. Instead of running commands, tools, and agent processes inside the application server, we can provision a separate environment for that work and interact with it remotely.\n\nThis distinction becomes important when working with AI agents.\n\nAn AI model can reason about a problem, decide which tools to use, and determine what information it needs. However, reasoning alone does not give the model access to a filesystem, a terminal, or the ability to execute commands. Those capabilities require an execution environment.\n\nThis is the role Box plays. It gives an agent an environment where it can execute commands, inspect files, use available tools, and perform the work required by a task. The application remains responsible for creating the environment, providing the necessary inputs, and collecting the result.\n\nIt helps to separate the different responsibilities involved:\n\nThese responsibilities work together, but they are not the same thing. Box does not replace the model, and the model does not provide the execution environment.\n\nUpstash also provides built-in agent support, which allows an agent harness to run within a Box rather than requiring us to build the entire execution loop ourselves. In our implementation, we use the built-in Codex harness with an OpenAI model.\n\nYou can read more about Box's [execution model](https://upstash.com/docs/box/overall/how-it-works?utm_source=abdulrahmon-adenuga) and [built-in agent support](https://upstash.com/docs/box/overall/agent?utm_source=abdulrahmon-adenuga).\n\nBefore looking at agent execution, let's see what creating a Box looks like.\n\nThe `@upstash/box` SDK provides the `Box.create()` method. We can configure the execution environment, give it a name, select its runtime and size, and define its network policy.\n\nHere is the creation call used in our implementation, with the configuration values supplied by the application:\n\n``` js\nconst box = await Box.create({\n  ...connection,\n  name: input.resource.name,\n  labels: [input.resource.label],\n  runtime: 'node',\n  size: 'small',\n  timeout: 20000,\n  networkPolicy: {\n    mode: 'custom',\n    allowedDomains: [\n      'upstash.com',\n      ...(input.resource.evidenceOrigin\n        ? [new URL(input.resource.evidenceOrigin).hostname]\n        : []),\n      ...(input.agentModel ? ['api.openai.com'] : []),\n    ],\n  },\n  ...(input.agent\n    ? {\n        agent: {\n          harness: Agent.Codex,\n          model: input.agent.model,\n          apiKey: input.agent.apiKey,\n        },\n      }\n    : {}),\n});\n```\n\nThere are a few things worth pointing out here.\n\nFirst, `runtime` specifies the runtime available inside the Box. In this case, we use Node.js. This does not mean the application creating the Box must itself run inside Node.js. The application is simply communicating with the Box SDK and managing the remote environment.\n\nSecond, the `size` determines the resources allocated to the environment, while `timeout` bounds the SDK creation operation. The network policy also allows us to control which domains the environment can reach. Rather than giving every Box unrestricted outbound access, we explicitly configure the domains required for its work.\n\nFinally, notice the `agent` configuration. This is where we select the agent harness, model and API key. We use Codex as the harness and an OpenAI model for reasoning. The distinction matters: Box provides the execution environment, Codex provides the agent harness, and the model provides the reasoning capability.\n\nOnce the Box has been created and configured with an agent, we can execute a task through its agent interface.\n\nIn our implementation, the agent execution looks like this:\n\n``` js\nconst run = await box.agent.run({\n  prompt: investigationPrompt(input.input),\n  responseSchema: agentReportSchema,\n  timeout: 90000,\n  maxRetries: 0,\n  options: {\n    modelReasoningEffort: 'low',\n    webSearch: false,\n  },\n  onToolUse: () => {\n    tools++;\n\n    if (tools > agentToolObservationLimit) {\n      throw new BoxError('Agent tool observation limit reached');\n    }\n  },\n});\n```\n\nThe `prompt` contains the task instructions and the context available to the agent. `responseSchema` defines the expected structure of the result, allowing the SDK to work with structured output rather than an unrestricted text response.\n\nWe also configure an execution timeout and observe tool usage through `onToolUse`. In this implementation, the callback enforces an application-level limit on the number of observed tool uses.\n\nThe important part is that we are not implementing our own model interaction loop or manually coordinating every tool call. The built-in agent harness handles that execution within the Box.\n\nSeparate execution environments are useful whenever an application needs to run work that should not share the same execution context as its main processes.\n\nFor example, consider a platform that allows users to submit code for execution. Running arbitrary user code directly inside the application server would introduce unnecessary risks and resource contention. A separate environment provides a boundary in which that code can execute without sharing the application's own process environment.\n\nThe same idea applies to data processing jobs, automated testing, code analysis, build processes, and AI agents that need access to terminals and filesystems. Each task can have its own environment, dependencies, configuration and lifecycle.\n\nThis also changes how we think about resource management. Instead of maintaining long-running execution processes for work that may only happen occasionally, an application can create an environment when the work is needed, use it, collect the result, and clean it up afterwards.\n\nFor workloads that involve multiple independent tasks, separate environments also provide a foundation for running those tasks concurrently without forcing them to share one execution environment.\n\nThe system is built around a small commerce application consisting of independent services. It simulates a typical order lifecycle, from customer authentication and stock reservation to order processing, payment, and notifications. The complete implementation is available in the [GitHub repository](https://github.com/Rahmannugar/incident-system).\n\nThe Gateway serves as the entry point for customer requests. When a customer creates an order, the Gateway authenticates the request, generates an order ID, and coordinates with Inventory to reserve the requested items. Once the reservation succeeds, it sends the order details to the Order service.\n\nThe Order service creates the pending order and writes an event to its transactional outbox. Its publisher picks up the event and publishes it to [Upstash QStash](https://upstash.com/docs/qstash?utm_source=abdulrahmon-adenuga), which delivers it to the Payment service for processing.\n\nPayment processing is mocked in the application. The Payment service processes the request, records the payment attempt, and publishes the resulting payment event.\n\nAlongside the commerce services, we have an Incident Service responsible for receiving alerts, creating investigations, coordinating their execution, and storing the resulting reports.\n\nThe application is instrumented with OpenTelemetry to collect distributed traces, metrics, and logs across the services. We use Prometheus for metrics, Loki for logs, and Tempo for traces. Grafana uses these data sources to evaluate alert rules and send notifications when configured conditions are met.\n\nFor testing the investigation workflow, we implemented scenarios that introduce real failures into the running application. These scenarios allow us to observe the resulting errors and collect the metrics, logs, and traces generated across the affected services.\n\nNow that we understand how the application works, let's look at how an incident moves through the investigation system.\n\nThe workflow starts when Grafana detects an issue in one of the services. For example, a sudden increase in request latency or repeated request failures can trigger an alert. Grafana sends an alert webhook to the Incident service. When it receives the webhook, the Incident service creates an incident, an investigation, and an outbox entry for the investigation job.\n\nAn outbox publisher picks up the pending job and publishes it to [Upstash QStash](https://upstash.com/docs/qstash?utm_source=abdulrahmon-adenuga). QStash then delivers the message to the Incident service's signed receiver.\n\nThe receiver verifies the message and records the delivery before acknowledging it. From there, the application coordinates the investigation execution.\n\nFor each investigation attempt, the application provisions a dedicated [Upstash Box](https://upstash.com/docs/box/overall/quickstart?utm_source=abdulrahmon-adenuga). The agent runs inside that Box with the investigation instructions, the required tools, and access to the operational evidence relevant to the incident.\n\nThe evidence comes from the application's observability infrastructure. Depending on the investigation's scope, the agent can inspect metrics, logs, traces, and relevant source files and runbooks. It uses this information to build a timeline of events, identify observations, and develop possible explanations for the incident.\n\nEach investigation runs independently in its own Box. This allows the application to execute multiple investigations concurrently without sharing the same agent execution environment.\n\nWhen the agent finishes, it submits a structured report through the application's callback endpoint. The Incident service validates the report and its evidence references before storing it.\n\nThe report contains a summary, timeline, observations, findings, possible cause, alternative explanations, confidence level, and limitations. The application then makes the persisted report available through its API.\n\nAfter a successful investigation, the application also cleans up the Box used for that attempt and releases the resources associated with it.\n\nThe overall flow looks like this:\n\n``` php\nflowchart TD\n    A[\"Application failure\"] --> B[\"Grafana alert\"]\n    B --> C[\"Incident Service\"]\n    C --> D[\"Create incident and investigation\"]\n    D --> E[\"Transactional outbox\"]\n    E --> F[\"Upstash QStash\"]\n    F --> G[\"Signed message receiver\"]\n    G --> H[\"Provision Upstash Box\"]\n    H --> I[\"Run investigation agent\"]\n    I --> J[\"Inspect operational evidence\"]\n    J --> K[\"Submit structured report\"]\n    K --> L[\"Validate and persist report\"]\n    L --> M[\"Clean up Box\"]\n    L --> N[\"Report available through API\"]\n```\n\nThis is the complete path from an alert to an investigation report. The following sections will look at how we prepare the execution environment, dispatch jobs, provide evidence to agents, and coordinate multiple investigations.\n\nBefore an investigation agent starts working, we need to prepare the information it will use. The agent needs more than an incident description. It needs enough context about the affected services, relevant source files, and operational runbooks to investigate what happened.\n\nWe maintain an allowlist of source files and runbooks that can be included in an investigation. Each document is associated with the services it relates to, allowing us to select the relevant documents based on the investigation scope.\n\nFor example, our allowlist includes entries like these:\n\n``` js\nconst allowlist = [\n  {\n    path: 'runbooks/payment-timeouts.md',\n    kind: 'runbook',\n    services: ['gateway', 'identity', 'order', 'payment'],\n  },\n  {\n    path: 'runbooks/outbox-delivery.md',\n    kind: 'runbook',\n    services: ['order', 'payment', 'notification'],\n  },\n  {\n    path: 'apps/payment/src/payments/payments.repository.ts',\n    kind: 'source',\n    services: ['payment'],\n  },\n  {\n    path: 'apps/payment/src/payments/payments.sql',\n    kind: 'source',\n    services: ['payment'],\n  },\n  {\n    path: 'apps/order/internal/orders/outbox.publisher.go',\n    kind: 'source',\n    services: ['order'],\n  },\n];\n```\n\nEach entry identifies a document, its type, and the services it relates to.\n\nWhen an investigation is created, we use its service scope to select the relevant entries from this allowlist. For example, if an investigation covers Gateway and Payment, we include documents associated with either of those services.\n\nWe also narrow down the service list attached to each selected document so that it only contains services covered by the investigation:\n\n``` js\nconst selectedDocuments = allowlist\n  .filter(entry =>\n    entry.services.some(service =>\n      scopeServices.includes(service)\n    )\n  )\n  .map(entry => ({\n    ...entry,\n    services: entry.services.filter(service =>\n      scopeServices.includes(service)\n    ),\n  }));\n```\n\nThe first filter selects the documents that are relevant to the investigation. The second filter narrows the service associations of each selected document to the investigation scope.\n\nThe worker reads these selected files from the repository's local working tree and calculates a SHA-256 hash for each file:\n\n``` js\nconst sha256 = createHash('sha256')\n  .update(buffer)\n  .digest('hex');\n```\n\nWe include the hash in the document reference so that the application can identify the exact contents prepared for the investigation:\n\n``` js\nconst document = {\n  path: entry.path,\n  kind: entry.kind,\n  services: entry.services,\n  sha256,\n  bytes: buffer.length,\n  ref: `sha256:${sha256}:${entry.path}`,\n  content,\n};\n```\n\nThese references are also used when the files are copied into the Box. The Box verifies the copied runbooks against their expected hashes before allowing the agent to start. If a hash does not match, preparation fails with a `Runbook identity mismatch` error.\n\nWe also keep the document collection bounded: individual documents cannot exceed 32 KB, and the complete catalog cannot exceed 64 KB.\n\nOnce prepared, the documents are copied into the Box workspace. The agent does not need to fetch the repository or access Git to inspect the relevant source files.\n\nWe also prepare the information that identifies the investigation and defines what the agent is allowed to inspect.\n\nThis includes:\n\nThe service scope and observation window define the boundaries of each investigation. They determine which services the agent can inspect and the period of telemetry it should examine.\n\nWe pass this information to the agent as part of its investigation input:\n\n``` js\nconst input = {\n  scope: {\n    incidentId: claim.incidentId,\n    investigationId: claim.investigationId,\n    services: evidenceScope.services,\n    window: {\n      start: evidenceScope.window.start.toISOString(),\n      end: evidenceScope.window.end.toISOString(),\n    },\n    summary: incident.summary,\n  },\n  model: agent.model,\n};\n```\n\nThe agent also receives instructions describing how to approach the investigation, which prepared files to inspect, how to reference evidence, and the expected report structure.\n\nWe use the built-in Codex harness inside Box with the configured OpenAI model. The agent is instructed to investigate using read-only evidence. It cannot remediate services, query application databases directly, fetch Git, or install additional packages.\n\nAt this point, the execution environment has its runtime, agent configuration, investigation context, and the source documents prepared for the task. The operational telemetry is made available through a separate evidence-access mechanism, which we'll examine later.\n\nThis gives us a consistent starting environment for each investigation, with the files and context prepared according to its scope.\n\n[Upstash QStash](https://upstash.com/docs/qstash?utm_source=abdulrahmon-adenuga) is a messaging platform that delivers messages to HTTP endpoints. It supports asynchronous delivery, retries, request signing, and message deduplication.\n\nIn our application, we integrated QStash to handle the dispatch of investigation jobs from the Incident service to its worker endpoint. The worker could also have picked up pending jobs directly and initiated the investigations. We chose to introduce QStash so we could explore how it fits into this workflow and use its message delivery capabilities.\n\nWhen Grafana sends an alert, the Incident service creates the incident, investigation, and corresponding outbox entry in a database transaction.\n\nThe outbox entry contains the information needed to dispatch the investigation. We use a versioned job structure:\n\n```\ninterface InvestigationJob {\n  id: string;\n  type: 'investigation.requested';\n  version: 1;\n  incident_id: string;\n  investigation_id: string;\n  occurred_at: string;\n  traceparent?: string;\n}\n```\n\nA separate publisher process claims pending outbox entries and publishes them to QStash through its HTTP API. We use the `/v2/batch` endpoint to publish multiple jobs in a single request.\n\n``` js\nconst response = await fetch(\n  `${config.baseURL}/v2/batch`,\n  {\n    method: 'POST',\n    headers: {\n      Authorization: `Bearer ${config.token}`,\n      'Content-Type': 'application/json',\n    },\n    body: JSON.stringify(messages),\n    redirect: 'error',\n    signal: AbortSignal.any([\n      signal,\n      AbortSignal.timeout(10000),\n    ]),\n  },\n);\n```\n\nEach message includes the worker endpoint, the serialized job, and delivery configuration:\n\n```\nmessages.push({\n  destination: config.destination,\n  body: JSON.stringify(row.payload),\n  headers: {\n    'Content-Type': 'application/json',\n    'Upstash-Deduplication-Id': row.job_id,\n    'Upstash-Retries': '2',\n    'Upstash-Timeout': '10s',\n  },\n});\n```\n\nThe job ID is used as the deduplication ID, while the retry and timeout headers configure message delivery.\n\nAfter publishing, the publisher records the result and the QStash message ID against the corresponding outbox entry. We use ownership tokens when claiming entries so that a publisher can only update records belonging to its current claim.\n\nQStash delivers each job to the Incident service through an HTTP endpoint. The receiver verifies the request signature against the original request body and validates the job payload.\n\nOnce validation succeeds, it records a durable receipt before acknowledging the message. The receipt allows the application to recover accepted jobs if the worker process restarts before execution begins.\n\nWe also use the stable job ID and payload hash to handle repeated deliveries. This prevents a redelivered message from creating another execution for a job that has already been accepted.\n\nFor local development, we run the QStash development server in Docker and configure the publisher to use its local HTTP API. It accepts published messages and delivers them to the configured worker endpoint, allowing us to test the same publishing and delivery flow locally.\n\nYou can find the setup in the [QStash local development guide](https://upstash.com/docs/qstash/howto/local-development?utm_source=abdulrahmon-adenuga).\n\nOnce an investigation job reaches the worker, the Incident service provisions a dedicated [Upstash Box](https://upstash.com/docs/box/overall/quickstart?utm_source=abdulrahmon-adenuga) for that investigation attempt. The Box provides an isolated environment in which the agent can execute its tools, inspect files, and carry out the investigation independently of the main application.\n\nEach investigation gets its own Box, with a separate filesystem and execution environment. This allows multiple agents to run concurrently without sharing the same workspace or processes.\n\nWe use `Box.create()` to provision the environment. The configuration specifies the runtime, Box size, timeout, network policy, and agent configuration.\n\n``` js\nconst box = await Box.create({\n  ...connection,\n  name: input.resource.name,\n  labels: [input.resource.label],\n  runtime: 'node',\n  size: 'small',\n  timeout: 20000,\n  networkPolicy: {\n    mode: 'custom',\n    allowedDomains: [\n      'upstash.com',\n      evidenceHostname,\n      'api.openai.com',\n    ],\n  },\n  agent: {\n    harness: Agent.Codex,\n    model: input.agent.model,\n    apiKey: input.agent.apiKey,\n  },\n});\n```\n\nWe use the Node.js runtime and a small Box for each investigation. The custom network policy controls which external domains processes inside the Box can reach. We allow access to Upstash, our evidence endpoint, and the OpenAI API because these are the services the agent needs during execution. Other outbound destinations are restricted.\n\nWe also configure the agent to use the built-in Codex harness with the OpenAI model selected for the investigation. Box provides the execution environment, while Codex provides the agent harness that runs inside it.\n\nAfter creating the Box and preparing the investigation context, the worker retrieves the Box and starts the agent with `box.agent.run()`.\n\n``` js\nconst run = await box.agent.run({\n  prompt: investigationPrompt(input.input),\n  responseSchema: agentReportSchema,\n  timeout: 90000,\n  maxRetries: 0,\n  options: {\n    modelReasoningEffort: 'low',\n    webSearch: false,\n  },\n  onToolUse: () => {\n    tools++;\n\n    if (tools > agentToolObservationLimit) {\n      throw new BoxError('Agent tool observation limit reached');\n    }\n  },\n});\n```\n\nThe prompt contains the incident summary, investigation scope, observation window, and instructions for carrying out the investigation. We also provide a response schema that defines the structure expected from the agent.\n\nThe run has a 90-second timeout, and we disable automatic retries at this level. The `onToolUse` callback tracks tool calls and stops execution when the configured limit of 24 calls is reached.\n\nWhen the agent finishes, the worker receives the completed run, including its structured result and usage information. The next step is to turn that result into an investigation report, which the Incident service validates and persists.\n\nOnce the agent finishes its investigation, it returns a structured report containing its findings and the evidence supporting them. We define the expected report structure using a response schema and pass it to `box.agent.run()`, so the output follows the format required by the Incident service.\n\nThe report includes a summary, timeline, observations, findings, likely cause, alternative explanations, confidence level, limitations, and suggested follow-up actions.\n\nFor example, in one of our payment-timeout investigations, the agent returned a report identifying PostgreSQL lock contention as the likely cause of the failures:\n\n```\n{\n  \"summary\": \"Payment payment.get requests repeatedly waited on a PostgreSQL relation lock on payments.attempts, then timed out with DEADLINE_EXCEEDED. The lock contention cleared later, and a subsequent request succeeded.\",\n  \"likely_cause\": {\n    \"statement\": \"An AccessExclusiveLock on payments.attempts blocked payment.get reads that required AccessShareLock, resulting in repeated request timeouts.\",\n    \"evidence_refs\": [\n      \"loki:d973b0f8e9482dbc2d393698cdaed590ef871d1c1db9a33c0e6cb70224050b18\",\n      \"sha256:6b3235a78732d6a3f33ed33ca0ec509aa9ecde1b1aefd06f5881cfe5e5851348:apps/payment/src/payments/payments.sql\"\n    ]\n  },\n  \"confidence\": \"high\"\n}\n```\n\nAfter the agent finishes, the worker sends the result to the Incident service through the investigation callback endpoint. The service validates the report and persists it against the corresponding investigation.\n\nThe application then makes the stored report available through its API.\n\nAfter a successful submission, the worker also cleans up the Box used for that investigation attempt, releasing the execution environment and its associated resources.\n\nIn this project, we use three Upstash products: Redis, QStash, and Box. Each has a specific responsibility within the application:\n\nBeyond the products used in this implementation, Upstash provides several other services for different application workloads:\n\nThe complete implementation is available in the [incident-system repository](https://github.com/Rahmannugar/incident-system).", "url": "https://wpnews.pro/news/building-a-parallel-incident-investigation-system-with-upstash-box", "canonical_source": "https://dev.to/rahmannugar/building-a-parallel-incident-investigation-system-with-upstash-box-5e8f", "published_at": "2026-11-29 17:36:50+00:00", "updated_at": "2026-11-29 17:45:59.684055+00:00", "lang": "en", "topics": ["ai-agents", "ai-infrastructure", "ai-tools", "mlops", "developer-tools"], "entities": ["Upstash", "Upstash Box", "Upstash QStash", "OpenAI", "Codex", "GitHub"], "also_reported_by": [], "takeaway": "Giving each AI incident-investigation agent its own isolated Box container and dispatching jobs asynchronously via QStash lets multiple investigations run in parallel without interfering with each other or the main application.", "recommendation": {"advice": "Run each agent investigation in its own isolated execution environment and dispatch jobs asynchronously, so concurrent investigations cannot interfere with each other or the host application.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/building-a-parallel-incident-investigation-system-with-upstash-box", "markdown": "https://wpnews.pro/news/building-a-parallel-incident-investigation-system-with-upstash-box.md", "text": "https://wpnews.pro/news/building-a-parallel-incident-investigation-system-with-upstash-box.txt", "jsonld": "https://wpnews.pro/news/building-a-parallel-incident-investigation-system-with-upstash-box.jsonld"}}