---
title: "Managing Multi-Tenant ADK Instances: Isolating App Names and User Scopes"
date: "2026-11-25T07:40:00+07:00"
description: "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."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-multi-tenant-app-names-user-scopes.jpg"
alt: "Diagram showing isolated ADK session scopes per tenant and user"
tags: ['google-adk', 'multi-tenancy', 'sessions', 'state-management', 'architecture']
---

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.

```python
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.

```python
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.

```python
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.

```python
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.

```python
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.

| Service | Isolation risk | Mitigation |
|---|---|---|
| `InMemorySessionService` | None across processes — but shared within one process | Fine for dev; per-tenant DB in prod |
| `DatabaseSessionService` | Rows keyed by `(app_name, user_id, ...)` | Enforce the key in the query, not the app layer |
| `ArtifactService` | Files keyed by app/user/session | Bucket prefix per tenant; signed URLs with short TTL |
| `MemoryService` | **Cross-session by design** | Filter 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:

```python
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.

```python
@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](/blog/adk-dependency-injection-services-adapters), [the `InvocationContext` lifecycle](/blog/adk-invocationcontext-lifecycle-thread-safety) that carries these scopes, and [enterprise-grade reliability guardrails](/blog/enterprise-adk-assistants-reliability-latency-cost) for running the whole thing in production.

## References

- [Agent Development Kit — Technical Overview](https://adk.dev/get-started/about/)
- [Conversational context: Session, State, and Memory](https://adk.dev/sessions/)
- [Agent context: `InvocationContext`, `Context`, `ToolContext`](https://adk.dev/context/)
- [Agent Runtime](https://adk.dev/runtime/)
- [google/adk-python](https://github.com/google/adk-python)
