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

DatabaseSessionService with postgres and high concurrent requests is throwing psycopg2 DatabaseError

Open jasveer-os opened this issue 1 year ago • 2 comments

When we are load testing agent wrapped as an API with concurrent requests of around 10-20, around 20% of our requests are failing at 'create_session' or 'get_session' of SessionService. The error thrown is : 'psycopg2.DatabaseError: error with status PGRES_TUPLES_OK and no message from the libpq'

Here's the code we've for the API wrapper over root agent:

<all_imports_here>
session_service = DatabaseSessionService(
    db_url="postgresql://username:pwd@url:host/db_name?sslmode=disable",
    pool_pre_ping=True,
    pool_size=10,
    max_overflow=5,
    pool_timeout=30,
    pool_recycle=1800,
)

class ChatAgentQuery:
    async def on_post(self, req: falcon.Request, resp: falcon.Response) -> None:
        try:
            runner = Runner(
                agent=root_agent, 
                app_name=APP_NAME,
                session_service=session_service,
                
            )
            resp.content_type = "text/event-stream"
            resp.cache_control = ["no-cache"]
            resp.set_header("Connection", "keep-alive")

            async def event_generator():
                content = types.Content(role='user', parts=[types.Part(text=query)])
                session_details = await session_service.get_session(app_name=app_name, user_id=rfp_question_id, session_id=session_id)
                if not session_details:
                    await session_service.create_session(app_name=APP_NAME, user_id=user_id, session_id=session_id, state={state_object_here)
                else:
                   state_changes = {existing_session_state_updates_object}
                    actions_with_update = EventActions(state_delta=state_changes)
                    system_event = Event(
                        invocation_id="session_state_meta_data_update",
                        author="system",
                        actions=actions_with_update,
                        timestamp=time.time()
                    )

                    await session_service.append_event(session_details, system_event)

                run_config = RunConfig(streaming_mode='sse')
                async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content, run_config=run_config):                    

                    for index, part in enumerate(event.content.parts):
                        if part.text:
                            chunk_data = {}
                            chunk_data["token"] = part.text
                            chunk_data["is_complete"] = False
                            if event.is_final_response():
                                chunk_data["session_id"] = session_id
                                if index == len(event.content.parts) - 1:
                                    chunk_data["is_complete"] = True
                                    chunk_data["token"] = ""
                                else:
                                    chunk_data["is_complete"] = False
                            sse_message = f"{json.dumps(chunk_data)}\n\n"
                            yield sse_message.encode("utf-8")
                    
                    if event.is_final_response():
                        break

            resp.stream = event_generator()

        except Exception as e:
            self.logger.exception(f"Failed to answer user query, {str(e)}")
            resp.status = falcon.HTTP_500
            resp.media = {"error": "Failed to answer user query"}

Some of the things I've debugged and tried based on error stack traces are:

  1. Keeping user_id unique while receiving requests (Some SessionService errors were showing that internally create_session fetches all sessions of a user
  2. Keeping app_id unique while receiving requests (Some SessionService errors were showing that internally create_session fetches all sessions simply.
  3. Tried assigning session_service local to API request, i.e. not sharing it at global level in service to avoid pool connections stale/sharing, but still the same.

None of the above resolved the error as such. Also, the ADK is tightly coupled with psycopg2-binary (v2), while the latest is v3, which can help resolve as this was reported earlier in older versions as well in psycopg.

Expected behavior is that the SessionService in agent API should be scalable enough to support 100 concurrent requests.

OS: MacOS/Linux Python version: 3.10 ADK version: 1.15.0

Are you using LiteLLM: Yes (OpenAI) Which model is being used(e.g. gpt 4.1)

jasveer-os avatar Sep 30 '25 21:09 jasveer-os

hey @DeanChensj is there any update here?

jasveer-os avatar Oct 16 '25 07:10 jasveer-os

@jasveer-os This issue was resolved in ADK v1.17.0+ through a complete rewrite of DatabaseSessionService to use full async operations with SQLAlchemy's async engine.

The error you're seeing is caused by synchronous psycopg2 operations blocking the async event loop under concurrent load in v1.15.0.

Upgrade to ADK v1.20.0 and optionally switch to asyncpg driver using postgresql+asyncpg:// in your connection URL for best performance - this should eliminate the 20% failure rate you're experiencing.

The new implementation properly handles concurrent requests with async connection pooling.

Thanks!

surajksharma07 avatar Dec 05 '25 09:12 surajksharma07