Skip to content
Blog

DatabaseSessionService: Persisting Conversations to PostgreSQL and Cloud SQL

Swap InMemorySessionService for DatabaseSessionService and conversations survive every redeploy — with the right async driver, two-tiered locking for multi-replica deployments, and the v1.22.0 session schema migration.

Published on • December 3, 2026

AI Assistant

The demo works beautifully — until you redeploy. With InMemorySessionService, every session (history, state, last_update_time) evaporates the moment the process restarts, and your users start from zero with no trace of why. DatabaseSessionService is ADK’s answer for teams that want conversation data living in a database they already operate: PostgreSQL, MySQL, MariaDB, or SQLite, reached through a standard async connection URL.

This tutorial covers installing the extra, choosing the correct async driver, wiring the service into a Runner, the two-tiered locking that makes multi-replica deployments safe, and migrating the session schema after the ADK Python v1.22.0 format change.

Prerequisites

  • ADK installed with the database extra: pip install google-adk[db].
  • A relational database you can reach — a local SQLite file is enough to follow along; PostgreSQL (self-hosted or Cloud SQL) is the production target.
  • A working Runner example on InMemorySessionService, so the service constructor is the only variable you change.

1. Why move off in-memory

The three SessionService implementations expose the same operations — create_session, get_session, list_sessions, delete_session, append_event — and differ in exactly the dimension that matters here: durability.

ImplementationPersistenceExtra requirementsBest for
InMemorySessionServiceNone — lost on restartNothingLocal development, tests, examples
DatabaseSessionServiceYes — rows in your own databasepip install google-adk[db] + async driverSelf-managed relational storage
VertexAiSessionServiceYes — managed Agent PlatformGCP project, google-adk[gcp], Agent RuntimeFully managed production on Google Cloud

Because the API surface is identical, migrating later is a constructor change, not a rewrite.

2. Install the extra and pick an async driver

Importing DatabaseSessionService without the extra raises an ImportError that names the missing db extra, so the install is not optional:

pip install google-adk[db]
pip install asyncpg          # for PostgreSQL — or aiomysql for MySQL, aiosqlite for SQLite

The service requires an async driver. A synchronous URL (sqlite:///..., postgresql://...) will not work — the scheme must name the async driver:

DatabaseConnection URL schemeAsync driver
SQLitesqlite+aiosqlite:///./my_agent_data.dbaiosqlite
PostgreSQLpostgresql+asyncpg://user:pass@host:5432/dbnameasyncpg
MySQLmysql+aiomysql://user:pass@host:3306/dbnameaiomysql
MariaDBmysql+aiomysql://user:pass@host:3306/dbnameaiomysql
from google.adk.sessions import DatabaseSessionService

db_url = "postgresql+asyncpg://adk:change-me@localhost:5432/adk_sessions"
session_service = DatabaseSessionService(db_url=db_url)

The same URL shape works for any reachable PostgreSQL endpoint — a Docker container, a VM, or a Cloud SQL instance — because the service only cares about the async SQLAlchemy URL, not where the server runs.

3. Wire it into the Runner

Nothing else changes: create a session, hand the service to the Runner, and let the event loop drive persistence.

from google.adk.agents import LlmAgent
from google.adk.runners import Runner
from google.adk.sessions import DatabaseSessionService
from google.genai.types import Content, Part

session_service = DatabaseSessionService(
    db_url="postgresql+asyncpg://adk:change-me@localhost:5432/adk_sessions"
)

agent = LlmAgent(
    name="support_agent",
    model="gemini-flash-latest",
    instruction="Answer support questions concisely.",
)
runner = Runner(
    agent=agent,
    app_name="support_app",
    session_service=session_service,   # one shared instance per process
)

session = await session_service.create_session(
    app_name="support_app",
    user_id="u_123",
    state={"ticket_id": "T-42"},
)

async for event in runner.run_async(
    user_id="u_123",
    session_id=session.id,
    new_message=Content(role="user", parts=[Part(text="Where is my order?")]),
):
    if event.is_final_response():
        print("committed:", await session_service.get_session(
            app_name="support_app", user_id="u_123", session_id=session.id
        ))

Every append_event the Runner performs now writes rows: the event lands in history, the state_delta is applied to the session’s state, and last_update_time is refreshed — all in the database.

4. Concurrency: two-tiered locking

The moment two requests touch the same conversation, persistence needs a concurrency story. In Python, DatabaseSessionService uses two tiers:

  1. In-process locking — an internal lock serializes append_event calls for the same session within one process, so concurrent requests in your web workers cannot race each other.
  2. Row-level locking — for PostgreSQL, MySQL, and MariaDB, the service uses SELECT ... FOR UPDATE to protect the same session row across processes and replicas.

The practical consequence: you can run several replicas of your agent server against one database, and two users (or two tabs) writing to the same session will serialize instead of clobbering each other. SQLite gets the in-process tier only — fine for a single-node deployment, not a story for horizontal scaling.

5. Migrate the schema after ADK Python v1.22.0

Starting with ADK Python v1.22.0, the session database schema moved from v0 (pickle-based serialization) to v1 (JSON-based serialization). Old v0 databases keep working on v1.22.0 and later, but v1 may be required by future releases — so plan the migration now rather than during an incident.

The CLI ships the conversion (ADK Python v1.22.1 or higher is required; it includes the command and bug fixes for the schema change):

adk migrate session \
  --source_db_url=postgresql://localhost:5432/v0 \
  --dest_db_url=postgresql://localhost:5432/v1

The script reads existing sessions, converts them to the new format, and writes them to a fresh database. Afterwards, point DatabaseSessionService(db_url=...) at your dest_db_url. Treat this as a release step: run it during a maintenance window, keep the source database until the new one is verified, then cut over.

Checklist

  • google-adk[db] is installed in the environment that runs the agent.
  • The connection URL names an async driver (sqlite+aiosqlite, postgresql+asyncpg, mysql+aiomysql).
  • The matching driver package (asyncpg, aiomysql, aiosqlite) is installed alongside ADK.
  • One DatabaseSessionService instance is created per process and shared with the Runner.
  • Multi-replica deployments rely on row-level locking (PostgreSQL/MySQL/MariaDB), not SQLite.
  • Databases created before ADK Python v1.22.0 are migrated with adk migrate session on v1.22.1+.
  • Conversation data is covered by the database’s backup and retention tooling — it is now your data to protect.
  • InMemorySessionService appears nowhere in the deployed configuration.

Conclusion

DatabaseSessionService removes the “have you tried turning it off and on again?” failure mode from ADK apps without giving up the SessionService abstraction you already code against. Install the extra, name an async driver, let the two-tiered locking handle concurrency, and schedule the v1.22.0 migration while it is still a planned task. Your users’ conversations then live exactly where the rest of your application data lives — in a database you can back up, audit, and query.

References