Skip to content
Blog

Managing Multi-Tenant ADK Instances: Isolating App Names and User Scopes

How ADK's (app_name, user_id, session_id) triple becomes a real tenancy boundary — scoping sessions, state, artifacts, and services so one tenant can never read another's data.

Published on • November 25, 2026

AI Assistant

Every request that reaches an ADK Runner is addressed by exactly three strings: app_name, user_id, and session_id. That triple is not a convenience — it is the tenancy boundary. Sessions are stored under it, state is scoped to it, artifacts are namespaced by it, and every service lookup resolves through it. If you get the isolation model right, a multi-tenant deployment is mostly a naming discipline problem; if you get it wrong, tenant data leaks are structural rather than accidental.

This post treats the triple as a security and correctness boundary and works through how to partition a shared ADK process safely.

The addressing model

ADK stores a session as a key of (app_name, user_id, session_id). A SessionService implementation indexes its data by exactly that, and nothing in the framework will ever hand you a session that doesn’t match all three.

from google.adk.runners import InMemoryRunner
from google.adk.agents import Agent

root_agent = Agent(model="gemini-flash-latest", name="assistant")

runner = InMemoryRunner(agent=root_agent, app_name="support_desk")

session = await runner.session_service.create_session(
    app_name="support_desk",   # which application / tenant partition
    user_id="acme-corp",       # which principal inside that partition
)
print(session.id, session.app_name, session.user_id)

The important consequence: there is no cross-tenant lookup API by accident. To read another tenant’s session you must supply their app_name and user_id explicitly. Isolation failures therefore happen when your code derives those values from untrusted input.

Layer 1: app_name as the tenant partition

app_name is the coarsest axis and the right place to put the tenant. ADK itself uses it to route to the correct agent directory when you run adk web over an agents folder, and the API server exposes it in the URL path (/apps/{app_name}/...).

Two viable strategies:

One app per tenant — strongest isolation, highest operational cost. Each tenant gets their own agent package, their own SessionService namespace, and can be given their own services.

runner = InMemoryRunner(
    agent=root_agent,
    app_name=f"support__{tenant_id}",   # e.g. support__acme-corp
)

One app, tenant in user_id — cheaper, and what most deployments actually do. user_id becomes a composite principal.

session = await runner.session_service.create_session(
    app_name="support_desk",
    user_id=f"{tenant_id}:{end_user_id}",   # "acme-corp:u-8813"
)

The composite form keeps a single deployable agent while preserving a hard string boundary. Whichever you pick, decide once and enforce it in one function — never let a route handler build the principal itself.

def principal_for(tenant: str, user: str) -> str:
    """Single choke point for building an ADK user_id."""
    if not TENANT_RE.fullmatch(tenant) or not USER_RE.fullmatch(user):
        raise ValueError("malformed principal")
    return f"{tenant}:{user}"

The regex guard matters more than it looks: ADK will happily store whatever string you pass, so a user_id containing a delimiter or path traversal characters becomes an injection surface for the storage layer below.

Layer 2: state namespaces inside the session

Within a session, state is a flat dictionary — and ADK gives you a convention for partitioning it. Keys prefixed app: belong to the application; the rest belong to the conversation.

def my_tool(tool_context, **kwargs):
    # app-scoped: same for every session of this app
    endpoint = tool_context.state.get("app:api_endpoint")
    # conversation-scoped: private to this user's session
    cart = tool_context.state.get("cart_items", [])
    ...

In a multi-tenant process, app: state is shared across all tenants using that app. If you put a tenant-specific API key or tenant config under app: in a shared app, you have just leaked it to every other tenant. Keep tenant config in a keyed store (Secret Manager, Parameter Manager) and reference it by ID; keep per-tenant values under a tenant-scoped key in session state.

ADK also supports private sub-agent state via state["private:..."] style scoping, which keeps one agent’s scratch data out of the shared view other agents read. Use it for intermediate reasoning that other agents must not inherit.

Layer 3: services are the real blast radius

The SessionService, ArtifactService, and MemoryService you inject into the Runner determine how far a mistake can travel.

ServiceIsolation riskMitigation
InMemorySessionServiceNone across processes — but shared within one processFine for dev; per-tenant DB in prod
DatabaseSessionServiceRows keyed by (app_name, user_id, ...)Enforce the key in the query, not the app layer
ArtifactServiceFiles keyed by app/user/sessionBucket prefix per tenant; signed URLs with short TTL
MemoryServiceCross-session by designFilter every search by tenant before returning

Memory is the sharp edge. A MemoryService exists precisely to recall information across sessions — which means, unless you filter it, “what did this user say last month” can silently become “what did any user say last month.” Always scope memory ingestion and retrieval with the tenant principal:

async def recall(principal: str, query: str):
    results = await memory_service.search_memory(
        app_name=APP_NAME, user_id=principal, query=query
    )
    return [r for r in results if r.metadata.get("tenant") == tenant_of(principal)]

Defense in depth: filter in the application and partition the underlying store by tenant, so a missing filter degrades to slow queries rather than a breach.

Layer 4: request-time validation

The framework trusts you; the boundary must be re-derived from authenticated identity on every request, never from the request body.

@app.post("/chat")
async def chat(req: ChatRequest, auth: VerifiedUser):
    # auth comes from your JWT/OIDC layer — never from req.body
    principal = principal_for(auth.tenant, auth.subject)
    session = await runner.session_service.create_session(
        app_name=APP_NAME, user_id=principal
    )
    return await run_turn(runner, principal, session.id, req.message)

Three rules worth writing on the wall:

  1. Never accept app_name or user_id from the client. Derive both from the verified token.
  2. Never trust session_id alone. Always pair it with the derived principal when loading — a session ID from tenant B is useless if you also require tenant A’s principal.
  3. Validate the format, not just the value. Reject principals that don’t match your expected shape before they reach storage.

Cross-cutting concerns

Log redaction. Invocation logs include user_id, state deltas, and often tool arguments. Hash or truncate the principal in logs so operational telemetry stays useful without becoming a PII store.

Artifacts. Artifact filenames are user-visible. Sanitize them and prefix storage paths with the tenant, otherwise a crafted filename can collide across tenants in a shared bucket.

Concurrency. Isolation is not thread safety. Two requests for the same session still race on state deltas; ADK applies state deltas per event, so concurrent writes to the same key need optimistic handling at your service layer.

Testing. The cheapest high-value test in a multi-tenant system is a negative one: create two tenants, write distinct state and artifacts for each, then assert that every read path for tenant A returns nothing from tenant B — including memory search, artifact listing, and session replay.

A checklist before you ship

  • app_name and user_id derived exclusively from verified auth
  • Principal format validated at the boundary
  • Tenant config not stored under app: state in a shared app
  • Memory ingestion and search filtered by tenant
  • Artifact storage namespaced per tenant
  • Session reads always scoped by (app_name, user_id) together
  • Logs redact principals and PII
  • Negative isolation tests covering sessions, state, artifacts, and memory

Where to go next

Multi-tenancy is a framing problem; ADK supplies the primitives underneath it. Once the addressing discipline is in place, the natural follow-ups are dependency injection for per-tenant services, the InvocationContext lifecycle that carries these scopes, and enterprise-grade reliability guardrails for running the whole thing in production.

References