Skip to content

DatabaseSessionService: first query is slow due to lazy table initialization #4857

@ferponse

Description

@ferponse

Description

DatabaseSessionService initializes database tables lazily on the first database operation (create_session, get_session, list_sessions, etc.). This includes schema version detection and metadata.create_all(), which involves connecting to the database, inspecting existing tables, and potentially creating them.

In production applications, this means the first user request after a deployment or pod restart pays the full table-preparation cost, resulting in a noticeably slower response compared to subsequent requests.

Impact

  • User experience: The first user to interact with the agent after a restart experiences significantly higher latency.
  • Health checks: Applications that rely on a startup probe or readiness check cannot ensure the database is ready before accepting traffic.
  • Cold starts: In containerized / serverless environments, every cold start penalizes the first request.

Current behavior

_prepare_tables() is called at the beginning of every public method (create_session, get_session, list_sessions, delete_session, append_event). On the first call it performs:

  1. Schema version detection (DB connection + introspection)
  2. metadata.create_all() (DDL execution)
  3. Schema metadata insertion (for V1)

All subsequent calls hit an early-return fast path (if self._tables_created: return).

Proposed solution

Rename _prepare_tables() directly to prepare_tables(), making it part of the public API. All internal callers are updated to use the new public name. This allows applications to call it at startup (e.g. in a lifespan hook or after construction) to pay the initialization cost upfront:

session_service = DatabaseSessionService(db_url=db_url)
await session_service.prepare_tables()  # eager initialization

The lazy behavior is fully preserved for backward compatibility — calling prepare_tables() is optional.

Environment

  • google-adk version: 1.27.1
  • Database: PostgreSQL (async via asyncpg)
  • Python: 3.12

Metadata

Metadata

Labels

needs review[Status] The PR/issue is awaiting review from the maintainerservices[Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions