Skip to main content
Back to all articles
AI Engineering 5 min readUpdated August 31, 2026

An Agent Deadline Should Cancel Work, Not Just Stop Waiting

Timeouts are incomplete if child tools, model calls, database work, and subprocesses keep running. A deadline-based cancellation design for TypeScript and Python that propagates one shrinking time budget through the whole agent run.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-agents#cancellation#timeouts#deadlines#abortcontroller#asyncio#distributed-systems#typescript#python
On this page

A request timing out at the API gateway does not mean the work stopped.

That distinction becomes expensive with agents.

A single user request may fan out into model calls, searches, HTTP tools, database queries, subprocesses, and background workers. If the client disconnects after thirty seconds but those children continue running, the system can keep spending tokens, holding connections, and performing work nobody will ever see.

A timeout that only rejects the top-level promise is not resource control.

I prefer to give every agent run an absolute deadline and a cancellation signal. Every child derives its remaining budget from that same deadline. When the run is cancelled, adapters must attempt to stop the underlying work rather than simply throw away its result.

The example here is a document-processing agent that can search a knowledge base, call an extraction model, fetch a customer record, and run a PDF conversion subprocess.

Use one absolute deadline

Passing timeoutMs = 5000 separately to every layer creates accidental budget multiplication.

If five sequential steps each receive a fresh five-second timeout, the run can take twenty-five seconds even when the parent intended a five-second budget.

An absolute timestamp avoids that.

TypeScript
type RunDeadline = {  expiresAtMs: number;};​function remainingMs(deadline: RunDeadline): number {  return Math.max(0, deadline.expiresAtMs - Date.now());}​function assertTimeRemaining(deadline: RunDeadline): void {  if (remainingMs(deadline) <= 0) {    throw new DOMException("Agent deadline exceeded", "TimeoutError");  }}

At request entry:

TypeScript
const deadline: RunDeadline = {  expiresAtMs: Date.now() + 30_000,};

Every downstream operation sees the same deadline rather than resetting the clock.

Combine deadline expiry with explicit cancellation

A user can cancel before the deadline. The HTTP client can disconnect. A parent workflow can decide that another branch already produced the answer.

I use one AbortController for the run and arrange for the deadline to abort it too.

TypeScript
function createRunAbort(  deadline: RunDeadline,  external?: AbortSignal,): { signal: AbortSignal; dispose: () => void } {  const controller = new AbortController();​  const timeout = setTimeout(() => {    controller.abort(      new DOMException("Agent deadline exceeded", "TimeoutError"),    );  }, remainingMs(deadline));​  const onExternalAbort = () => {    controller.abort(external?.reason ?? new Error("Run cancelled"));  };​  external?.addEventListener("abort", onExternalAbort, { once: true });​  return {    signal: controller.signal,    dispose: () => {      clearTimeout(timeout);      external?.removeEventListener("abort", onExternalAbort);    },  };}

The dispose call matters. Long-lived workers should not accumulate timers and listeners after runs finish normally.

Pass cancellation into actual I/O

For native fetch, the signal belongs on the request:

TypeScript
async function fetchCustomer(  customerId: string,  signal: AbortSignal,): Promise<Customer> {  const response = await fetch(    `https://internal.example/customers/${encodeURIComponent(customerId)}`,    { signal },  );​  if (!response.ok) {    throw new Error(`Customer API returned ${response.status}`);  }​  return response.json() as Promise<Customer>;}

The adapter should not catch AbortError and convert it into a retryable dependency failure. Cancellation is a control-flow event from the parent run.

The same principle applies to model SDKs where cancellation is supported, database drivers with cancel/query-timeout features, queues, and subprocesses.

Child operations get the smaller of local and run budgets

A tool may need a stricter local timeout than the whole agent.

For example, the run has twenty seconds left, but a profile lookup should not consume more than two seconds.

TypeScript
async function withChildTimeout<T>(  parent: AbortSignal,  timeoutMs: number,  operation: (signal: AbortSignal) => Promise<T>,): Promise<T> {  const controller = new AbortController();  const timer = setTimeout(    () => controller.abort(new DOMException("Child timeout", "TimeoutError")),    timeoutMs,  );​  const onParentAbort = () => controller.abort(parent.reason);  parent.addEventListener("abort", onParentAbort, { once: true });​  try {    return await operation(controller.signal);  } finally {    clearTimeout(timer);    parent.removeEventListener("abort", onParentAbort);  }}

The caller should pass Math.min(localLimit, remainingMs(deadline)).

That keeps local policies inside the parent budget.

Do not start work that cannot plausibly finish

A deadline is also a scheduling signal.

Suppose a high-quality reranker typically takes 1.5 seconds and the run has 300 ms left. Starting it just to cancel immediately is pointless.

TypeScript
function requireBudget(  deadline: RunDeadline,  minimumMs: number,  operationName: string,): void {  const remaining = remainingMs(deadline);​  if (remaining < minimumMs) {    throw new Error(      `Skipping ${operationName}: ${remaining}ms remain, ` +        `${minimumMs}ms required`,    );  }}

For user-facing systems, the planner can then choose a degraded path: skip optional enrichment, use cached data, or return the partial result already available.

The last 300 ms should not begin another multi-second chain.

Python gets structured cancellation from asyncio

Python 3.11+ gives a clean timeout context with asyncio.timeout.

Python
import asynciofrom dataclasses import dataclassimport time​@dataclass(frozen=True)class Deadline:    expires_at: float​    @classmethod    def after(cls, seconds: float) -> "Deadline":        return cls(time.monotonic() + seconds)​    def remaining(self) -> float:        return max(0.0, self.expires_at - time.monotonic())​async def run_with_deadline(deadline: Deadline) -> str:    async with asyncio.timeout(deadline.remaining()):        return await execute_agent(deadline)

If the timeout expires, the current task is cancelled. Properly awaited child tasks receive cancellation through structured concurrency.

For a child with a smaller local budget:

Python
async def fetch_profile(    client,    customer_id: str,    deadline: Deadline,) -> dict:    timeout = min(2.0, deadline.remaining())​    async with asyncio.timeout(timeout):        response = await client.get(f"/customers/{customer_id}")        response.raise_for_status()        return response.json()

With httpx, it is also worth configuring connect/read/write/pool timeouts. The outer deadline and transport timeouts solve related but different problems.

Never swallow cancellation in a broad exception handler

This Python pattern is dangerous:

Python
try:    result = await tool()except BaseException as exc:    return {"ok": False, "error": str(exc)}

Catching BaseException can swallow cancellation and process-level control exceptions.

Prefer normal exceptions, and let asyncio.CancelledError propagate:

Python
try:    result = await tool()except asyncio.CancelledError:    raiseexcept Exception as exc:    return {"ok": False, "error": str(exc)}

A cancelled tool is not merely another failed observation for the model to “reason around.” The run is stopping.

Subprocess cancellation needs teardown

A coding or document agent may spawn pytest, ffmpeg, a compiler, or another process.

Cancelling the coroutine does not always guarantee the process tree disappears.

A Python wrapper can terminate and then escalate:

Python
async def run_command(    *args: str,    deadline: Deadline,) -> tuple[int, bytes, bytes]:    process = await asyncio.create_subprocess_exec(        *args,        stdout=asyncio.subprocess.PIPE,        stderr=asyncio.subprocess.PIPE,    )​    try:        async with asyncio.timeout(deadline.remaining()):            stdout, stderr = await process.communicate()            return process.returncode or 0, stdout, stderr    except (asyncio.TimeoutError, asyncio.CancelledError):        process.terminate()        try:            await asyncio.wait_for(process.wait(), timeout=2.0)        except asyncio.TimeoutError:            process.kill()            await process.wait()        raise

In containerized execution, cancelling the whole disposable container or job can be a cleaner boundary than chasing grandchildren individually.

Cancellation and side effects are uncomfortable together

A read can often be abandoned safely.

A write is different.

If the agent sends a refund request and the HTTP connection is cancelled before the response arrives, the payment service may still have processed it. Cancellation does not mean rollback.

The caller needs an idempotency key or operation ID and an unknown outcome state:

TypeScript
type WriteOutcome<T> =  | { status: "completed"; value: T }  | { status: "not-started" }  | { status: "unknown"; operationId: string };

After cancellation, a resumed workflow can query the operation rather than blindly submit the write again.

This is where timeout handling meets idempotency and durable execution.

Queue work needs cancellation state too

If an agent dispatches background jobs, aborting the HTTP request will not unsend a message already published to RabbitMQ, SQS, or another queue.

For cancellable long-running jobs I store run state centrally:

Text
run_83.status = cancelled

Workers check that state before expensive stages and before side effects. If the queue supports explicit job revocation, that can help, but I still want cooperative cancellation because a worker may already own the message.

The cancellation signal has to cross process boundaries as data.

A deadline should be visible in traces

Useful telemetry for every run includes:

  • original deadline;
  • cancellation source: user, client disconnect, parent, or timeout;
  • remaining budget when each tool started;
  • child timeout versus parent timeout;
  • operations still in flight at cancellation;
  • cleanup duration;
  • side effects with unknown outcome.

If a run timed out because the fifth retry began with 400 ms remaining, the trace should make that obvious.

Test cancellation by checking resources, not only responses

A test that asserts “API returned 504” is incomplete.

After cancellation I also want to assert things such as:

  • the HTTP mock observed connection abort;
  • the subprocess terminated;
  • no additional retry started;
  • semaphore permits were released;
  • database transaction rolled back where appropriate;
  • queued work noticed cancelled run state;
  • no unapproved side effect happened after cancellation.

The cleanup behavior is part of the feature.

When a simple timeout is enough

For a single stateless LLM call behind one HTTP request, a provider/client timeout may be all you need.

The stronger pattern becomes necessary as the request becomes a tree of work. Once one run owns several resources and child operations, cancellation needs the same propagation discipline as tracing context or authentication context.

I think of a deadline as a resource budget measured in time. It starts at the boundary, shrinks as the run progresses, and every layer is responsible for respecting it.

When the budget reaches zero, the system should stop *doing work*, not merely stop waiting for the answer.

KEEP READING

Related engineering notes