Snapshotting and Restoring Agent State Across Distributed Nodes
Because ADK rebuilds session state by replaying each event's state_delta in order, a snapshot is just a serialized event log — and a restore is a replay. This post builds portable snapshots, shows why InMemorySessionService cannot survive a node change, and covers what rewind_async does and does not undo.
Published on • December 3, 2026
AI Assistant

Move an ADK session from the node that created it to the node that serves turn fifty-one and you will find nothing waiting there. Not because the session is lost — sessions are serializable records — but because nothing ever carried it across. State and history are both projections of one thing, the ordered event log, and if your workers each hold their own InMemorySessionService, the log stops at the process boundary.
The good news is that this makes snapshotting almost disappointingly simple. Since SessionService rebuilds session.state by applying each event’s actions.state_delta in order, a snapshot is a serialized event list, and a restore is replaying it into a fresh session. The subtle parts are knowing what a snapshot does not capture — artifacts live in their own versioned store, user:/app: state lives outside the session, and Runner.rewind_async is not the rollback button it looks like. This post builds the snapshot/restore cycle and maps those boundaries precisely.
Prerequisites
- ADK installed (
pip install google-adk) and aRunnerwith at least one completed invocation. - Familiarity with events,
actions.state_delta, and the session lifecycle. - A persistent
SessionServicefor anything multi-node —InMemorySessionServicecannot participate.
1. Why state is a replay, not a record
Every event the Runner commits carries the change it made:
delta = event.actions.state_delta # {key: value} pairs for this step
The SessionService merges each delta into session.state as the event is appended, in log order. That means two invariants your snapshot design can rely on:
- State is fully determined by the event log. Given
session.events, you can reconstructsession.statefrom scratch — no separate state export required. - Order is load-bearing. The same deltas applied out of order produce different state, so a snapshot must preserve the log’s sequence, not just its contents.
The corollary is equally important: anything that changes state without leaving an event is invisible to replay. Mutating a fetched Session object directly (the classic ADK footgun) bypasses event tracking, so that change will not survive a restore. Snapshot-and-replay only works if every write went through output_key or EventActions.state_delta.
2. Snapshot: serialize the log
A minimal snapshot captures identity, the ordered events, and a timestamp:
import json
from datetime import datetime, timezone
from google.adk.sessions import Session
async def snapshot_session(session_service, app_name: str,
user_id: str, session_id: str) -> dict:
session: Session = await session_service.get_session(
app_name=app_name, user_id=user_id, session_id=session_id,
)
return {
"schema_version": 1,
"taken_at": datetime.now(timezone.utc).isoformat(),
"app_name": session.app_name,
"user_id": session.user_id,
"session_id": session.id,
"events": [event.model_dump(mode="json") for event in session.events],
}
def write_snapshot(snapshot: dict, path: str) -> None:
with open(path, "w", encoding="utf-8") as fh:
json.dump(snapshot, fh, ensure_ascii=False, indent=2)
Events are pydantic models, so model_dump(mode="json") gives you a JSON-safe structure directly. The same dict uploads cleanly to GCS if you want snapshots off-box:
from google.cloud import storage # pip install google-cloud-storage
def upload_snapshot(snapshot: dict, bucket_name: str, blob_name: str) -> None:
client = storage.Client()
blob = client.bucket(bucket_name).blob(blob_name)
blob.upload_from_string(
json.dumps(snapshot, ensure_ascii=False),
content_type="application/json",
)
Snapshot size check. A snapshot of the whole log grows with conversation length. If you only need resumable state rather than full history, snapshot the accumulated state instead — replay every state_delta up to the cut point and serialize the resulting dict, then restore it by seeding create_session(state=...). The tradeoff is real: the event-log snapshot preserves full history and auditability; the state-only snapshot is small but irreversibly flattens the past.
3. Restore: create a session and replay
Restoring into a fresh session on any node looks like this:
from google.adk.events import Event
from google.adk.sessions import SessionNotFoundError
async def restore_session(session_service, snapshot: dict) -> str:
new_id = f"{snapshot['session_id']}-restored"
try:
# Idempotency: don't stack duplicate restores.
await session_service.get_session(
app_name=snapshot["app_name"],
user_id=snapshot["user_id"],
session_id=new_id,
)
return new_id
except SessionNotFoundError:
pass
session = await session_service.create_session(
app_name=snapshot["app_name"],
user_id=snapshot["user_id"],
session_id=new_id,
)
for raw in snapshot["events"]:
# Replaying each event re-applies its state_delta, rebuilding state.
await session_service.append_event(session, Event(**raw))
return new_id
SessionNotFoundError (a ValueError subclass) is your idempotency guard: if the restored session already exists, return it instead of appending the log a second time. If you chose the state-only snapshot, replace the loop with create_session(..., state=snapshot["state"]) — one call, no replay.
4. Artifacts live in their own store — snapshot them separately
Artifacts are not inside session.events. They sit in the ArtifactService, versioned independently, referenced by event.actions.artifact_delta as {filename: version}. A session restore that ignores them leaves dangling references:
| Concern | Where it lives | Snapshot how |
|---|---|---|
| Events (history) | session.events | Serialize the log |
| Session/user state | Derived from state_delta replay | Replayed, or seeded explicitly |
| Artifacts | ArtifactService (own versioned store) | Enumerate + export separately |
| App/user state | SessionService, keyed by app_name/user_id | Not part of a session snapshot |
Because the artifact store is versioned, you can snapshot selectively — list_artifact_keys for the filenames, list_versions for each filename’s history, load_artifact(..., version=N) for a specific one — rather than dumping every blob:
async def snapshot_artifact_refs(artifact_service, app_name: str,
user_id: str, session_id: str) -> dict:
refs = {}
for filename in await artifact_service.list_artifact_keys(
app_name=app_name, user_id=user_id, session_id=session_id,
):
refs[filename] = await artifact_service.list_versions(
app_name=app_name, user_id=user_id,
session_id=session_id, filename=filename,
)
return refs
Copy the referenced blobs to your snapshot store, or — simpler — ensure all nodes point at the same GcsArtifactService and only record the references.
5. Distributed nodes: externalize, then snapshot
The architectural prerequisite for all of this is that nodes share state to begin with. A worker-local InMemorySessionService means a snapshot taken on node A is the only copy until node B pulls it; a worker-local InMemoryArtifactService has the same problem for binaries. The fix is the standard one:
| Approach | Shared across nodes | Survives restart | Snapshot needed? |
|---|---|---|---|
InMemorySessionService | No | No | Yes — and it is your only copy |
DatabaseSessionService | Yes (shared DB) | Yes | For backup/migration, not for routing |
VertexAiSessionService | Yes (managed) | Yes | For backup/migration, not for routing |
With DatabaseSessionService or VertexAiSessionService in the picture, any node can get_session and continue the conversation — snapshots become a backup, migration, and time-travel mechanism rather than a session handoff hack. Note that DatabaseSessionService provides in-process locking plus row-level locking for PostgreSQL/MySQL/MariaDB, which is what makes two nodes appending to the same session safe.
What Runner.rewind_async does — and does not — do
ADK offers a tempting shortcut: runner.rewind_async(rewind_before_invocation_id=...) undoes invocations by truncating the session’s event log from that point. It is genuinely useful for “pretend that last turn never happened.” But three limits matter for a distributed design:
- Session-local only. It does not touch app-level or user-level resources (
app:/user:state), memory ingests, or any external system your tools wrote to. - Not atomic across stores. It does not coordinate state, artifacts, and events as one transaction, so a failure mid-rewind can leave the three out of sync.
- Not a snapshot. It deletes the tail of the log; it does not export anything you can restore elsewhere.
For cross-node recovery you still want the explicit snapshot of §2–3. Use rewind for in-session undo, snapshots for portability.
Checklist
- Every state write goes through
output_keyorEventActions.state_delta, so replay can reconstruct state. - Snapshots serialize
session.eventsin order — sequence is part of the data. - Snapshot format carries a
schema_versionfor forward migration. - Restore is idempotent, guarded by
SessionNotFoundError. - Artifacts are enumerated (
list_artifact_keys/list_versions) and copied, or all nodes share oneGcsArtifactService. -
user:/app:state is handled deliberately — it is not inside a session snapshot. - All nodes share
DatabaseSessionServiceorVertexAiSessionService; no worker holds the only copy. -
rewind_asyncis used for in-session undo only, never as cross-store rollback. - Restore is tested on a different node than the one that snapshotted.
- State-only snapshots (via
create_session(state=...)) are chosen knowingly, with history loss understood.
Conclusion
Distributed ADK sessions are portable because they were never more than an ordered log: snapshot the events, replay them on another node, and state reassembles itself. Artifacts and app/user state sit outside that log and need their own handling, and rewind_async covers in-session undo rather than multi-store rollback. Get a shared SessionService underneath everything first — then snapshots stop being a survival mechanism and become what they should be: a backup, a migration path, and a time machine.