Skip to content

Conversation

@anmolg1997
Copy link
Contributor

@anmolg1997 anmolg1997 commented Feb 10, 2026

Link to Issue or Description of Change

Problem:

The ADK currently lacks a serverless, low-infrastructure session backend for GCP deployments. InMemorySessionService is dev-only, DatabaseSessionService requires SQL infrastructure, and VertexAiSessionService requires a Reasoning Engine.

Solution:

Adds FirestoreSessionService — a new BaseSessionService implementation backed by Google Cloud Firestore. This provides persistent, serverless session storage with zero database management.

Key design decisions:

  • Events stored in Firestore subcollections (avoids 1MB document size limit)
  • Three-tier state management (app/user/session) using separate collections
  • Lazy import via __getattr__ (same pattern as DatabaseSessionService)
  • google-cloud-firestore added as optional firestore extra

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change.
  • All unit tests pass locally.

17 new unit tests covering all CRUD operations, state management, event handling, and edge cases. Firestore interactions are mocked (no GCP project needed).

$ pytest tests/unittests/sessions/test_firestore_session_service.py -v
17 passed in 0.67s

Manual E2E Tests:

Requires a GCP project with Firestore enabled. Set up ADC and instantiate:

from google.adk.sessions import FirestoreSessionService
service = FirestoreSessionService(project="your-project")
session = await service.create_session(app_name="test", user_id="u1")

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @anmolg1997, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses the need for a robust, serverless session persistence solution within the Google ADK for GCP environments. It introduces a new FirestoreSessionService that leverages Google Cloud Firestore to store session data, application state, user state, and events. This provides a highly scalable and managed backend for session management, simplifying deployment and operations for developers building on Google Cloud.

Highlights

  • New FirestoreSessionService: Introduced a new FirestoreSessionService to provide persistent, serverless session storage for Google ADK applications, specifically targeting GCP deployments.
  • Serverless Persistence: This service offers a low-infrastructure alternative to existing session services, requiring no SQL database management or a Reasoning Engine.
  • Three-Tier State Management: Implemented a three-tier state management system (app/user/session) and stores events in Firestore subcollections to avoid document size limits.
  • Optional Dependency: The google-cloud-firestore library is added as an optional firestore extra, ensuring it's only installed when needed, and uses lazy import via __getattr__.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • pyproject.toml
    • Added 'firestore' as an optional dependency group for google-cloud-firestore.
  • src/google/adk/sessions/init.py
    • Exported the new FirestoreSessionService.
    • Implemented lazy loading for FirestoreSessionService to only import google-cloud-firestore when the service is accessed.
  • src/google/adk/sessions/firestore_session_service.py
    • Implemented the FirestoreSessionService class, extending BaseSessionService.
    • Defined Firestore collection and document field names for session, app, user states, and events.
    • Provided methods for creating, retrieving, listing, deleting sessions, and appending events, all interacting with Firestore.
    • Included logic for merging app, user, and session-specific states.
    • Added an __aenter__ and __aexit__ for async context management and a close method for the Firestore client.
  • tests/unittests/sessions/test_firestore_session_service.py
    • Added a comprehensive suite of 17 unit tests for FirestoreSessionService.
    • Implemented a lightweight in-memory mock for Firestore (_FakeDocSnapshot, _FakeDocRef, _FakeCollection, _FakeQuery, _FakeFieldFilter, _FakeFirestoreClient) to enable testing without a real GCP project.
    • Tested CRUD operations, state management (app, user, session), event handling, and edge cases like duplicate session IDs and partial events.
Activity
  • The author, anmolg1997, created 17 new unit tests covering all CRUD operations, state management, event handling, and edge cases for the new service.
  • All unit tests passed locally, ensuring the new service functions as expected.
  • Manual end-to-end testing instructions were provided, requiring a GCP project with Firestore enabled to verify real-world functionality.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@adk-bot adk-bot added the services [Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc label Feb 10, 2026
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a FirestoreSessionService for serverless session persistence, which is a great addition for GCP deployments. The implementation is solid and includes comprehensive unit tests. My review focuses on improving performance and ensuring data consistency under concurrent operations. I've identified several areas where database access can be optimized (e.g., using server-side limits, avoiding N+1 queries, and reducing redundant reads) and have pointed out critical race conditions in state updates that should be addressed by using Firestore transactions.

Comment on lines +216 to +214
if app_state_delta:
current_app_state = await self._get_app_state(app_name)
current_app_state.update(app_state_delta)
await self._set_app_state(app_name, current_app_state)

if user_state_delta:
current_user_state = await self._get_user_state(app_name, user_id)
current_user_state.update(user_state_delta)
await self._set_user_state(app_name, user_id, current_user_state)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The updates to app and user state follow a non-atomic read-modify-write pattern. If multiple sessions are created concurrently for the same app or user, this can lead to race conditions and data loss, as one update may overwrite another. To ensure atomicity and data consistency, these state updates should be performed within a Firestore transaction.

Comment on lines +324 to +315
app_state = await self._get_app_state(app_name)
user_state = await self._get_user_state(app_name, suid)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Fetching app and user state inside the loop is inefficient and causes an N+1 query problem.

  1. App State: _get_app_state should be called once before the loop, as the app_name is constant.
  2. User State: If user_id is provided to list_sessions, _get_user_state should also be called once before the loop. If user_id is None, it needs to remain in the loop.

This refactoring will significantly improve performance by reducing database calls.

Comment on lines 388 to 392
if app_state_delta:
current_app_state = await self._get_app_state(app_name)
current_app_state.update(app_state_delta)
await self._set_app_state(app_name, current_app_state)

if user_state_delta:
current_user_state = await self._get_user_state(
app_name, user_id
)
current_user_state.update(user_state_delta)
await self._set_user_state(app_name, user_id, current_user_state)

if session_state_delta:
stored_data = doc.to_dict()
stored_state = stored_data.get(_FIELD_STATE, {})
stored_state.update(session_state_delta)
await session_ref.update({_FIELD_STATE: stored_state})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The updates to app, user, and session states are performed using a non-atomic read-modify-write pattern. In a concurrent environment, this can lead to race conditions where state updates from one event overwrite another, causing data loss. For example, if two append_event calls run simultaneously for the same app, they might read the same initial app state, and the last one to write will win, discarding the other's changes.

To ensure data consistency, these state updates should be wrapped in a Firestore transaction. Transactions guarantee that the series of operations (read, modify, write) is atomic.

Comment on lines +237 to +228
app_state = await self._get_app_state(app_name)
user_state = await self._get_user_state(app_name, user_id)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code re-fetches the app and user states from Firestore to build the response, even though they might have been fetched and updated just lines before. This can lead to redundant database reads.

To optimize, you could fetch the state at the beginning of the method, apply deltas if they exist, and then reuse the in-memory state for building the response. This would avoid the second read.

Comment on lines +288 to +279
if config and config.num_recent_events:
events = events[-config.num_recent_events :]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Fetching all events and then slicing on the client-side is inefficient, especially for sessions with a long history. It results in unnecessary data transfer and client-side processing.

To optimize this, you should use a server-side limit. The google-cloud-firestore client supports limit_to_last() which can be applied to the query. This will fetch only the required number of recent events from Firestore.

Example:

    if config and config.num_recent_events:
      events_query = events_query.limit_to_last(config.num_recent_events)

    event_docs = events_query.stream()
    # ... process docs ...

    # Then this client-side slicing can be removed.

Comment on lines +350 to +342
events_ref = session_ref.collection(_EVENTS_SUBCOLLECTION)
async for event_doc in events_ref.stream():
await event_doc.reference.delete()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Deleting event documents one by one within a loop is inefficient, as each .delete() call results in a separate network request. For sessions with a large number of events, this can be slow and could potentially exceed rate limits.

A more performant approach is to use a batch write to delete multiple documents in a single request. You can use AsyncWriteBatch from the Firestore client to collect all delete operations and commit them at once.

Adds a new session service backed by Google Cloud Firestore, providing
persistent, serverless session storage. This addresses the gap between
InMemorySessionService (dev-only) and DatabaseSessionService (requires
managing SQL infrastructure) for GCP-native deployments.

The implementation follows established ADK patterns:
- Extends BaseSessionService with all CRUD operations
- Supports three-tier state management (app/user/session)
- Events stored in Firestore subcollections (avoids 1MB doc limit)
- Lazy import via __getattr__ (same pattern as DatabaseSessionService)
- google-cloud-firestore added as optional 'firestore' extra

Ref: google#3776
Co-authored-by: Cursor <[email protected]>
@anmolg1997 anmolg1997 force-pushed the feat/firestore-session-service branch from 1edbca4 to 368a6fc Compare February 10, 2026 15:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

services [Component] This issue is related to runtime services, e.g. sessions, memory, artifacts, etc

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants