Skip to content
Visual explainer 3h to learn 5 steps

ADK state across instances: concurrency and duplicates

Compare single- and multi-instance execution, handle concurrency and duplicate requests, choose durable state and record the decision.

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

Topic 25 of 29

In short

On one instance with InMemorySessionService, every request sees the same memory, so state looks simple until the process restarts or a second instance starts. With many instances, sessions must live in a shared store such as DatabaseSessionService on PostgreSQL, and you must decide what happens when two turns hit one session at once or when a client retries the same request. Writing that choice down in a short decision record stops the team from relearning it during an incident.

Think of it like this: One instance is a single shop clerk with a notebook; many instances are several clerks who must all write in one shared ledger, and someone has to say who writes first.

Explained simply

When you build an agent on your laptop, there is one copy of the program. Every message goes to that copy, and the session lives in its memory. That is why InMemorySessionService feels so easy: nothing to install, nothing to configure.

In production you usually run more than one copy, called instances, so the service can handle more users and survive a crash. A load balancer sends each request to whichever instance is free. If sessions live only in one instance's memory, the next message may land on an instance that has never heard of that conversation.

The fix is to keep sessions in a shared, durable store, such as a PostgreSQL database through DatabaseSessionService, or a managed store. Now any instance can load the session, add events and save it again. But sharing brings two new questions: what if two messages for the same session arrive at the same time, and what if the same message arrives twice?

Both questions have simple answers. Allow only one run per session at a time, and give every message a unique request ID so a repeat can be spotted and answered from the stored result. Write these rules in a short decision record so everyone knows why the system behaves this way.

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

CompareOne instance compared with many
One instance, in-memory sessions
  • Fast and zero setup
  • Lost on restart or redeploy
  • Cannot scale out
  • Fine for adk web and tests
Many instances, shared database
  • Any instance can serve any turn
  • Survives restarts and rollouts
  • Needs a durable session store
  • Needs rules for concurrent turns and retries
SequenceA retried request made safe with a request ID
Client
API instance
Session store
  1. 1POST turn, request_id r-42
    Client to API instance: POST turn, request_id r-42
  2. 2Record r-42 as in progress
    API instance to Session store: Record r-42 as in progress
  3. 3Connection drops before reply
    API instance to Client: Connection drops before reply
  4. 4Retry: same request_id r-42
    Client to API instance: Retry: same request_id r-42
  5. 5r-42 already seen?
    API instance to Session store: r-42 already seen?
  6. 6Yes: stored final response
    Session store to API instance: Yes: stored final response
  7. 7Same answer, no second run
    API instance to Client: Same answer, no second run
LayersWhere each kind of state should live
  1. 1
    Request scope

    Temporary values for one invocation (temp: prefix), safe to lose

  2. 2
    Instance memory

    Warm caches and clients, never the only copy of anything

  3. 3
    Session store

    Events and session state, shared by all instances

  4. 4
    User and app state

    user: and app: prefixed keys, persisted by the session service

  5. 5
    Idempotency table

    request_id, status and stored response per user

In depth

What changes when you add a second instance

With one instance, process memory is the single source of truth. Restarts wipe it, but nothing disagrees with it. With two or more instances, there is no shared memory, so anything kept in Python variables, module-level caches or InMemorySessionService becomes a per-instance copy. A user's second turn may reach an instance that has no session, and ADK raises a session-not-found error or, with auto_create_session, silently starts a fresh, empty session. That second case is worse because it hides the bug. Before scaling out, list every place the agent keeps data between requests: sessions, artifacts, memory, rate-limit counters and caches. Each must either move to a shared service or be safe to lose. Cloud Run makes this concrete: instances start and stop on their own, so even a service with a maximum of one instance loses in-memory sessions on every new revision.

  • Sessions: DatabaseSessionService or a managed session service
  • Artifacts: a bucket-backed artifact service, not memory
  • Counters and locks: the database or a shared cache
  • Per-instance caches: fine only if losing them is harmless

Concurrent turns in one session

Two turns in the same session can arrive together when a user double-clicks, opens two tabs or a client retries too early. Each run loads the session, calls the model and appends events. Recent ADK releases protect the storage itself: DatabaseSessionService serialises append_event per session inside one process and uses SELECT ... FOR UPDATE row locks on PostgreSQL, MySQL and MariaDB across replicas. A writer that loaded an older copy of the session gets a stale-session error (StaleSessionError, a ValueError subclass) instead of overwriting newer data. That keeps the database consistent, but it does not make the conversation sensible: two interleaved runs still confuse history and state. So add an application rule above ADK. The simplest is one active run per session: take a lock keyed by the session ID before calling run_async and release it when the final event arrives. If the lock is held, return HTTP 409 with a short message, or queue the turn.

FlowOne active run per session
  1. 1
    Turn arrives

    user_id from auth, session_id from path

  2. 2
    Try session lock

    Postgres advisory lock or a lock row

  3. 3
    Lock held?

    Return 409 busy, or queue the turn

  4. 4
    Run the agent

    run_async appends events

  5. 5
    Release lock

    Also on error, timeout or disconnect

Making duplicate requests safe

Networks drop replies, so clients retry. If the retry is treated as a new turn, the agent runs again, calls tools again and bills you again. The standard fix is an idempotency key: the client sends a request ID with each turn, and the server stores the ID together with its status and final response. On a repeat, the server returns the stored response, or a still-running status, without starting a new run. Store the key in the same database as the session, scoped by user so one user cannot read another's result. ADK has a related feature: a resumable App lets you continue an interrupted run by passing its invocation_id to run_async. The docs warn that tools run at least once and may run again on resume, so tools must be idempotent too. For this path that is easy: every tool is read-only, and any write is only a dry-run proposal.

  • Key: user_id plus request_id
  • Status: in_progress, done or failed
  • Keep keys for a short retention window, such as 24 hours
  • Read-only tools make repeats harmless

Choosing a durable session store

Pick the store by the questions you need answered, not by habit. DatabaseSessionService works with any SQLAlchemy database that has an async driver: sqlite+aiosqlite for local work, postgresql+asyncpg for production. You own backups, retention jobs and schema upgrades; the Python schema changed in 1.22.0, so plan a migration when you upgrade across it. A managed session service on Google's Agent Runtime (formerly Vertex AI Agent Engine) removes the database work but ties sessions to that platform and its regions. Whichever you pick, test three things: a restart in the middle of a conversation, two instances serving alternate turns, and deletion of one user's sessions without touching another's.

CompareSession store options
InMemorySessionService
  • No setup
  • Lost on restart
  • One process only
  • Tests and adk web
DatabaseSessionService
  • SQLite locally, PostgreSQL in production
  • You run backups and retention
  • Row locks across replicas
  • Needs async driver
Managed session service
  • Runs on Agent Runtime
  • No database to operate
  • Platform and region bound
  • Check pricing and quotas

Writing the decision record

A decision record (often called an ADR, architecture decision record) is one page in the repository. It states the context, the options you considered, the decision, and the consequences you accept. Keep it factual and testable. For state topology, the record should name the instance model, the session store and its connection settings, the concurrency rule, the retry rule, retention, and the tests that prove each one. Link the trace or test run that backs each claim. When something changes, such as moving to a managed runtime, write a new record that supersedes the old one rather than editing history.

  • Context: traffic, users, data sensitivity
  • Options: in-memory, database, managed
  • Decision and the rules it adds
  • Consequences: cost, operations, lock-in
  • Evidence: test names and trace IDs

Learn it in 5 short steps

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

  1. 1
    Compare one instance with many~35m
  2. 2
    Handle concurrent turns in a session~35m
  3. 3
    Make duplicate requests safe~35m
  4. 4
    Pick a durable session store~35m
  5. 5
    Write a decision record~35m

Key points

  • In-memory sessions are per process: a second instance or a restart sees none of them.
  • DatabaseSessionService needs an async driver, for example sqlite+aiosqlite for local work or postgresql+asyncpg in production.
  • Allow only one active run per session; reject or queue a second concurrent turn instead of letting both write.
  • Clients and load balancers retry, so give every turn a request ID and return the stored result for a repeat.
  • Record the topology, store, concurrency rule and retry rule in a short decision record with its trade-offs.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
from google.adk.runners import Runner
from google.adk.sessions import DatabaseSessionService
from support_agent.agent import app

# Async driver required. Placeholder credentials only.
sessions = DatabaseSessionService(
    db_url="postgresql+asyncpg://adk:<password>@10.0.0.5:5432/adk"
)
runner = Runner(app=app, session_service=sessions)

Every instance points at the same database, so any of them can continue any session.

Proving the in-memory bug with two local instances

Prerequisites: the support agent from earlier modules and a mock model. Step 1: start two copies of the FastAPI wrapper on ports 8001 and 8002, both with InMemorySessionService. Step 2: create a session for user-a on port 8001 and send a turn. Step 3: send the next turn for the same session to port 8002. Expected evidence: a session-not-found error, or with auto_create_session a reply that has forgotten the first turn. Step 4: switch both copies to DatabaseSessionService with the same SQLite file and repeat. Now both turns appear in one session. Cleanup: stop both servers and delete the SQLite file.

bash
export SESSION_DB="sqlite+aiosqlite:///./sessions.db"
uvicorn api:app --port 8001 &
uvicorn api:app --port 8002 &
TOKEN=dev-token-user-a   # local fake auth only
curl -s -X POST localhost:8001/sessions/s1/turns -H "Authorization: Bearer $TOKEN" \
  -d '{"request_id":"r-1","text":"Status of T-1001?"}'
curl -s -X POST localhost:8002/sessions/s1/turns -H "Authorization: Bearer $TOKEN" \
  -d '{"request_id":"r-2","text":"And when was it opened?"}'
kill %1 %2 && rm sessions.db

An idempotent turn handler

The handler checks the request ID before running the agent. A repeat that finished returns the stored answer; a repeat still running returns 409 so the client waits. Only a new ID starts a run. The store is a small table keyed by user and request ID, kept for 24 hours. Expected evidence in the trace: one invocation for r-42 even though the client sent it twice.

python
async def handle_turn(user_id: str, session_id: str, req: TurnIn):
    seen = await idem.get(user_id, req.request_id)
    if seen and seen.status == "done":
        return seen.response
    if seen:
        raise HTTPException(409, "Turn already running")
    await idem.start(user_id, req.request_id)
    async with session_lock(session_id):  # one run per session
        answer = await run_turn(user_id, session_id, req.text)
    await idem.finish(user_id, req.request_id, answer)
    return answer

Quick reference

  • InMemorySessionService: one process, lost on restart; tests and adk web only.
  • DatabaseSessionService(db_url="postgresql+asyncpg://...") needs an async driver.
  • Postgres, MySQL and MariaDB get row locks across replicas; still allow one run per session.
  • Stale session error: reload the session and retry; never overwrite newer data.
  • Idempotency key = user_id + request_id, with stored status and response.
  • Resumable App: ResumabilityConfig(is_resumable=True); tools may run more than once.
  • Test: restart mid-chat, alternate instances, delete one user's data.

Common mistakes

  • Scaling to two instances while still on InMemorySessionService, so users randomly lose their conversation.
  • Letting two browser tabs send turns into the same session at once, which interleaves events and state changes.
  • Treating a retry as a new turn, which runs tools twice and doubles cost.

Quick quiz

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

Question 1

1A Cloud Run service with InMemorySessionService works in testing but users lose context after a deploy. Why?

Question 2

2What is the best application rule for two turns arriving at once in one session?

Question 3

3Which value lets the server recognise a retried request?

Question 4

4What do the ADK docs warn about tools when a resumable run is resumed?

Question 5

5Which db_url is suitable for DatabaseSessionService in local development?

0/5 answered

Practice exercises

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

  1. Exercise 1easy

    List every place your support agent keeps data between requests, and mark each as shared, per-instance or safe to lose.

  2. Exercise 2medium

    Add a session lock so a second concurrent turn in the same session returns HTTP 409. Prove it with two parallel curl calls.

  3. Exercise 3hard

    Write a decision record for moving the support agent from one in-memory instance to three Cloud Run instances.

Check yourself

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

Feel confident about this topic?

Frequently asked questions

Can I use sticky sessions instead of a shared database?
Sticky routing reduces the problem but does not remove it: instances still restart and scale down, and the conversation is lost with them. Use it as an optimisation, not as storage.
Does ADK handle duplicate requests for me?
Not for HTTP retries. Recent releases protect stored events from conflicting writes, but recognising a repeated client request is your application's job, usually with a request ID.
Is SQLite enough for production?
Only for a single instance with a persistent disk. For several instances use a networked database such as PostgreSQL or a managed session service.
Where do I find the invocation ID to resume a run?
Every event carries an invocation_id. The resume docs show passing it to run_async; resuming from adk web or the CLI is not supported.

Go deeper

ShareXLinkedInWhatsApp