Skip to content
Blog

Google ADK: State Migration Strategies When Upgrading Agent Data Schemas

Version, dual-read, and backfill ADK session state safely. Covers migrate-on-read callbacks, EventActions deltas, and the adk migrate session CLI for v0→v1 databases.

Published on • December 4, 2026

AI Assistant

Agents accumulate state the way applications accumulate technical debt: silently. A key called booking_step becomes a dict; user:language_preference needs a fallback list; the DatabaseSessionService schema underneath shifts from pickle to JSON in a point release. Then one morning, production sessions written under the old shape collide with code that only understands the new one.

Schema migration for ADK agents is not a single event but three distinct problems: your own state keys, the events that carry state deltas, and the session database schema itself. This tutorial walks through each, with the migrate-on-read pattern as the centerpiece and the official adk migrate session CLI for the storage layer.

Prerequisites

  • ADK Python v1.22.1 or higher (required for the session migration CLI)
  • pip install google-adk[db] if you use DatabaseSessionService
  • Existing sessions with state you cannot afford to lose

1. Know which schema you are migrating

ADK state is a collection of serializable key-value pairs with scope-defining prefixes: no prefix for session state, user: for cross-session user state, app: for application-wide settings, and temp: for per-invocation scratch that never persists. Three layers can drift independently:

LayerExample driftMigration cost
State keys & value shapescart_total (str) → cart (dict)Per-session, lazy
Event payloadsstate_delta entries written under old keysBackfill or rewrite history
Session DB schemaADK v0 pickle → v1 JSON serializationOne-off CLI run

Start by dumping real data. Before writing any migration, sample a dozen live sessions and list every state key with its type — you will almost certainly find keys you forgot existed.

2. Version your state explicitly

Add a schema version key to state the moment you ship a change, so old and new sessions are distinguishable at read time:

from google.adk.agents import LlmAgent
from google.adk.sessions import InMemorySessionService, Session

STATE_SCHEMA_VERSION = 2  # bump on every breaking state-shape change

# Initialize the version when the session is first created
session_service = InMemorySessionService()
session = await session_service.create_session(
    app_name="booking_app",
    user_id="user_42",
    state={
        "state_schema_version": STATE_SCHEMA_VERSION,
        # v1 shape: a bare string
        "booking_step": "confirm_payment",
    },
)

def needs_migration(state: dict) -> bool:
    return int(state.get("state_schema_version", 1)) < STATE_SCHEMA_VERSION

Sessions created before the versioning scheme existed default to 1 — treat a missing key as the oldest schema rather than crashing on it.

3. Migrate lazily with a callback (migrate-on-read)

The cheapest migration is the one you never run: transform state on the next turn it is actually read. ADK lets callbacks modify the state on the Context directly, and the framework tracks those changes through events:

from google.adk.agents import LlmAgent

def migrate_state(callback_context) -> None:
    """Runs before each agent turn; upgrades v1 state to v2 in place."""
    state = callback_context.state
    if int(state.get("state_schema_version", 1)) >= 2:
        return  # already current — zero cost fast path

    # v1: booking_step was a bare string
    # v2: booking_step became a dict with history
    old_step = state.get("booking_step")
    if isinstance(old_step, str):
        state["booking_step"] = {"current": old_step, "history": [old_step]}

    # New keys get defaults; deleted keys get cleaned up here too
    state.setdefault("booking_confirmed", False)
    state["state_schema_version"] = 2

booking_agent = LlmAgent(
    name="booking_agent",
    model="gemini-flash-latest",
    instruction="Continue the booking flow. Current step: {booking_step}",
    before_agent_callback=migrate_state,
)

Why this works well:

  • No batch job. Idle sessions are never migrated — a user who never returns costs nothing.
  • Write path stays legal. State modified through the callback context is tracked by ADK’s event machinery; you avoid the documented pitfall of mutating session.state on a fetched session, which bypasses event tracking.
  • Instruction templating keeps working. The {booking_step} placeholder in instruction reads the post-migration value because the callback runs before the agent.

The trade-off: readers of state outside the agent (dashboards, analytics, other services) must handle both shapes until you backfill or retire old sessions.

4. Backfill history with EventActions.state_delta

When lazy migration is not enough — say an output_key-produced value or a user:-scoped preference must be corrected across all sessions — write the change explicitly as an event with a state delta, the standard mechanism ADK documents for multi-key updates:

from google.adk.events import Event, EventActions
import time

async def backfill_user_state(session_service, app_name: str, user_id: str,
                               session_id: str) -> None:
    session = await session_service.get_session(
        app_name=app_name, user_id=user_id, session_id=session_id
    )
    if session.state.get("state_schema_version", 1) >= 2:
        return

    # Prefixes route the delta: user: persists across sessions,
    # unprefixed keys stay session-scoped, temp: would be discarded.
    delta = {
        "state_schema_version": 2,
        "user:preferred_language": session.state.get("user:language", "en"),
        "booking_step": {"current": "unknown", "history": []},
    }
    event = Event(
        invocation_id=f"migrate_{session.id}",
        author="system",
        actions=EventActions(state_delta=delta),
        timestamp=time.time(),
    )
    await session_service.append_event(session, event)

Note what the delta does not include: temp: keys are discarded after the invocation by design, so migrating them is pointless. And because user: state persists at the SessionService level, one delta per user is enough — no need to replay every session.

5. Migrate the session database itself

Framework-level schema changes get an official path. ADK Python v1.22.0 moved DatabaseSessionService from a v0 pickle-based serialization to a v1 JSON-based one. Old databases keep working for now, but the docs are explicit that v1 may be required in future releases — and with ADK Python v1.22.1+, the CLI does the conversion for you:

# SQLite
adk migrate session \
  --source_db_url=sqlite:///source.db \
  --dest_db_url=sqlite:///dest.db

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

After the run, point your DatabaseSessionService configuration at the dest_db_url. The script reads existing data, converts it, and writes a fresh database — so the old one stays untouched as your rollback target. (On Go, the equivalent is calling database.AutoMigrate on every startup, which adds missing tables and columns without dropping anything.)

6. Roll out with an expand–contract plan

PhaseCodeStateDatabase
1. ExpandReads both shapes; writes old shapeVersion key addedUnchanged
2. DualReads both; writes new shape + version bumpMigrate-on-read activeadk migrate session run on a copy
3. ContractOld-shape fallbacks removedBackfill completeApp switched to dest_db_url
4. CleanupVersion check simplifiedDead keys deletedOld DB archived

Ship phases 1–2 together in one release, but keep phase 2 in production for at least one full conversation-retention cycle. Deleting the old-shape fallback while stale sessions still exist is how migrations fail in production.

Checklist

  • Sampled live sessions to inventory every state key and its type
  • A state_schema_version key initializes on session creation
  • Missing version treated as the oldest schema, never an error
  • Migration runs in before_agent_callback via the callback context, not by mutating session.state
  • Cross-session user:/app: state backfilled with EventActions.state_delta
  • temp: keys deliberately skipped (they never persist anyway)
  • adk migrate session tested against a copy before touching production
  • Old-shape read fallbacks removed only after retention cycles confirm no stragglers
  • Rollback path (old database URL) verified before cutover

Conclusion

State migration in ADK decomposes cleanly: version your keys, transform them lazily where they are read, backfill anything cross-session through the event mechanism, and hand framework schema changes to adk migrate session. No phase requires downtime, because every layer tolerates both shapes while the transition runs.

The one rule that keeps the whole system honest is ADK’s own: state changes travel through events. Migrations that respect that path inherit the framework’s persistence, tracking, and thread-safety for free — and roll back as easily as reverting code.

References