adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

DatabaseSessionService: first query is slow due to lazy table initialization

Open ferponse opened this issue 8 months ago • 2 comments

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

ferponse avatar Mar 17 '26 11:03 ferponse

@ferponse Thanks for the update. The request is currently being reviewed, and I will let you know if anything further is needed. Thank you for your understanding.

klateefa avatar Mar 18 '26 05:03 klateefa

Notification: The author has updated the issue description. Maintainers, please review.

adk-bot avatar Mar 25 '26 06:03 adk-bot