Workflow Timeouts and Cancellation Semantics for Long-Running Tasks
Configure per-node timeouts and retry policies in ADK graph workflows, understand what NodeTimeoutError does to a run, and learn how cancellation propagates through a running invocation.
Published on • December 2, 2026
AI Assistant

A node calls a forecast API that has started returning responses after 45 seconds instead of 2. Nothing in your graph is “wrong” — every edge is valid, every handler exists — but the whole workflow now takes three minutes per run, and downstream jobs pile up behind it. Meanwhile a user clicks Cancel on a run that has already produced half its report, and you need the remaining work to stop without destroying the half that succeeded.
Long-running workflows fail in two distinct ways: they run too long, and they need to stop before they finish. ADK 2.0 gives you a per-node knob for the first (timeout plus a RetryConfig) and a runtime-level cancellation mechanism for the second (AbortController / AbortSignal). This post walks through both, including what actually happens to the rest of the graph when a timeout fires.
Prerequisites
- ADK 2.0 with graph-based workflows (
Workflow,@node,Event). See the graph workflows intro if the syntax is new. - Familiarity with the conditional-routing pattern (
Event(route=...)), covered in our conditional edge routing post. - The node-level timeout and retry APIs shown here are Python. The programmatic cancellation examples come from the Cancel Agent Runs guide, which documents
AbortController/AbortSignalfor the TypeScript runtime — the semantics (graceful, non-destructive, propagating) are what matter, and they are the same model in every language.
1. Attach a timeout to a node
A timeout limits a single attempt of a node. It is declared alongside the retry policy on the node itself:
import random
from google.adk import Context, Event, Workflow
from google.adk.workflow import NodeTimeoutError, RetryConfig, node
class ServiceUnavailableError(Exception):
"""Stands in for a transient failure from a remote service."""
@node(
retry_config=RetryConfig(
max_attempts=3, # 1 original attempt + 2 retries
initial_delay=1.0, # seconds before the first retry
exceptions=[ServiceUnavailableError, NodeTimeoutError],
),
timeout=10.0, # seconds allowed for each attempt
)
async def fetch_forecast(ctx: Context):
yield Event(message=f"Fetching forecast, attempt {ctx.attempt_count}")
if random.random() < 0.5:
raise ServiceUnavailableError("Forecast service unavailable")
yield "sunny"
def report_forecast(node_input: str):
return Event(message=f"The forecast is {node_input}.")
root_agent = Workflow(
name="forecast_workflow",
edges=[("START", fetch_forecast, report_forecast)],
)
Three details worth internalizing:
- The timeout is per attempt, not per node lifetime. A
timeout=10.0with three attempts allows up to 30 seconds of execution plus the backoff waits between them. The delay between attempts does not count toward the timeout. ctx.attempt_countstarts at 1. Your node body can tell which attempt is running — useful for logging, and for backing off harder on later attempts.- Delays and timeouts are in seconds (floats allowed).
2. What happens when a node times out
When an attempt runs past its timeout, ADK stops it and treats it as a failure:
- The attempt fails with
NodeTimeoutError(in Go, the context reaches its deadline and fails withcontext.DeadlineExceeded). - If the node’s retry policy covers
NodeTimeoutError, the timeout is just another retryable failure: ADK waitsinitial_delay, then re-runs the node with the same input. - If it doesn’t cover it — or there is no retry policy — the node fails immediately, and the failure propagates to the rest of the workflow. The next node in the sequence does not run.
That second point is the trap. By default a retry policy retries almost every error — but only if you actually attached one. A bare timeout=10.0 with no retry_config means the first slow response kills the node. If you want “stop the stalled call and try again,” you must list NodeTimeoutError in exceptions, exactly as the example above does.
Conversely, a timeout without an explicit exceptions list on a policy that is present still retries, because the default is to retry all errors. Being explicit about which errors retry is better engineering either way:
Rule: retry only transient errors. Bad input and bugs fail identically on every attempt. List connection errors, rate limits, and timeouts — let programming errors fail fast.
One documented limitation to remember: the attempt count lives in memory for the current run of the node. If the workflow pauses (for example for human input) or the process restarts, a node that runs again after resume starts back at attempt 1 with all of its attempts available. Retries are not a durable budget across a resume.
3. Retry policy options at a glance
| Option | Default | Meaning |
|---|---|---|
| Maximum attempts | 5 | Attempts including the original. 0 or 1 disables retries. |
| Initial delay | 1s | Wait before the first retry. |
| Maximum delay | 60s | Cap on any single wait. |
| Backoff factor | 2.0 | Multiplier per attempt → base waits of 1, 2, 4, 8… |
| Jitter | 1.0 | Random spread as a fraction of the wait; 0 gives fixed waits (useful in tests). |
| Errors to retry | All errors | In Python, exceptions takes classes or class names; a listed class also matches subclasses. |
Two placement options matter for real graphs:
- Set the policy on the node that can fail. You can attach a retry policy to a nested workflow in Python, and then a failure of any node inside it retries the entire nested workflow. That is a blunt instrument — retrying one flaky service call by re-running a whole sub-process. Prefer the per-node policy when you know which node is unreliable.
- Make retried work safe to repeat. A retry runs the whole node again. If the node writes to an external system before it fails, that write can happen more than once. Either make the write idempotent, or move the side effect into a separate node that runs only after the unreliable call succeeds.
4. Cancelling a running invocation
Timeouts are passive: they fire when a node overruns. Cancellation is active: your application decides a run is no longer needed — the user clicked Stop, conditions changed, a job was superseded.
ADK’s cancellation is non-destructive: events already committed to the session remain persisted. The documented mechanism is AbortController/AbortSignal, passed to the run:
const controller = new AbortController();
const run = runner.runAsync({
userId: session.userId,
sessionId: session.id,
newMessage: { role: 'user', parts: [{ text: 'Tell me about quantum computing.' }] },
abortSignal: controller.signal,
});
for await (const event of run) {
// ... process events
controller.abort(); // stop the invocation mid-stream
}
You can also time-box a run declaratively with AbortSignal.timeout(2_000), or combine both with AbortSignal.any([controller.signal, AbortSignal.timeout(60_000)]).
Behavior on cancellation
When the signal fires:
- Graceful termination. The async generator returned by the run completes — it stops yielding events without throwing an error.
- Committed events persist. Events already yielded and processed before the abort remain in session history. Cancellation is not a rollback.
- No partial events. Events that were in progress but not yet yielded are discarded. Consumers never see a half-formed event.
- Resource cleanup. In-flight LLM requests are cancelled through the SDK’s native signal support, freeing network connections.
5. How cancellation propagates — and your cleanup obligations
Cancellation propagates down the entire execution stack. Each component checks the signal at critical lifecycle points and terminates early:
| Component | What happens on abort |
|---|---|
| Runner | Stops before session fetch, after plugin callbacks, and within the event streaming loop. |
| LlmAgent | Stops between execution steps, before/after model callbacks, and within response streaming. |
| LoopAgent | Stops between loop iterations and between sub-agent executions. |
| ParallelAgent | Stops when merging results from concurrent sub-agent runs. |
| Models (Gemini) | The signal reaches the GenAI SDK, cancelling the in-flight HTTP request. |
| AgentTool | Passes the signal to the sub-agent runner. |
| MCPTool | Passes the signal to the MCP client’s callTool. |
The invocation context also registers a listener that sets endInvocation = true when the signal fires, telling every component to wind down.
Node timeouts ride on the same machinery: stopping a timed-out attempt relies on cancellation, and how it reaches your code is language-specific. In Go, pass the node’s context (or check ctx.Done()) to the calls your node makes. In TypeScript, ADK stops reading events from the node; to also cancel work the node started — an HTTP request, say — pass ctx.abortSignal to that work.
Which brings us to your obligations as the author of a node or tool:
- Check the signal inside long-running tools. In TypeScript,
toolContext.abortSignalis available in custom tools; checkabortedbetween steps and return a partial result ({ status: 'cancelled', processed: n }) instead of continuing to burn compute. - Close what you opened. Cancellation stops the engine; file handles, database transactions, and third-party jobs you started inside a node are your responsibility to release.
- Design side effects to be resumable, not just retryable. Since committed events survive cancellation, a cancelled run can often be resumed later — your cleanup should leave external state in a condition that makes that safe.
6. Choosing timeouts
There is no universal number, but the process is:
- Measure the healthy latency distribution of the service the node calls, then set the timeout well above the p99 — a timeout that fires on healthy traffic is pure noise that multiplies your retry load.
- Budget backwards from the deadline of the whole workflow. If the job must finish in 60 seconds and you have five sequential nodes with retries, per-attempt timeouts must leave room for worst-case retries on every node, not just the happy path.
- Distinguish “slow” from “stuck.” A node calling a model API might legitimately take 30 seconds; a node doing a database lookup that takes 30 seconds is already broken. Tight timeouts on internal calls, looser timeouts on external model calls.
- Remember retries multiply the timeout. Worst-case node duration ≈
max_attempts × timeout + backoff waits. Compute that per node before you commit to a total.
Checklist
Before shipping a graph with long-running nodes:
- Every node that calls a remote service has an explicit
timeout. - Timeouts that should be recoverable list
NodeTimeoutErrorinexceptions. -
RetryConfig.exceptionsis restricted to genuinely transient error types. - Retried node bodies are safe to run twice (idempotent writes, or side effects split into a separate node).
- Long-running tools check the abort signal between steps.
- Node cleanup releases external resources on both success and cancellation paths.
- Worst-case duration (
attempts × timeout + backoff) fits the job’s overall deadline.
A timeout is not a pessimistic guess about latency — it is the boundary that turns “this service might hang forever” into “this service has 10 seconds, three tries, and then we fail loudly.” Pair it with cancellation that preserves completed work, and long-running workflows stop being a liability.