The InvocationContext Lifecycle and Thread Safety in ADK
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.
Published on • November 25, 2026
AI Assistant

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 asctxinside 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); itsstateis amappingproxy.Context— the unified mid-tier (formerlyCallbackContextandToolContext): mutablestate, artifact load/save,user_content. Used in lifecycle and model callbacks.ToolContext—Contextplus tool-call-specific members:request_credential,request_confirmation,search_memory,list_artifacts, andfunction_call_id. Members that only make sense mid-tool-call raiseValueErrorwhen 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:
- 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. - The session is loaded, not held. State reads/writes through
context.statego to the session object the context references; the session service persists deltas as events. - Sub-agents share the invocation. A sub-agent in the same run sees the same context lineage — one
invocation_idspans 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:
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.
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:
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 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
ctxonselfor in a module-level variable - ❌ Assuming
statewrites are immediately durable before the event persists - ❌ Writing per-user secrets under
app:keys - ❌ Passing
InvocationContextinto tools whenToolContextsuffices - ❌ Running two invocations against one session without serialization
- ❌ Treating
ReadonlyContext.stateas mutable (it’s amappingproxy— 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 for addressing, and dependency injection for constructing what the context references. For unattended runs where many invocations interleave, see headless background agents and async queues.