Skip to content
Blog

Headless and Background Agents in ADK: Async Queues and Trigger Runtimes

Running ADK agents without a user in the loop — trigger endpoints, ambient agents, concurrency and retry knobs, idempotent handlers, and queueing patterns for background work.

Published on • November 25, 2026

AI Assistant

Most ADK tutorials assume a chat: a user sends a message, the runner streams events back. Production systems quickly outgrow that shape. A nightly job reconciles invoices. A webhook from CI kicks off a review agent. An event stream wakes an agent that works for minutes with nobody watching. This is the world of headless agents — runs with no interactive user, no streaming consumer, and no natural back-pressure.

ADK’s answer here is the ambient agents model: trigger endpoints that start agent runs in the background, governed by deployment-level concurrency, timeout, and retry limits. The engineering challenge shifts from “render a response” to queueing, idempotency, and observability without a human watching the spinner.

The mental model: a request becomes a run

In interactive mode, the HTTP request is the run — the connection stays open and events flow down it. In trigger mode, the HTTP request only enqueues:

webhook / cron / event
      │
      ▼
trigger endpoint ──▶ admission control (concurrency cap, queue)
      │
      ▼
background agent run (headless — no user, no stream)
      │
      ▼
session events + state + downstream effects

ADK’s ambient runtime enforces the middle box with environment variables:

export ADK_TRIGGER_MAX_CONCURRENT=4     # default 10 (Python)
export ADK_TRIGGER_MAX_RETRIES=3         # failed runs are retried
# runs exceeding 10 minutes are cut off

The endpoint acknowledges quickly; the run proceeds under those bounds. This separation is what lets a burst of webhook traffic degrade into queuing instead of saturation.

Designing the handler

A headless handler must make three decisions: what the trigger carries, how the run is identified, and what happens on retry.

from google.adk.runners import Runner

async def handle_invoice_event(payload: InvoiceEvent, runner: Runner) -> TriggerAck:
    # 1. Validate before touching any agent
    event = InvoiceEvent.model_validate(payload)

    # 2. Deterministic session per entity → retries converge on one session
    session_id = f"invoice-{event.invoice_id}"

    await runner.session_service.create_session(
        app_name="billing_agent", user_id="system:trigger", session_id=session_id
    )

    # 3. Enqueue the run; acknowledge fast
    await QUEUE.put(RunRequest(
        runner=runner,
        app_name="billing_agent",
        user_id="system:trigger",
        session_id=session_id,
        message=text_message(f"Reconcile invoice {event.invoice_id}"),
    ))
    return TriggerAck(received=True)

Notice what’s doing the heavy lifting: the deterministic session ID. If the platform retries the trigger, the retry lands in the same session rather than forking a parallel history — half of idempotency solved by naming.

Idempotency before retries

Retries are only safe if re-running converges. In practice:

  • Key every side effect. Tool calls that write to external systems should carry an idempotency key derived from the event ID; the receiving system dedupes.
  • Check state first. The agent’s first tool call should be “has this already been done?” — session state makes that natural:
    def reconcile(invoice_id: str, tool_context) -> dict:
        if tool_context.state.get(f"done:{invoice_id}"):
            return {"status": "already_reconciled"}
        result = billing.reconcile(invoice_id)
        tool_context.state[f"done:{invoice_id}"] = True
        return {"status": "ok", "result": result}
  • Ordering is not guaranteed. If event N+1 can be processed before N, either make handlers order-independent or per-entity sequence numbers the handler respects (a latest_seq state key that discards stale events).

The async queue in front

For anything beyond trivial volume, put a real queue between admission and execution. Even an in-process asyncio queue gives you the essential properties:

import asyncio

async def worker(q: asyncio.Queue, concurrency: int):
    sem = asyncio.Semaphore(concurrency)

    async def run_one(req: RunRequest):
        async with sem:
            try:
                await drain(runner=req.runner, request=req)
            except Exception:
                logger.exception("background run failed: %s", req.session_id)
                await DEAD_LETTER.put(req)   # don't lose it silently

    while True:
        req = await q.get()
        asyncio.create_task(run_one(req))

For durable work, the same seam accepts Redis, SQS, Pub/Sub, or Cloud Tasks. The properties you need from whatever you pick:

PropertyWhy it matters
At-least-once deliveryCombined with idempotency, gives effectively-once outcomes
Visibility timeout > run deadlineOtherwise the message redelivers while the first run is alive
Dead-letter pathPoison events must not loop forever
Per-entity ordering (optional)When handlers aren’t order-independent

Failure, retry, and the dead-letter queue

ADK’s trigger layer retries failed runs (ADK_TRIGGER_MAX_RETRIES, default 3) and bounds run duration (10 minutes). But your queue has a retry story too — decide how they compose. A sensible layering:

  1. In-run: tool-level retries for transient errors (seconds).
  2. Trigger-level: ADK’s bounded retries for run failures (minutes).
  3. Queue-level: visibility-timeout redelivery for infrastructure failure (longer).
  4. Dead-letter: after all of it, park the event with its full context for a human or an alert.

Always-on rule: escalating failures should stop retrying and start alerting. An event that has failed across all three layers is a bug or poison data, not a transient hiccup.

Observability without a user

Nobody is watching the stream, so the run must narrate itself:

  • Log trigger_id, session_id, invocation_id, llm_calls, elapsed_ms, status for every run.
  • Persist meaningful progress as session state — the session is your debugging transcript. Replaying events shows exactly where a background run went sideways.
  • Alert on queue depth, oldest-message age, dead-letter count, and runs hitting the 10-minute cutoff (a cutoff is a symptom of an agent doing too much per trigger).
  • Keep messages bounded: if one trigger needs 400 model calls, split it into fan-out work rather than raising max_llm_calls forever.

When to use which pattern

PatternUse it when
Trigger endpoint → runOccasional, latency-tolerant events; simplest option
Queue + worker poolBursts, need back-pressure and durable retries
Cron fan-outScheduled sweeps; fan out per entity, run per session
Event stream consumerHigh volume with ordering needs per key
Interactive run in backgroundYou still want a stream — attach later, poll session events

Where to go next

Background runs multiply the failure surface — pair this with global timeouts and execution deadlines and graceful exception handling. The context rules in the InvocationContext lifecycle apply unchanged to headless runs, and enterprise reliability patterns cover operating the whole fleet.

References