Skip to content
Blog

Synchronous vs Asynchronous Tool Implementations: When to Use async def

Blocking tools stall the event loop and your latency budget. How ADK executes sync and async tools, when async actually helps, fan-out with gather, CPU-bound work, timeouts and cancellation, and a decision guide.

Published on • November 27, 2026

AI Assistant

Python’s default is to do one thing at a time, and the ADK event loop is no exception: a tool that blocks for three seconds blocks everything sharing that loop. The symptom is sneaky — one slow tool doesn’t just cost you three seconds, it delays every other request your process is serving, and it looks like an unexplained latency spike under load.

This tutorial explains how ADK runs tools, when async def genuinely pays, and how to structure tool code so the loop stays responsive.

What ADK does with your function

When the model calls a tool, the framework executes it and packages the return value into the conversation. Two cases:

async def tool — awaited on the event loop. It cooperates with everything else: while it waits on I/O, other requests, events, and responses keep flowing.

def (sync) tool — runs on the loop’s thread by default in the common execution mode, meaning it blocks while it runs. A sync tool doing network I/O or time.sleep(3) freezes the loop for that duration.

Some execution modes offload blocking work to a thread pool (ADK’s tool execution configuration exposes sequential vs parallel execution options), but you should not rely on an offload you haven’t verified: write the tool as async when the work is I/O-bound and you control it.

When each shape is right

Tool workShapeWhy
HTTP call, DB query, queue publishasync defI/O wait; cooperative awaiting is free
Multiple upstream calls the tool can make at onceasync def + gatherParallel instead of sequential
CPU-bound compute (parse 50 MB, image transform)sync, in an executor / workerBlocking is unavoidable; move it off-loop
In-memory dict lookupsync, trivialFast enough that shape doesn’t matter
Long-running job (minutes)LongRunningFunctionToolDon’t block at all — pause and resume

The real rule: async is for waiting, not for computing. Wrapping a CPU-heavy computation in async def without an executor just moves the blocking onto the loop anyway.

Patterns

Async with concurrency inside the tool

import asyncio
import httpx

async def fetch_account_health(accounts: list[str]) -> dict:
    """Fetch health status for several accounts at once.

    Args:
        accounts (list[str]): Account IDs to check.
    """
    async with httpx.AsyncClient(timeout=5) as client:
        responses = await asyncio.gather(
            *(client.get(f'{API}/{a}') for a in accounts),
            return_exceptions=True,
        )

    results, errors = [], []
    for acct, resp in zip(accounts, responses):
        if isinstance(resp, Exception):
            errors.append(acct)
        else:
            results.append({'id': acct, 'state': resp.json()['state']})

    return {
        'status': 'partial' if errors else 'success',
        'accounts': results,
        'failed': errors,
        'summary': f'{len(results)}/{len(accounts)} accounts healthy.',
    }

return_exceptions=True is essential: one dead upstream shouldn’t cancel the other calls. And the partial-success shape (status: 'partial', explicit failed list) lets the model decide what to tell the user rather than failing the whole turn.

Keep the event loop free of surprises

# Blocking (don't do this on the loop):
def lookup_user(user_id: str) -> dict:
    time.sleep(0.5)
    return db.query(...)          # sync driver, blocking socket

# Cooperative:
async def lookup_user(user_id: str) -> dict:
    return await db.fetch_one(...)   # async driver

# CPU-bound: offload it, even from an async tool
async def parse_report(path: str) -> dict:
    result = await asyncio.to_thread(parse_large_file, path)   # frees the loop
    return {'status': 'success', 'rows': result.row_count}

Choices that matter as much as async def: use async database and HTTP drivers. An async def tool that calls a blocking psycopg2 query blocks just as hard as a sync one — the keyword changed, the behaviour didn’t.

Bound everything

async def call_upstream(payload: dict) -> dict:
    try:
        async with httpx.AsyncClient(timeout=(2.0, 8.0)) as client:
            resp = await asyncio.wait_for(client.post(URL, json=payload), timeout=10)
            resp.raise_for_status()
    except asyncio.TimeoutError:
        return {'status': 'error', 'error_message': 'Upstream timed out after 10s; suggest retrying once.'}
    return {'status': 'success', 'result': resp.json()}

Timeouts belong in the tool because that’s where the cost is bounded. Cancellation also propagates: if a run is cancelled, an async tool awaiting I/O is interruptible; a stuck sync tool is not.

Fan-out across tools

ADK can run multiple tool calls from one model response concurrently when execution is configured for parallel tool execution. Design for that:

  • Don’t assume ordering between sibling tool calls in the same step.
  • No shared mutable state without synchronisation; prefer ToolContext.state writes that the framework sequences.
  • Idempotency — concurrent retries plus side effects is where duplicate writes come from (see rate limits and backoff).

Decision guide

  1. Is the work a job (seconds to minutes)? → LongRunningFunctionTool, not a blocking call.
  2. Is it I/O? → async def with async drivers, timeouts on every call.
  3. Is it CPU-bound? → run it off-loop (asyncio.to_thread, a process pool, or a worker) and keep the tool’s own body thin.
  4. Is it trivial in-memory work? → plain def is fine and simplest.

Measure rather than guess: log per-tool duration, and watch your service’s event-loop lag under load. If p95 tool duration is fine but user-facing p95 doubles, the loop is probably blocked somewhere you didn’t expect.

Takeaways

  • Sync tools block the shared event loop; async tools wait cooperatively. Only one of those scales with concurrency.
  • async def only helps if the callee is actually async — blocking drivers and CPU work inside an async tool still stall the loop.
  • Use gather with return_exceptions=True for fan-out, return partial-success shapes, and bound every upstream call with timeouts.
  • Offload CPU-bound work with asyncio.to_thread or a worker; use LongRunningFunctionTool for jobs measured in minutes.
  • Verify your tool execution mode (sequential/parallel) and test under concurrency — the bug only appears under load.

Further reading