Skip to content
Blog / Engineering

Polling Webhooks for Cron and Serverless Agents: Offsets, Leases and 4 Patterns (2026)

Binoy Perera

How a polling webhook queues email events for agents with no public URL: offsets, leases and commits, plus cron, serverless, audit and per-pod patterns in Python.

  • engineering
  • webhooks
  • polling
  • ai-agents
  • python

TL;DR

An AI agent that runs on a schedule, in a sandbox or behind a firewall has no address the internet can post events to, so ordinary webhooks miss it. This article explains how a webhook you read instead of receive keeps every email event for that agent. You'll see how its read positions work, four patterns you can copy, and the mistakes that lose or repeat work in production.

Most agents don't run all day. A support triager wakes every ten minutes. It does its work and exits. A coding agent lives in a sandbox for the length of one task. A finance agent sits behind a corporate firewall that blocks inbound traffic, and an agent on a laptop sleeps when the lid closes.

Email doesn't wait for any of them. A message arrives at 3:12 in the morning. The usual way to hear about it is a webhook, an HTTP request the email provider sends to a public URL you own. An agent with no public URL, or one that isn't running at 3:12, never sees that request. The common workarounds are a tunnel that has to stay up, or a loop that lists the inbox every minute and works out what changed.

A polling webhook removes both. Below we cover what it is and how it remembers what your agent already handled. Then come the identifiers you have to get right, four patterns for agents that start and stop, and what breaks once real traffic arrives.

What is a polling webhook?

A polling webhook is a webhook you read instead of one we deliver. You subscribe to the same event types as a push webhook, such as message.received, and AgentMail keeps the matching events in a queue for that subscription. Your agent fetches them whenever it runs, then marks the ones it finished. Nothing in your setup has to be reachable from the internet.

It is not a list loop. A list loop asks "what is in the inbox now" and leaves you to diff the answer against the last run, which is where duplicate replies and missed messages come from. A polling webhook asks "what happened since I last confirmed", and the server keeps the answer. If you read our older post on building real-time agents with webhooks, its case against list loops still holds. This is a different mechanism.

You read the queue with the Svix SDK's consumer and two calls: receive returns waiting events, and commit confirms them. The announcement post shows the minimal loop, and the full reference is in the docs.

How does the queue know what your agent already handled?

The queue knows because your agent commits an offset, the position of an event in the queue. Every event carries one. When you call commit with an offset, that event and every event before it count as handled, and receive stops returning them.

Anything you received but didn't commit comes back on the next receive. That single rule decides how your agent behaves after a crash. Suppose it reads five events, replies to three and dies. On the next start, events four and five come back, and so does event three if the reply went out but the commit didn't.

So delivery is at least once. A crash between doing the work and committing it means the work can run twice, never zero times. Commit after the side effect, and make the side effect safe to repeat. Committing before the work flips the risk: a crash then loses the event for good.

Two details decide when "comes back" happens. We found both by running the code on this page. A receive takes a lease on the events it returns. Until you commit or the lease runs out, another receive on that consumer id fails with no_available_lease. The default lease held for more than two and a half minutes in our tests. With lease_duration_ms set to 20,000, the uncommitted event came back after about 20 seconds.

The second detail is where a new consumer id starts. By default its first receive starts at the newest event. Anything queued between create and that first read is skipped. Passing starting_position as earliest picks those events up, and a consumer that has committed keeps its own position either way.

Which IDs and tokens matter?

Three identifiers matter, and mixing them up causes most production bugs. The client_id names the subscription. You pass it when you create the polling webhook, and creating again with the same client_id returns the same queue instead of a second one. That is what makes "create on every start" safe.

The token reads the queue. Create returns it. Get and list never do. Each repeat create with the same client_id issues a new token and invalidates the previous one at once. One client_id should therefore back exactly one running worker, and the token deserves the same care as an API key.

The consumer id is a read position inside one queue. You pass it to receive and commit. Two consumer ids on the same token each see every event, and each commits on its own. Most agents use one.

Example: a cron job that drains the queue and exits

A scheduled agent should drain everything waiting, commit as it goes and exit. It can create the subscription on every run, because the same client_id returns the same queue with a fresh token, and only one copy of the job runs at a time.

Python

# cron job: rotate the token, drain the queue, commit, exit (agentmail 2.0.25, svix 2.10.0)import osfrom agentmail import AgentMailfrom svix import AutoConfigConsumerfrom svix.api_internal.message_pollerv2 import MessagePollerv2ConsumerPollOptionsfrom svix.models import SinkInCommon, StartingPositionclient = AgentMail(api_key=os.environ["AGENTMAIL_API_KEY"])inbox_id = os.environ["AGENTMAIL_INBOX_ID"]# same client_id every run: same queue, new token, previous token deadsubscription = client.inboxes.webhooks.polling.create(    inbox_id, client_id="nightly-triage", event_types=["message.received"])consumer = AutoConfigConsumer(subscription.token, SinkInCommon())# a new consumer id starts at the newest event unless told otherwisefrom_start = MessagePollerv2ConsumerPollOptions(starting_position=StartingPosition.EARLIEST)handled = 0while True:    page = consumer.receive("triage", from_start)    for event in page.data:        message = event.payload["message"]  # same object a push webhook would carry        handled += 1  # triage the message here, then commit        consumer.commit("triage", event.offset)    if page.done:        breakprint(f"handled {handled} events, queue drained")# output: handled 5 events, queue drained

The loop ends on page.done, which is true once the queue is empty, so the job never sleeps or waits for mail. Events that arrive after it exits sit in the queue until the next run. Mail that lands at 3:12 gets handled at 3:20, and nothing had to be listening in between.

This uses the inbox route because the key in the example belongs to one inbox. A key scoped to a pod or an inbox has to use its own route. An organization key can use client.webhooks.polling.create and cover every inbox.

Example: a serverless function that replies once per message

A serverless function has two problems a cron job doesn't: several copies can run at once, and a timeout can kill one between the reply and the commit. Handle the first by never creating the subscription inside the function. If two invocations both called create, the second would rotate the token and break the first. Create it once from a deploy step, store the token in your secret manager, and cap the function at one concurrent run.

Handle the second with a short lease and an idempotency key on the reply. A one-minute lease means events from a killed run come back on the next invocation a minute later. Each event has an event_id that stays the same when the event is returned again, and a send that reuses an Idempotency-Key returns the original message instead of sending a second one. The idempotent inbound email post covers that header in depth.

Python

# serverless handler: token from a secret, one reply per event even after a retry (agentmail 2.0.25, svix 2.10.0)import osfrom agentmail import AgentMailfrom svix import AutoConfigConsumerfrom svix.api_internal.message_pollerv2 import MessagePollerv2ConsumerPollOptionsfrom svix.models import SinkInCommon, StartingPositionclient = AgentMail(api_key=os.environ["AGENTMAIL_API_KEY"])consumer = AutoConfigConsumer(os.environ["POLLING_TOKEN"], SinkInCommon())# a timed-out run releases its events after one minute instead of the default leaseoptions = MessagePollerv2ConsumerPollOptions(    starting_position=StartingPosition.EARLIEST, lease_duration_ms=60_000)def handler(request=None):    page = consumer.receive("replier", options)    for event in page.data:        message = event.payload["message"]        client.inboxes.messages.reply(            inbox_id=message["inbox_id"],            message_id=message["message_id"],            to=[message["from_"]],            text="Thanks, we have your request and a person will follow up.",            # a returned event keeps its event_id, so no second reply goes out            request_options={"additional_headers": {"Idempotency-Key": event.payload["event_id"]}},        )        consumer.commit("replier", event.offset)    return {"replied": len(page.data), "more": not page.done}# output: a dict with the number of replies sent and whether events are still waiting

Idempotency keys expire 24 hours after the send. That covers a retry on the next invocation, but not a function that stays broken for two days and then replays a backlog. For that case, also record handled message ids in your own store.

Example: an audit reader on its own consumer id

An audit log, an analytics job or a second agent can read the same events without touching the first agent's position. Give it its own consumer id on the same token. Each consumer id keeps a separate position, so a slow audit job never holds back the agent, and the agent's commits never hide events from the audit job.

Python

# two consumer ids on one token: the agent and the audit log each see every event (agentmail 2.0.25, svix 2.10.0)import osimport timefrom agentmail import AgentMailfrom svix import AutoConfigConsumerfrom svix.api_internal.message_pollerv2 import MessagePollerv2ConsumerPollOptionsfrom svix.models import SinkInCommon, StartingPositionclient = AgentMail(api_key=os.environ["AGENTMAIL_API_KEY"])inbox_id = os.environ["AGENTMAIL_INBOX_ID"]subscription = client.inboxes.webhooks.polling.create(    inbox_id, client_id="audit-demo", event_types=["message.received"])consumer = AutoConfigConsumer(subscription.token, SinkInCommon())from_start = MessagePollerv2ConsumerPollOptions(starting_position=StartingPosition.EARLIEST)client.inboxes.messages.send(    inbox_id=inbox_id, to=[inbox_id], subject="Refund request 2291", text="Please refund order 2291.")time.sleep(15)  # give the event time to reach the queuefor reader in ("agent", "audit"):    page = consumer.receive(reader, from_start)  # without it, both readers skip the message    for event in page.data:        print(reader, event.event_type, event.payload["message"]["subject"])        consumer.commit(reader, event.offset)# demo over: deleting frees the slot and kills the tokenclient.inboxes.webhooks.polling.delete(inbox_id, subscription.webhook_id)# output:# agent message.received Refund request 2291# audit message.received Refund request 2291

Both readers printed the same message. In production the two loops live in different processes. They share the token, so whoever rotates it has to hand the new one to both.

Example: one polling webhook per customer pod

A product that gives each customer its own agents usually puts each customer in a pod, a group of inboxes with its own data and credentials. One polling webhook per pod gives each tenant its own queue and its own worker, so a noisy customer's backlog never delays another's. Name the client_id after the tenant, so get finds the subscription by name and a repeat create is safe.

Python

# one polling webhook per customer pod, one worker per tenant (agentmail 2.0.25)import osfrom agentmail import AgentMailclient = AgentMail(api_key=os.environ["AGENTMAIL_API_KEY"])tenant_pods = {"northwind": os.environ["NORTHWIND_POD_ID"], "contoso": os.environ["CONTOSO_POD_ID"]}tokens = {}for tenant, pod_id in tenant_pods.items():    subscription = client.pods.webhooks.polling.create(        pod_id, client_id=f"{tenant}-worker", event_types=["message.received"]    )    tokens[tenant] = subscription.token  # store each one like an API keyprint(sorted(tokens))# output: ['contoso', 'northwind']

Each organization, pod and inbox holds at most 10 polling webhooks, and an eleventh create answers 403. A repeat create with an existing client_id doesn't count. Per-tenant subscriptions therefore belong on the pod route, where each pod has its own 10, rather than on the organization route. The pods guide covers how pods split data and keys between tenants.

When is a push webhook or WebSocket better?

A push webhook or WebSocket is better when your agent is always running and latency matters. A polling webhook delivers on your next fetch, so its delay is your schedule. A WebSocket delivers the same events as they happen, over a connection your process keeps open. A push webhook also delivers as it happens, if you have a server with a public URL.

Push is strict about downtime. Your endpoint must answer with a 2xx within 15 seconds, and a failed delivery is retried 8 times over about 27.5 hours. An endpoint that keeps failing for 5 days is disabled, and events from the disabled period are not redelivered. If your agent can be offline longer than a retry window, polling is the safer default. The trigger an agent when email arrives post compares the push options.

What breaks in production?

Production failures come from a short list. Most of them are the identifiers again.

  • A second copy of the worker starts and calls create with the same client_id. Its new token invalidates the first copy's, which then fails on every receive. Run one worker per client_id, or create once and share the stored token.
  • Two processes read with the same consumer id. While one holds the lease, the other's receive fails with no_available_lease, and a crashed holder blocks its own restart until the lease runs out. Run one reader per consumer id and set lease_duration_ms to a little more than your slowest batch.
  • A new consumer id reads with the default starting position and skips whatever was queued before its first receive. Pass earliest.
  • Someone calls subscribe() on the consumer. It replaces the event types and inboxes AgentMail set at create time. Pass an empty sink configuration and use only receive and commit.
  • The code commits before it does the work. A crash in between loses the event. Commit last.
  • The API key that created the subscription loses a permission. A token can only read what that key could read when it was made, and a repeat create is then refused. Delete the polling webhook and create it again with the current key.
  • The spam, blocked and unauthenticated variants of message.received need the matching label permission on the key, the same as for push webhooks.
  • The agent runs against the EU region. Polling webhooks are in the US region only for now.

What AgentMail does not do

We don't run or schedule your agent: a cron entry, a function trigger or a long-lived process has to wake it, and events wait until it does. Delivery is at least once, not exactly once, so the handler has to be safe to repeat. Polling webhooks are not on the EU region yet.

FAQ

Questions, answered.

Yes. The AgentMail Node SDK creates the polling webhook, and the Svix Node SDK has the same AutoConfigConsumer with receive and commit. The token and the consumer ids work the same way in both languages, so a Python cron job and a TypeScript audit reader can share one queue.

As quickly as your agent asks. In our tests an event was in the queue about four seconds after the message arrived, and the agent sees it on its next receive. A job that runs every ten minutes has up to ten minutes of delay; if that is too slow, keep a process running and use a WebSocket.

No signature check is involved, because nothing posts to your server. Your code calls out to the queue with the token, so there is no inbound request to forge. Protect the token the way you protect an API key, and rotate it by creating again with the same client_id.

Yes. Leave out inbox_ids and pod_ids and it covers the whole organization, or list up to 10 pods and inboxes. A pod already includes every inbox in it, so listing the pod is enough for a tenant.

Blog

Suggested reading

View all posts

News · November 4, 2026

Introducing Polling Webhooks

Polling webhooks let an AI agent fetch its email events from a queue whenever it runs, with no public URL or open connection. Built in partnership with Svix.

Engineering · September 4, 2026

How to Trigger an Agent When Email Arrives

Trigger an AI agent when new mail arrives with AgentMail message.received, Svix verification, hydrate oversized bodies, then reply in thread.

Prompt

Give yourself access to AgentMail by following the guide at:

https://docs.agentmail.to/agent-onboarding.md

and refer to:

https://docs.agentmail.to/llms.txt

for the documentation index.

Start integrating AgentMail into your AI agents today.