---
title: "Headless and Background Agents in ADK: Async Queues and Trigger Runtimes"
date: "2026-11-25T08:00:00+07:00"
description: "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."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-headless-background-agents-async-queues.jpg"
alt: "Background worker queue feeding agent runs without a user present"
tags: ['google-adk', 'ambient-agents', 'background-jobs', 'queues', 'python']
---

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:

```bash
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.

```python
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:
  ```python
  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:

```python
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:

| Property | Why it matters |
|---|---|
| **At-least-once delivery** | Combined with idempotency, gives effectively-once outcomes |
| **Visibility timeout > run deadline** | Otherwise the message redelivers while the first run is alive |
| **Dead-letter path** | Poison 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

| Pattern | Use it when |
|---|---|
| **Trigger endpoint → run** | Occasional, latency-tolerant events; simplest option |
| **Queue + worker pool** | Bursts, need back-pressure and durable retries |
| **Cron fan-out** | Scheduled sweeps; fan out per entity, run per session |
| **Event stream consumer** | High volume with ordering needs per key |
| **Interactive run in background** | You 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](/blog/adk-global-timeouts-execution-deadlines) and [graceful exception handling](/blog/adk-agent-exceptions-graceful-fallback). The context rules in [the `InvocationContext` lifecycle](/blog/adk-invocationcontext-lifecycle-thread-safety) apply unchanged to headless runs, and [enterprise reliability patterns](/blog/enterprise-adk-assistants-reliability-latency-cost) cover operating the whole fleet.

## References

- [Trigger actions with Ambient Agents](https://adk.dev/runtime/ambient-agents/)
- [Agent Runtime](https://adk.dev/runtime/)
- [Runtime Configuration](https://adk.dev/runtime/runconfig/)
- [google/adk-python](https://github.com/google/adk-python)
