---
title: "The InvocationContext Lifecycle and Thread Safety in ADK"
date: "2026-11-25T07:56:00+07:00"
description: "What InvocationContext actually owns, when it is created and torn down, how the narrower context types relate to it, and the concurrency rules that keep sessions consistent."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-invocationcontext-lifecycle-thread-safety.jpg"
alt: "Lifecycle diagram of an InvocationContext spanning one agent run"
tags: ['google-adk', 'invocation-context', 'concurrency', 'python', 'architecture']
---

Every agent run in ADK is organized around one object: `InvocationContext`. It is created when a run starts, threaded through every callback, tool, and sub-agent, and discarded when the run ends. Understanding its lifecycle is the difference between "my tool can see the session" and "my tool accidentally mutated state two other requests were reading."

## What the context actually is

ADK deliberately splits context into a small family instead of one all-powerful object:

- **`InvocationContext`** — the full, mutable view of one run: `session`, `agent`, `invocation_id`, `user_content`, plus references to the session, artifact, memory, and auth services. It's received as `ctx` inside an agent's `_run_async_impl` / `_run_live_impl`.
- **`ReadonlyContext`** — a restricted read-only projection. Used where mutation must be impossible (e.g. instruction providers); its `state` is a `mappingproxy`.
- **`Context`** — the unified mid-tier (formerly `CallbackContext` and `ToolContext`): mutable `state`, artifact load/save, `user_content`. Used in lifecycle and model callbacks.
- **`ToolContext`** — `Context` plus tool-call-specific members: `request_credential`, `request_confirmation`, `search_memory`, `list_artifacts`, and `function_call_id`. Members that only make sense mid-tool-call raise `ValueError` when accessed outside one.

The design rule follows from the hierarchy: **take the narrowest context that gives you what you need.** A tool that demands `InvocationContext` is requesting authority over the whole run to read one state key.

## The lifecycle, step by step

```
Runner.run_async(user_id, session_id, new_message)
  │
  ├─ session loaded (app_name, user_id, session_id)
  ├─ InvocationContext created  ── invocation_id assigned
  ├─ for each agent in the flow:
  │     ├─ before_agent callbacks (Context)
  │     ├─ before_model callbacks (Context)
  │     ├─ model generates ──▶ after_model callbacks
  │     ├─ tool calls execute (ToolContext)
  │     └─ after_agent callbacks
  ├─ events appended to session, state deltas applied
  └─ InvocationContext released (run_async generator completes)
```

Key implications:

1. **It has exactly the lifetime of one invocation.** Never stash a context on `self`, in a module global, or in a cache. Once the run ends, it references a stale session — using it later is a use-after-free with extra steps.
2. **The session is loaded, not held.** State reads/writes through `context.state` go to the session object the context references; the session service persists deltas as events.
3. **Sub-agents share the invocation.** A sub-agent in the same run sees the same context lineage — one `invocation_id` spans the whole tree, which is what makes cross-agent state visible at all.

## State: deltas, not mutations

`context.state` looks like a plain dict, but writes are tracked as deltas that get attached to the next event. Two consequences catch people out:

```python
def my_tool(tool_context, **kwargs):
    tool_context.state["cart_total"] = 42      # scheduled as a delta
    tool_context.state["app:mode"] = "strict"  # app-scoped, shared across sessions
    return {"ok": True}
```

- **`app:` keys are application scope, not this conversation.** They persist across sessions of the app — correct for shared configuration, catastrophic for per-user values.
- **Private scoping exists.** Keys can be scoped private to a sub-agent so its scratch work isn't visible in the shared view.
- **Deltas land with events.** If the run dies mid-flight, uncommitted deltas may never persist — the same reason you should [design for exceptions explicitly](/blog/adk-agent-exceptions-graceful-fallback).

## Thread safety: what's actually guaranteed

ADK's async runner executes within an event loop, and here is the honest rule: **`InvocationContext` is not a synchronization primitive.** Concurrency safety comes from *your* discipline:

**One invocation per session at a time.** Two concurrent runs against the same `(app_name, user_id, session_id)` both load the session, both compute deltas, and the last writer wins. If your API allows it, serialize per session — a per-session lock or queue at the application layer:

```python
session_locks: dict[tuple[str, str, str], asyncio.Lock] = defaultdict(asyncio.Lock)

async def run_turn(app_name, user_id, session_id, message):
    key = (app_name, user_id, session_id)
    async with session_locks[key]:
        ...  # runner.run_async here
```

**Different sessions are independent.** Separate sessions have separate contexts; concurrent runs across users are safe as long as shared services underneath (DB pools, HTTP clients) are themselves safe — which is precisely the [dependency injection concern](/blog/adk-dependency-injection-services-adapters) of building them once at startup rather than per call.

**Contexts must not cross invocations.** Caching a `Context` to reuse "convenient" later is the classic bug: it holds a reference to an old session whose state has since moved on. Share *data* (IDs, config values), never context objects.

**Callbacks may run concurrently across invocations.** Your `before_model` callback serving user A can be interleaved with one serving user B. Keep callbacks stateless; if they need per-run data, take it from the context they were handed.

## Anti-patterns checklist

- ❌ Storing `ctx` on `self` or in a module-level variable
- ❌ Assuming `state` writes are immediately durable before the event persists
- ❌ Writing per-user secrets under `app:` keys
- ❌ Passing `InvocationContext` into tools when `ToolContext` suffices
- ❌ Running two invocations against one session without serialization
- ❌ Treating `ReadonlyContext.state` as mutable (it's a `mappingproxy` — by design)

## Where to go next

The context is the carrier; what travels in it is covered by [multi-tenant app names and user scopes](/blog/adk-multi-tenant-app-names-user-scopes) for addressing, and [dependency injection](/blog/adk-dependency-injection-services-adapters) for constructing what the context references. For unattended runs where many invocations interleave, see [headless background agents and async queues](/blog/adk-headless-background-agents-async-queues).

## References

- [Agent context: `InvocationContext`, `ReadonlyContext`, `Context`, `ToolContext`](https://adk.dev/context/)
- [Conversational context: session, state, and memory](https://adk.dev/sessions/)
- [Agent Runtime](https://adk.dev/runtime/)
- [google/adk-python](https://github.com/google/adk-python)
