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

ADK import overhead (8-20s) causes slow cold starts

Open pentium10 opened this issue 1 year ago • 35 comments

When you deploy a basic agent to Cloud Run, somehow the framework core is so slow to boot that is unusable.

25s + cold starts constantly, using the bare minimum examples from Tutorial.

Improvements need to be made here, to reduce boilerplate for cold starts.

Image

Dockerfile

FROM python:3.13-slim
WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

RUN adduser --disabled-password --gecos "" myuser && \
    chown -R myuser:myuser /app

COPY . .

USER myuser

ENV PATH="/home/myuser/.local/bin:$PATH"

CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port $PORT"]

main.py

import os

import uvicorn
from google.adk.cli.fast_api import get_fast_api_app

# Get the directory where main.py is located
AGENT_DIR = os.path.dirname(os.path.abspath(__file__))
# Example session service URI (e.g., SQLite)
SESSION_SERVICE_URI = "sqlite:///./sessions.db"
# Example allowed origins for CORS
ALLOWED_ORIGINS = ["http://localhost", "http://localhost:8080", "*"]
# Set web=True if you intend to serve a web interface, False otherwise
SERVE_WEB_INTERFACE = True

# Call the function to get the FastAPI app instance
# Ensure the agent directory name ('capital_agent') matches your agent folder
app = get_fast_api_app(
    agents_dir=AGENT_DIR,
    session_service_uri=SESSION_SERVICE_URI,
    allow_origins=ALLOWED_ORIGINS,
    web=SERVE_WEB_INTERFACE,
)

# You can add more FastAPI routes or configurations below if needed
# Example:
# @app.get("/hello")
# async def read_root():
#     return {"Hello": "World"}

if __name__ == "__main__":
    # Use the PORT environment variable provided by Cloud Run, defaulting to 8080
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

my cold start command is to create a session

curl -X POST 
    "$APP_URL/apps/demo_agent/users/api_user/sessions/api_session_1" \
    -H "Content-Type: application/json" \
    -d '{"state": {}}' # Optional initial state

pentium10 avatar Aug 08 '25 07:08 pentium10

@pentium10 Is that because the cloud run instance is not up? What if you set minimum 1 instance for that cloud run app?

Jacksunwei avatar Aug 08 '25 16:08 Jacksunwei

@Jacksunwei Its the cold start. So the initial boot of the container and app. To boot one instance takes 20 seconds more. To boot additional instances another 20 seconds. Minimum instance doesn't help this world as its a serverless environment, you pay per use. So you want to have scale to zero.

pentium10 avatar Aug 08 '25 16:08 pentium10

I think that's the general limitation for all container-based pay-as-you-use cloud service, incl. Cloud Run.

ADK as a software has no control over that.

Jacksunwei avatar Aug 08 '25 16:08 Jacksunwei

I cannot agree on the generalities. I deliver talks on Cloud Run since the begining I know Cloud Run service entirely, crafted workshops and so on. Been deep involved so I know something is off with ADK here. ADK has some issue on loading of libraries. It loads too much than needs to run the agent. 20 seconds is huge. At most it should be 2-3 seconds (even that is slow), but a <sub 1second would be ideal.

pentium10 avatar Aug 08 '25 16:08 pentium10

Could agree @pentium10, it is a performance issue regarding ADK. So, it takes too long to load and start to serve it causes massive cold start latencies. Cold start is the end result of slow library in this case not about the serverless architecture.

calganaygun avatar Aug 08 '25 17:08 calganaygun

I might be wrong, but I suspect the cold start delay is caused by eager imports in __init__.py. From reviewing the source, it seems the ADK loads most lower-level modules in these init files.

In my tests, even importing a specific submodule still triggers unrelated components to load because the parent __init__.py is executed.

calganaygun avatar Aug 08 '25 19:08 calganaygun

I agree with the comments above. I seems a general pattern that has been applied through the entirety of ADK is to initialize global objects inside a module's __init__ scope or individual Python file scope. While I could understand the rationale from Python's lack of dependency injection, it creates various fundamental problems on resource allocation in memory and also on testability:

An example is the AgentLoader functionality [1]. It expects to be pointed to a python module, where it will look for the export of root_agent inside an agent directory. But before we can construct a functional Agent, it might have to consume configuration such as VertexAI Engine ID, GCS bucket name, etc. This forces us to also design our configuration as a global singleton as well, otherwise agents can not import and share underlying configuration

When writing unittests for an Agent, we now have to be very careful which modules are imported. Even something as simple as @patch("my_package.agent_location.my_agent.main.some_function") will trigger a full import of the agent, its configuration, any sub-agents, and any configuration they might have. Let's say we use a GmailApiToolset, we already require access to GCP credentials in order to convert the OIDC spec to OpenAPI spec [2]

This forces all users of ADK to essentially write a lot of boilerplate around global imports, or discard the AgentLoader altogether and create factory patterns to generate agents elsewhere.

I'd like to hear if other users are also encountering the same issues.

[1] https://github.com/google/adk-python/blob/main/src/google/adk/cli/utils/agent_loader.py#L37 [2] https://github.com/google/adk-python/blob/main/src/google/adk/tools/google_api_tool/googleapi_to_openapi_converter.py#L63

arryon avatar Aug 09 '25 09:08 arryon

I might be wrong, but I suspect the cold start delay is caused by eager imports in __init__.py. From reviewing the source, it seems the ADK loads most lower-level modules in these init files.

In my tests, even importing a specific submodule still triggers unrelated components to load because the parent __init__.py is executed.

yes this is what happens when I profile the adk web command, 50% of trace time is spent on adk/__init__.py, where aiplatform/__init__ contributes the most. This is quite a blocker to use adk for prod.

yshuolu avatar Aug 14 '25 09:08 yshuolu

For what it's worth: ADK 1.13.0 takes about 8 seconds just to import on my linux VM. This is a real outlier for "heavyweight" Python libraries, let alone one that doesn't perform compute-heavy tasks.

$ time python -c "from google.adk.agents import BaseAgent"

real    0m8.022s
user    0m7.492s
sys     0m0.523s

And for comparison:

$ time python -c "import numpy as np"

real    0m0.162s
user    0m0.283s
sys     0m0.194s
$ time python -c "import pandas as pd"

real    0m0.552s
user    0m0.609s
sys     0m0.256s
$ time python -c "from pydantic_ai import Agent"

real    0m0.695s
user    0m0.626s
sys     0m0.066s

For us, this long import time has two significant effects:

  • Developer Experience: As a "code-first" library, the 8-second delay after each code/config edit significantly slows down the development and debugging cycle.
  • Production Environments: It poses a major challenge for serverless platforms like AWS Lambda or Google Cloud Functions, where cold start times are critical. An 8-second import consumes a large portion of a typical default timeout (e.g., Lambda's is 10 seconds).

crw2998 avatar Aug 29 '25 23:08 crw2998

Thanks, @crw2998 ! I think this aligns with our observe. We could take a look at this.


(edit) here is the colab that I think we can target for optimize. For anyone, feel free to comment below for your use case

https://colab.research.google.com/drive/17K11VWBu5jMpvFaFFpr6A38Gq9i9D2V5?usp=sharing

Jacksunwei avatar Sep 16 '25 19:09 Jacksunwei

Adding my team's use case , we are trying to integrate the adk(1.14.1) into our Django application , the import time varies, but experiencing anywhere between 15-30s added time in startup. This is acceptable to us as a cold start, however development and debugging has been a nightmare as that added time is also affecting hot-reload making it quite cold.

JokingLemon avatar Sep 17 '25 05:09 JokingLemon

We use ADK on Messenger chatbot, and Meta needs sub 3 second response time, right now the effect of looong cold start is that Meta is sending repeatedly the callback until gets a response, and the chatbot responds slow + greats the user 4-5 times as a side effect.

pentium10 avatar Sep 17 '25 05:09 pentium10

any progress here? This is a huge issue for us scaling pods on cloud run.

srochiramani avatar Oct 23 '25 15:10 srochiramani

Hi folks, thanks for reporting this and investigate.

We are looking into this. If you have any suggestions on the solution or findings, feel free to post them.

hangfei avatar Oct 24 '25 19:10 hangfei

Summary of Duplicate Issues and Key Findings

This issue is tracking ADK's import performance problem that affects cold starts and development experience across all environments. We've consolidated several related issues here:

  • #157 (April 2025) - First report: 29s to import Agent in notebook
  • #2704 (Aug 2025) - 20s cold starts, 5-10s response times
  • #3041 (Sep 2025) - 3s to import specific modules like LLMRegistry

Root Cause (Identified by Community)

Eager imports in __init__.py files - ADK loads most lower-level modules at import time, even when only a specific submodule is needed.

Analysis from @calganaygun (comment):

"I suspect the cold start delay is caused by eager imports in __init__.py. From reviewing the source, it seems ADK loads most lower-level modules in these init files. Even importing a specific submodule still triggers unrelated components to load because the parent __init__.py is executed."

Profiling data from @yshuolu (comment):

"50% of trace time is spent on adk/__init__.py, where aiplatform/__init__ contributes the most."


Impact Benchmarks

Import Time Comparisons (from @crw2998, comment):

numpy import:        0.16s
pandas import:       0.55s
pydantic_ai import:  0.70s
google-adk import:   8.00s ⚠️

Latest Testing (@JokingLemon, comment):

  • ADK v1.16 in venv: 4.5-5s
  • ADK v1.16 with debugger: 14-16s
  • ADK v1.14.1 in Django: 15-30s

Cold Start Impact:

  • Local api_server: 20s cold start (#2704)
  • Cloud Run: 25s+ cold start (#2433)
  • First response time: 5-10s even after startup (#2704)

Affected Environments

Production Deployments

Development Experience

  • ✅ Django hot-reload - 15-30s reload delays (@JokingLemon, comment)
  • ✅ Jupyter notebooks - 29s import time (#157 original report)
  • ✅ Local debugging - 14-16s with debugger (@JokingLemon, comment)
  • ✅ adk web - Slow startup during development (@yshuolu, comment)

Real-World Production Impact

  • Meta Messenger integration (@pentium10, comment): Requires <3s response time, currently causes duplicate greetings due to slow cold starts
  • Chat applications (#2704): ADK feels "too heavy for real-world chat UX"

Technical Details

Global Object Initialization Problem (@arryon, comment):

"A general pattern applied through ADK is to initialize global objects inside a module's __init__ scope or individual Python file scope. This creates fundamental problems on resource allocation in memory and also on testability."

Examples of problematic imports:

# Takes ~3 seconds (#3041)
from google.adk.models import LLMRegistry, BaseLlm
from google.adk.models.lite_llm import LiteLlm

# Takes ~8 seconds (#2433)
from google.adk.agents import BaseAgent

# Even importing specific submodule triggers full load (#2433)

Progress Update

Community Investigation:

  • Root cause identified: Eager imports in __init__.py files
  • Profiling completed showing 50% of time in adk/__init__.py with aiplatform/__init__ as major contributor
  • Global object initialization pattern identified as architectural issue

Testing Results:

  • No improvement observed between v1.8.0 → v1.16
  • Latest measurements (Oct 2025) still show 4.5-5s in venv, 14-16s with debugger
  • Issue persists across all deployment environments

Current Status:

  • Team is investigating
  • Optimization Colab notebook created: https://colab.research.google.com/drive/17K11VWBu5jMpvFaFFpr6A38Gq9i9D2V5?usp=sharing

If you're experiencing this issue, please add:

  • Your ADK version
  • Environment (Cloud Run, Lambda, local, etc.)
  • Import time measurements
  • Production impact details

Jacksunwei avatar Oct 28 '25 04:10 Jacksunwei

This is a critical issue, as it has been already reported. Is there any process to tag the severity ?

It's seems like it has been reported a few months ago but that most information comes from the community.

@pentium10 @calganaygun @arryon @yshuolu @crw2998 @JokingLemon @srochiramani I recommend you rise the issue through your GCP customer representative. I will do so on my side.

BertrandDechoux avatar Oct 31 '25 07:10 BertrandDechoux

My client is using

  • GCP cloud run
  • adk-python 1.9.0

And is (was?) planning a large scale use in a public facing chatbot.

The adk version is a bit old. We are planning to update it. However, as commented in this issue, it's already known that it won't reduce the slow cold start.

I probably won't have time to measure exactly the import time of adk-python in our context. But the results are very likely the same are reported.

The title of the issue is misleading, the cold startup time in production is closer to what @pentium10 reported

25s +

From what I understand, if there is a need to deploy a scalable chatbot, only two solutions exist now

  • not deploy it
  • use another library (and in that case why bother with Gemini and GCP?)

BertrandDechoux avatar Oct 31 '25 07:10 BertrandDechoux

🚀 Follow-up & Deep Dive: An experimental + unofficial mitigation for the 30s Cold Start

I'm the original author of this issue and wanted to follow up with a detailed report on a successful, albeit experimental, solution I've developed to reduce cold-starts.

After extensive testing, I can confirm the root cause is the eager import cascade 🔍 within the library. To solve this, I went down a deep rabbit hole exploring various metaprogramming techniques for lazy-loading. Many of these attempts (like simple module proxies) failed due to the library's complex circular dependencies and fragile relative imports.

The strategy that finally worked was a hybrid lazy-loading approach ✨ managed by a custom build.py script. Here’s how it works:

  1. It identifies "sensitive" directories that are critical for startup (like the top-level package and the cli directory) and applies a gentle optimization, leaving their __init__.py files untouched.
  2. For all other sub-packages (agents, flows, etc.), it aggressively replaces their __init__.py files with a lightweight, lazy-loading shim.

🔥This shim stops the import cascade dead in its tracks. The modules are only loaded from disk when an attribute from them is actually accessed for the first time. This approach respects the fragile entry points of the library while delivering a massive performance win everywhere else.

The results are very positive ✅. By integrating this process into our Docker build for a Cloud Run deployment, we have reliably reduced our application's cold start time from over 24 seconds down to ~9 seconds. On a second project we reduced cold starts from 30s to 14 seconds.


I've written a detailed article explaining the entire journey, the failed attempts, and the final solution:

📖 Medium Article: Hacking ADK's Importer: How We Slashed 24-Second Cold Start in Half

I have also published the build.py script and a full README in a GitHub repository for anyone who wants to experiment with this approach:

🛠️ GitHub Repository: https://github.com/pentium10/adk-minification-experiment

Disclaimer: ⚠️ This is an unofficial and experimental workaround. It's a pragmatic hack that works for our use case but may be fragile between library versions.

I hope this detailed analysis and working solution can help others facing similar issues and provide valuable data for the framework's maintainers.

pentium10 avatar Oct 31 '25 21:10 pentium10

3 months already. Any concrete updates or plan to work on this? ☹️

blah-mad avatar Nov 04 '25 01:11 blah-mad

We are planning to work on it this week. Sorry for the delay. Stay tuned for an update.

wuliang229 avatar Nov 04 '25 01:11 wuliang229