Skip to content
Visual explainer 2h 30m to learn 5 steps

Per-user session isolation and retention in ADK

Derive the user ID from authentication, scope sessions per user, apply retention and deletion, and prove isolation with two synthetic users.

By Invicly Tech, , in Google ADK with Python for AI Agents. About 11 minutes to read.

Topic 6 of 29

In short

ADK scopes every session by app name, user ID and session ID, but it trusts whatever user ID you pass. Isolation is therefore your job: take the user ID from the verified login, never from the request body, and look sessions up only under that user. ADK has no automatic expiry, so you also write the retention job that deletes old sessions, and you prove both with two synthetic users.

Think of it like this: ADK is a set of lockers labelled by name; it opens whichever locker you name, so the reception desk must check ID before saying the name.

Explained simply

A support assistant talks to many people. Each person's conversations, state and files must stay theirs. ADK helps by filing every session under an app name, a user ID and a session ID. Ask for a session under the wrong user and you get nothing back.

But ADK cannot know who the user really is. It uses whatever user ID your code passes in. If your API lets the caller type any user ID, anyone can read anyone's conversations. So the user ID must come from the login system, after the token is checked, never from the message or the URL.

Conversations also should not live forever. Old chats may hold personal details, and keeping them costs storage and adds risk. ADK has no automatic expiry, so you write a small job that finds sessions older than your limit and deletes them.

Finally, you prove it works. Make two fake users, give each some data, and check that neither can see the other's sessions or state. Write down what the test proved and what it did not, such as artifacts or memory if you did not test them.

Press Play on a diagram to walk through it one step at a time.

FlowWhere the user ID must come from
  1. 1
    Request arrives

    With a bearer token

  2. 2
    Verify token

    Auth layer, not the model

  3. 3
    Derive user_id

    From the token subject

  4. 4
    Look up session

    app, user_id, session_id

  5. 5
    Run agent

    run_async with that user_id

MapEverything to delete for one user
Delete user-a
  • Sessions
    • list_sessions then delete_session
    • Removes events and session state
  • User state
    • user: keys survive session deletion
  • Artifacts
    • list_artifact_keys then delete_artifact
    • Session and user: files
  • Memory
    • Depends on the memory service
    • Check its delete options
  • Logs and traces
    • Should hold IDs, not content
    • Follow log retention

In depth

Taking the user ID from the auth layer

Put authentication in front of the runner. Verify the bearer token, for example a JWT from your identity provider, then use a stable claim such as sub as the ADK user_id. Do not use an email address if it can change. Pass that value to create_session, get_session and run_async, and ignore any user_id field in the request body.

The ADK API server started by adk api_server reads the user ID from the URL path, such as /apps/support_app/users/user-a/sessions. That is fine for local testing but unsafe for real users unless a gateway or middleware rewrites or checks the path against the verified token. A small FastAPI wrapper around the runner, covered in a later module, makes this easier to control.

  • Verify the token before touching sessions
  • user_id = token subject, not a request field
  • Never put user_id in the model's prompt as authority
  • adk api_server: user_id is in the URL path

Scoping sessions per user

Session services look sessions up by app name, user ID and session ID together. If User B sends User A's session ID, get_session under User B returns None, and run_async raises SessionNotFoundError. Map both to a plain 404 so the response does not reveal that the session exists.

Let the server generate session IDs; create_session makes a random one when you omit session_id. If clients must choose IDs, treat them as names within the user's own space, never as global keys. Remember the wider scopes too: user: state is shared across that user's sessions, and app: state is shared with everyone, so it must never hold personal data. Artifacts and memory are also filed by user ID, so the same rule applies.

CompareUnsafe versus safe session lookup
Unsafe
  • user_id read from the request body
  • Client picks guessable session IDs
  • Error says session belongs to someone else
  • Personal data under app: keys
Safe
  • user_id from the verified token
  • Server generates random session IDs
  • Unknown or foreign session returns 404
  • Personal data only in user or session scope

Retention and deletion

Pick a retention period that matches your privacy notice, for example 30 days after the last message. A scheduled job lists each user's sessions with list_sessions(app_name=..., user_id=...), compares last_update_time, a Unix timestamp in seconds, with the cutoff, and calls delete_session for old ones. Log counts, not content.

Deleting sessions is not the whole job. user: and app: state survive session deletion. Artifacts need delete_artifact per filename, and memory services keep their own copies. For a user's deletion request, remove all four and record when it was done. With a database service you may also add your own SQL job, but keep using the ADK service API where you can so the schema can change safely.

  • list_sessions, then delete_session for stale ones
  • last_update_time is seconds since the epoch
  • Also clear user: state, artifacts and memory
  • Log counts and IDs, never message content

Proving isolation with two synthetic users

Write an automated test with two made-up users, user-a and user-b. Give user-a a session with a ticket ID in state and a user: preference. Then, as user-b: list sessions and expect none of user-a's; get user-a's session ID and expect None; run with user-a's session ID and expect SessionNotFoundError; create a new session and expect no user: values from user-a. Run the same test against the in-memory and database services.

Record the result: what was tested, the ADK version, the service type and the date. Also record what was not tested, such as the API layer's token handling or memory search, so nobody assumes more than the test proved.

FlowTwo-user isolation test
  1. 1
    Seed user-a

    Session, state, user: pref

  2. 2
    List as user-b

    Expect no user-a sessions

  3. 3
    Get as user-b

    Expect None

  4. 4
    Run as user-b

    Expect SessionNotFoundError

  5. 5
    Record evidence

    Version, service, date, gaps

Learn it in 5 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Take the user ID from the auth layer~30m
  2. 2
    Scope sessions per user~30m
  3. 3
    Set retention and delete sessions~30m
  4. 4
    Test isolation with two synthetic users~30m
  5. 5
    Record what the check proved~30m

Key points

  • The user ID must come from authentication; a user ID in the body or URL is untrusted input.
  • get_session for the wrong user returns None, and run_async raises SessionNotFoundError, which your API should map to 404.
  • The built-in API server takes the user ID from the URL path, so it needs an auth layer in front before real use.
  • ADK has no session TTL: list sessions, compare last_update_time and call delete_session on a schedule.
  • Isolation tests use two synthetic users and assert that neither can read the other's session or user: state.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import time

async def purge_old_sessions(svc, app_name: str, user_id: str, days: int = 30):
    cutoff = time.time() - days * 86400
    resp = await svc.list_sessions(app_name=app_name, user_id=user_id)
    for s in resp.sessions:
        if s.last_update_time < cutoff:
            await svc.delete_session(
                app_name=app_name, user_id=user_id, session_id=s.id
            )

A retention job; run it per user on a schedule and log how many sessions it deleted.

Deriving the user ID in an API handler

A FastAPI dependency verifies the token and returns its subject. The handler never reads a user ID from the body. Expected evidence: a request with a valid token for user-a can only open user-a's sessions; a missing or invalid token gets 401 before ADK is called. verify_token stands for your identity provider's JWT check.

python
from fastapi import Depends, HTTPException, Header

async def current_user(authorization: str = Header(...)) -> str:
    claims = verify_token(authorization.removeprefix("Bearer "))
    if not claims:
        raise HTTPException(status_code=401)
    return claims["sub"]

@api.get("/sessions/{session_id}")
async def get_my_session(session_id: str, user_id: str = Depends(current_user)):
    s = await sessions.get_session(app_name="support_app", user_id=user_id, session_id=session_id)
    if s is None:
        raise HTTPException(status_code=404)
    return {"id": s.id, "events": len(s.events)}

A pytest isolation check

This test seeds user-a and then tries every read path as user-b. Run it in CI against the in-memory service and, in a scheduled job, against a test database. Expected evidence: all assertions pass. If any fails, stop the release; it means one user's data can leak to another.

python
async def test_users_are_isolated(svc):
    a = await svc.create_session(app_name="x", user_id="user-a",
        state={"current_ticket": "T-1001", "user:lang": "fr"})
    listed = await svc.list_sessions(app_name="x", user_id="user-b")
    assert a.id not in [s.id for s in listed.sessions]
    assert await svc.get_session(app_name="x", user_id="user-b", session_id=a.id) is None
    b = await svc.create_session(app_name="x", user_id="user-b")
    assert "user:lang" not in b.state

Quick reference

  • user_id comes from the verified token subject, never from the request body
  • Sessions are looked up by app_name, user_id and session_id together
  • Foreign or missing session: return 404 without detail
  • Let create_session generate random session IDs
  • No built-in TTL: list_sessions + last_update_time + delete_session on a schedule
  • delete_session leaves user: state, artifacts and memory; delete those too
  • Never put personal data in app: state

Common mistakes

  • Accepting user_id from the request body because it is convenient in a demo.
  • Letting clients choose the session ID, which lets them guess other users' IDs.
  • Deleting sessions but forgetting user: state, artifacts and memory for the same user.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Where should the ADK user_id come from in a production API?

Question 2

2User B calls run_async with User A's session ID. What does ADK do?

Question 3

3After delete_session, a new session for the same user still shows user:lang. Why?

Question 4

4How do you expire sessions after 30 days in ADK 2.15.1?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    List three places in a request where a user ID could appear and say which one your API should trust.

  2. Exercise 2medium

    Write a retention function that deletes a user's sessions not updated in 30 days and returns how many it deleted.

  3. Exercise 3hard

    Write the two-user isolation test, run it against InMemorySessionService and DatabaseSessionService with SQLite, and write a three-line evidence note.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does ADK authenticate users for me?
No. ADK scopes data by the user ID you pass but does not verify it. Authentication belongs in your API layer or gateway.
Should I use the user's email as the ADK user ID?
Prefer a stable, opaque identifier such as the token's sub claim. Emails can change and are personal data in their own right.
How long should I keep sessions?
As short as your product needs and your privacy notice allows. Many support tools keep chats for 30 to 90 days; write your choice down and enforce it with a scheduled job.

Go deeper

ShareXLinkedInWhatsApp