cd /news/ai-agents/building-a-parallel-incident-investi… · home › topics › ai-agents › article
[ARTICLE · art-178211] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Building a Parallel Incident Investigation System with Upstash Box.

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.

recommendation

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.

more in playbook: Designing agent systems
by read17 min views11 publishedNov 29, 2026

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.

The 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?

I 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.

Building this required solving two related problems: providing isolated environments in which the agents could execute, and reliably dispatching investigation jobs to those environments.

This is where Upstash Box and Upstash QStash come in. Box provides the execution environment for each investigation, while QStash handles the asynchronous delivery of investigation jobs.

In 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. We'll look at how individual investigations execute, how they access operational evidence, and how the distributed application coordinates multiple investigations.

Upstash Boxprovides 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.

This distinction becomes important when working with AI agents.

An 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.

This 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.

It helps to separate the different responsibilities involved:

These 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.

Upstash 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.

You can read more about Box's execution model and built-in agent support.

Before looking at agent execution, let's see what creating a Box looks like.

The @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.

Here is the creation call used in our implementation, with the configuration values supplied by the application:

const box = await Box.create({
  ...connection,
  name: input.resource.name,
  labels: [input.resource.label],
  runtime: 'node',
  size: 'small',
  timeout: 20000,
  networkPolicy: {
    mode: 'custom',
    allowedDomains: [
      'upstash.com',
      ...(input.resource.evidenceOrigin
        ? [new URL(input.resource.evidenceOrigin).hostname]
        : []),
      ...(input.agentModel ? ['api.openai.com'] : []),
    ],
  },
  ...(input.agent
    ? {
        agent: {
          harness: Agent.Codex,
          model: input.agent.model,
          apiKey: input.agent.apiKey,
        },
      }
    : {}),
});

There are a few things worth pointing out here.

First, 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.

Second, 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.

Finally, 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.

Once the Box has been created and configured with an agent, we can execute a task through its agent interface.

In our implementation, the agent execution looks like this:

const run = await box.agent.run({
  prompt: investigationPrompt(input.input),
  responseSchema: agentReportSchema,
  timeout: 90000,
  maxRetries: 0,
  options: {
    modelReasoningEffort: 'low',
    webSearch: false,
  },
  onToolUse: () => {
    tools++;

    if (tools > agentToolObservationLimit) {
      throw new BoxError('Agent tool observation limit reached');
    }
  },
});

The 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.

We 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.

The 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.

Separate execution environments are useful whenever an application needs to run work that should not share the same execution context as its main processes.

For 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.

The 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.

This 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.

For 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.

The 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.

The 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.

The 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, which delivers it to the Payment service for processing.

Payment processing is mocked in the application. The Payment service processes the request, records the payment attempt, and publishes the resulting payment event.

Alongside the commerce services, we have an Incident Service responsible for receiving alerts, creating investigations, coordinating their execution, and storing the resulting reports.

The 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.

For 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.

Now that we understand how the application works, let's look at how an incident moves through the investigation system.

The 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.

An outbox publisher picks up the pending job and publishes it to Upstash QStash. QStash then delivers the message to the Incident service's signed receiver.

The receiver verifies the message and records the delivery before acknowledging it. From there, the application coordinates the investigation execution.

For each investigation attempt, the application provisions a dedicated Upstash Box. The agent runs inside that Box with the investigation instructions, the required tools, and access to the operational evidence relevant to the incident.

The 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.

Each investigation runs independently in its own Box. This allows the application to execute multiple investigations concurrently without sharing the same agent execution environment.

When 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.

The 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.

After a successful investigation, the application also cleans up the Box used for that attempt and releases the resources associated with it.

The overall flow looks like this:

flowchart TD
    A["Application failure"] --> B["Grafana alert"]
    B --> C["Incident Service"]
    C --> D["Create incident and investigation"]
    D --> E["Transactional outbox"]
    E --> F["Upstash QStash"]
    F --> G["Signed message receiver"]
    G --> H["Provision Upstash Box"]
    H --> I["Run investigation agent"]
    I --> J["Inspect operational evidence"]
    J --> K["Submit structured report"]
    K --> L["Validate and persist report"]
    L --> M["Clean up Box"]
    L --> N["Report available through API"]

This 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.

Before 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.

We 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.

For example, our allowlist includes entries like these:

const allowlist = [
  {
    path: 'runbooks/payment-timeouts.md',
    kind: 'runbook',
    services: ['gateway', 'identity', 'order', 'payment'],
  },
  {
    path: 'runbooks/outbox-delivery.md',
    kind: 'runbook',
    services: ['order', 'payment', 'notification'],
  },
  {
    path: 'apps/payment/src/payments/payments.repository.ts',
    kind: 'source',
    services: ['payment'],
  },
  {
    path: 'apps/payment/src/payments/payments.sql',
    kind: 'source',
    services: ['payment'],
  },
  {
    path: 'apps/order/internal/orders/outbox.publisher.go',
    kind: 'source',
    services: ['order'],
  },
];

Each entry identifies a document, its type, and the services it relates to.

When 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.

We also narrow down the service list attached to each selected document so that it only contains services covered by the investigation:

const selectedDocuments = allowlist
  .filter(entry =>
    entry.services.some(service =>
      scopeServices.includes(service)
    )
  )
  .map(entry => ({
    ...entry,
    services: entry.services.filter(service =>
      scopeServices.includes(service)
    ),
  }));

The 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.

The worker reads these selected files from the repository's local working tree and calculates a SHA-256 hash for each file:

const sha256 = createHash('sha256')
  .update(buffer)
  .digest('hex');

We include the hash in the document reference so that the application can identify the exact contents prepared for the investigation:

const document = {
  path: entry.path,
  kind: entry.kind,
  services: entry.services,
  sha256,
  bytes: buffer.length,
  ref: `sha256:${sha256}:${entry.path}`,
  content,
};

These 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.

We also keep the document collection bounded: individual documents cannot exceed 32 KB, and the complete catalog cannot exceed 64 KB.

Once 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.

We also prepare the information that identifies the investigation and defines what the agent is allowed to inspect.

This includes:

The 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.

We pass this information to the agent as part of its investigation input:

const input = {
  scope: {
    incidentId: claim.incidentId,
    investigationId: claim.investigationId,
    services: evidenceScope.services,
    window: {
      start: evidenceScope.window.start.toISOString(),
      end: evidenceScope.window.end.toISOString(),
    },
    summary: incident.summary,
  },
  model: agent.model,
};

The agent also receives instructions describing how to approach the investigation, which prepared files to inspect, how to reference evidence, and the expected report structure.

We 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.

At 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.

This gives us a consistent starting environment for each investigation, with the files and context prepared according to its scope.

Upstash QStash is a messaging platform that delivers messages to HTTP endpoints. It supports asynchronous delivery, retries, request signing, and message deduplication.

In 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.

When Grafana sends an alert, the Incident service creates the incident, investigation, and corresponding outbox entry in a database transaction.

The outbox entry contains the information needed to dispatch the investigation. We use a versioned job structure:

interface InvestigationJob {
  id: string;
  type: 'investigation.requested';
  version: 1;
  incident_id: string;
  investigation_id: string;
  occurred_at: string;
  traceparent?: string;
}

A 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.

const response = await fetch(
  `${config.baseURL}/v2/batch`,
  {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${config.token}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(messages),
    redirect: 'error',
    signal: AbortSignal.any([
      signal,
      AbortSignal.timeout(10000),
    ]),
  },
);

Each message includes the worker endpoint, the serialized job, and delivery configuration:

messages.push({
  destination: config.destination,
  body: JSON.stringify(row.payload),
  headers: {
    'Content-Type': 'application/json',
    'Upstash-Deduplication-Id': row.job_id,
    'Upstash-Retries': '2',
    'Upstash-Timeout': '10s',
  },
});

The job ID is used as the deduplication ID, while the retry and timeout headers configure message delivery.

After 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.

QStash 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.

Once 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.

We 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.

For 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.

You can find the setup in the QStash local development guide.

Once an investigation job reaches the worker, the Incident service provisions a dedicated Upstash Box 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.

Each 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.

We use Box.create() to provision the environment. The configuration specifies the runtime, Box size, timeout, network policy, and agent configuration.

const box = await Box.create({
  ...connection,
  name: input.resource.name,
  labels: [input.resource.label],
  runtime: 'node',
  size: 'small',
  timeout: 20000,
  networkPolicy: {
    mode: 'custom',
    allowedDomains: [
      'upstash.com',
      evidenceHostname,
      'api.openai.com',
    ],
  },
  agent: {
    harness: Agent.Codex,
    model: input.agent.model,
    apiKey: input.agent.apiKey,
  },
});

We 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.

We 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.

After creating the Box and preparing the investigation context, the worker retrieves the Box and starts the agent with box.agent.run().

const run = await box.agent.run({
  prompt: investigationPrompt(input.input),
  responseSchema: agentReportSchema,
  timeout: 90000,
  maxRetries: 0,
  options: {
    modelReasoningEffort: 'low',
    webSearch: false,
  },
  onToolUse: () => {
    tools++;

    if (tools > agentToolObservationLimit) {
      throw new BoxError('Agent tool observation limit reached');
    }
  },
});

The 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.

The 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.

When 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.

Once 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.

The report includes a summary, timeline, observations, findings, likely cause, alternative explanations, confidence level, limitations, and suggested follow-up actions.

For example, in one of our payment-timeout investigations, the agent returned a report identifying PostgreSQL lock contention as the likely cause of the failures:

{
  "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.",
  "likely_cause": {
    "statement": "An AccessExclusiveLock on payments.attempts blocked payment.get reads that required AccessShareLock, resulting in repeated request timeouts.",
    "evidence_refs": [
      "loki:d973b0f8e9482dbc2d393698cdaed590ef871d1c1db9a33c0e6cb70224050b18",
      "sha256:6b3235a78732d6a3f33ed33ca0ec509aa9ecde1b1aefd06f5881cfe5e5851348:apps/payment/src/payments/payments.sql"
    ]
  },
  "confidence": "high"
}

After 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.

The application then makes the stored report available through its API.

After a successful submission, the worker also cleans up the Box used for that investigation attempt, releasing the execution environment and its associated resources.

In this project, we use three Upstash products: Redis, QStash, and Box. Each has a specific responsibility within the application:

Beyond the products used in this implementation, Upstash provides several other services for different application workloads:

The complete implementation is available in the incident-system repository.

── more in #ai-agents 4 stories · sorted by recency
── more on @upstash 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/building-a-parallel-…] indexed:0 read:17min 2026-11-29 · —