Skip to content
Blog

Session Expiration and TTL Management in High-Traffic Production Apps

ADK core has no built-in per-session TTL — this post shows the production patterns you own instead: scheduled delete_session sweeps, DB-level retention jobs, archival to GCS/BigQuery, and graceful SessionNotFoundError handling.

Published on • December 3, 2026

AI Assistant

At ten thousand new sessions an hour, the question is not whether conversations should expire, but who expires them. Here is the honest answer about ADK: the core library ships no per-session TTL parameter. There is no create_session(..., ttl="7d"), no background reaper, no “expired” callback. Sessions live until something — your code — calls delete_session, or until you delete them at the storage layer.

That is not a gap you work around; it is a responsibility you design for. This post lays out the lifecycle API ADK does give you, then walks the four application-level production patterns — scheduled sweeps, database retention jobs, archive-before-delete, and platform retention settings — that together give you a defensible retention policy.

Prerequisites

  • ADK installed with a persistent SessionService (DatabaseSessionService via pip install google-adk[db], or VertexAiSessionService via pip install google-adk[gcp]).
  • A deployed environment where you can run scheduled work (Cloud Scheduler, Cloud Workflows, or any cron).
  • Agreement on your retention numbers (e.g., hot 30 days, archived forever) — patterns without policy are just code.

1. What ADK core provides — and what it does not

Be precise about the boundary between framework and application:

CapabilityIn ADK core?Where it lives
create_session / get_session / list_sessions / delete_session / append_event✅ YesSessionService
Per-session TTL / expiration parameter❌ NoYou (application level)
Automatic background deletion of stale sessions❌ NoYou (scheduled job)
SessionNotFoundError for missing/expired session_id✅ YesRaised by the service (a ValueError)
Runner(..., auto_create_session=True) for vanished sessions✅ YesRunner constructor
Retention settings on managed backends✅ Platform-levelVertex AI / Agent Platform settings — check current docs for your project

SessionNotFoundError is the framework’s only nod to expiry: it is raised for an invalid, expired, or missing session_id. Everything that makes a session expire is application-level from here down — every pattern below is labeled accordingly.

2. Pattern A — scheduled sweep with list_sessions + delete_session

The simplest complete TTL: a job that enumerates sessions and deletes the stale ones through the service API (which keeps your storage consistent — events, state, and metadata go together):

import time
from google.adk.sessions import SessionNotFoundError

APP_NAME = "support_agent"
RETENTION_SECONDS = 30 * 24 * 3600  # 30 days

async def sweep_user(session_service, user_id: str, now: float | None = None) -> int:
    """Application-level TTL: delete this user's sessions idle past retention."""
    now = now or time.time()
    deleted = 0
    listing = await session_service.list_sessions(app_name=APP_NAME, user_id=user_id)
    for summary in listing.sessions:
        if now - summary.last_update_time < RETENTION_SECONDS:
            continue
        try:
            await session_service.delete_session(
                app_name=APP_NAME, user_id=user_id, session_id=summary.id
            )
            deleted += 1
        except SessionNotFoundError:
            pass  # already gone — a concurrent sweep won the race
    return deleted

Wire sweep_user (or a sweep over an index of active users) to Cloud Scheduler hitting a Cloud Run job, or to a Cloud Workflows schedule. Label it clearly in your runbook: this is your job, not ADK’s — if it stops running, nothing expires.

3. Pattern B — DB-level retention (for DatabaseSessionService)

With DatabaseSessionService, sessions are rows you manage. Two application-level options:

  • Prefer the service when possible: run the Pattern A sweep against the same database. It is one DELETE path for everything ADK stores, and you never risk desynchronizing ADK’s schema from your queries. (Note the schema changed in ADK Python v1.22.0 — migrations are your responsibility.)
  • Use a database job for scale: when listing every session through Python is too slow, a scheduled SQL job that deletes rows older than your retention window is legitimate — just treat the ADK-managed tables as its schema, not yours: no new columns, no rewrites, and run it only during quiet periods or in batches with a LIMIT to avoid lock contention with live append_event calls.

4. Pattern C — archive before delete

Expiration should not mean evidence loss. Export first, delete second:

import json
from google.cloud import storage

async def archive_then_delete(session_service, user_id: str, session_id: str,
                              bucket_name: str) -> None:
    session = await session_service.get_session(
        app_name=APP_NAME, user_id=user_id, session_id=session_id
    )
    record = {
        "app_name": session.app_name,
        "user_id": session.user_id,
        "session_id": session.id,
        "last_update_time": session.last_update_time,
        "state": session.state,
        "events": [e.model_dump() for e in session.events],  # full replayable log
    }
    blob = storage.Client().bucket(bucket_name).blob(
        f"sessions/{APP_NAME}/{user_id}/{session_id}.json"
    )
    blob.upload_from_string(json.dumps(record), content_type="application/json")

    await session_service.delete_session(
        app_name=APP_NAME, user_id=user_id, session_id=session_id
    )

The exported JSON keeps the ordered event log — so audits and offline replay (see the companion post on replaying sessions) still work long after the hot session is gone. For analytics at scale, stream the same records into BigQuery instead of (or as well as) GCS objects. Application-level rule: never delete before the archive write is verified.

5. Pattern D — platform retention and graceful recovery

LayerMechanismNotes
ApplicationScheduled delete_session sweep (Pattern A)Works with every SessionService
DatabaseRetention job on ADK’s tables (Pattern B)Fastest at scale; treat schema as ADK-owned
StorageArchive to GCS/BigQuery, then delete (Pattern C)Keeps replayability after expiry
PlatformVertex AI / Agent Platform retention settings (Pattern D)Managed backend — verify current settings in your project’s docs
Request pathSessionNotFoundError handling + auto_create_sessionRecovers from already-expired sessions

The last row matters most for users: an expired session must degrade to a fresh conversation, not a 500. Catch the error, or let the Runner create on the fly:

from google.adk.runners import Runner
from google.adk.sessions import SessionNotFoundError

runner = Runner(
    agent=agent,
    app_name=APP_NAME,
    session_service=session_service,
    auto_create_session=True,  # vanished/expired session_id -> new session
)

async def run_safe(runner, user_id: str, session_id: str, message):
    try:
        async for event in runner.run_async(
            user_id=user_id, session_id=session_id, new_message=message
        ):
            yield event
    except SessionNotFoundError:
        # Belt and braces: surface a "starting a new conversation" signal
        # to your frontend instead of an error page.
        raise

(SessionNotFoundError inherits from ValueError, so a bare except ValueError also catches it — prefer the explicit type.)

Checklist

  • A written retention policy exists (hot TTL, archive destination, legal holds) before any code ships.
  • The team understands ADK core has no built-in TTL — expiration is an owned application job.
  • Deletion goes through session_service.delete_session (or a batched DB job), never partial row deletes.
  • The sweep runs on a scheduler (Cloud Scheduler/Workflows/cron) with alerting if it stops.
  • Archive-before-delete is verified (object exists / row count matches) before removal.
  • Sweeps tolerate SessionNotFoundError from concurrent deleters.
  • Expired session IDs on the request path degrade gracefully via auto_create_session=True or explicit handling.
  • Platform-level retention settings on Vertex AI / Agent Platform are checked against the same policy.
  • InMemorySessionService is never used where retention must be enforced — it expires everything at restart.

Conclusion

ADK gives you a complete lifecycle API — create, list, append, delete — and one expiry symptom (SessionNotFoundError), but deliberately not a TTL dial. In production you turn that API into retention: a scheduled delete_session sweep for simplicity, a database job for scale, an archive to GCS or BigQuery so deleted conversations stay replayable, platform retention settings as the backend backstop, and a request path that treats an expired ID as “new chat”, not “server error”. Own the reaper, and sessions stay a bounded, auditable cost instead of an unbounded liability.

References