Serverless, Streaming APIs, Queues and State
The hardest part of serving an agent is that the answer takes longer than a normal web request.
Use a direct request and response only for short tasks. For longer ones, stream progress or accept a job, return its identifier at once and let workers process it from a queue. Keep progress in a durable store, assume every message may be delivered more than once, and check each serverless platform's time limits before you design around it.
What you will learn: how to choose an interaction style, design a task API, use streaming and callbacks, fit agents into serverless platforms, run a queue with leases and retries and store state so that work survives failures.
Prerequisites: Deploying Agents to Production. The Agent Loop: Observe, Reason, Plan, Act, Reflect explains the loops that make run time vary.
The example runs in November 2026 with Python 3.13 and only the standard library, using an in-memory SQLite database in place of a queue service and a pretend clock. Platform limits quoted here were read from vendor documentation or announcements in November 2026 and change, so confirm them for your region and plan.
Why agent requests are different
A typical web request reads a database and returns in well under a second. An agent may call a model several times, search documents, run tools and wait for a person's approval. Two runs of the same task can differ widely in length, because the model decides how many steps to take.
Long open requests are fragile. Browsers, proxies, load balancers and platforms all have time limits. A phone loses signal. A release replaces the server. If the only record of the task is the open connection, any of these loses the work and the user usually retries, paying for it twice.
Four interaction styles
| Style | How it works | Use when |
|---|---|---|
| Synchronous | One request, one complete reply | The slowest realistic run is a few seconds |
| Streaming | The reply arrives in pieces on one connection | A person is watching and wants early output |
| WebSocket | A lasting two-way connection | Voice, live collaboration or frequent interruptions |
| Asynchronous job | Return an identifier, then poll or receive a callback | Runs last minutes or hours, or need approval |
These combine well. A common design creates a job, then lets the client open a stream to watch it. If the connection drops, the job continues and the client reconnects.
Designing a task API
A small, predictable set of operations covers most needs:
| Operation | Example | Notes |
|---|---|---|
| Create | POST /tasks | Returns 202 Accepted with a task identifier |
| Read | GET /tasks/{id} | State, progress, result or error |
| Watch | GET /tasks/{id}/events | Stream that can resume from a position |
| Answer | POST /tasks/{id}/input | Supply approval or missing information |
| Cancel | POST /tasks/{id}/cancel | A request that workers check between steps |
Give tasks a small set of named states, such as queued, running, waiting for input, succeeded, failed and canceled. Document which states are final.
Three details prevent most trouble:
- Idempotency key. The client sends a unique key with each create call. A repeat returns the same task instead of starting another.
- Ownership check. Every read and write verifies that this caller may see this task. A hard-to-guess identifier is not authorization.
- Structured errors. Say what failed, whether retrying can help and when to retry.
Streaming that survives disconnection
Server-sent events send a one-way stream over ordinary HTTP, and browsers can reconnect automatically. A WebSocket allows both sides to send at any time but needs more care with routing, authentication and reconnection.
Stream events, not just text, so that interfaces can show what is happening:
id: 41
event: step
data: {"tool": "search_orders", "status": "started"}
id: 42
event: text
data: {"delta": "I found two orders that match."}
id: 43
event: state
data: {"state": "waiting_for_input", "question": "Which order?"}
Number the events and keep them in the task store. After a disconnect, the client says which number it saw last and receives the rest. Send a small keep-alive message during long pauses, and check that no proxy buffers the whole stream before delivering it.
Progress events can leak internal tool names, file paths, other users' data or unfinished reasoning. Decide which fields are safe and filter them on the server. If output must pass a safety check before a person reads it, streaming raw tokens defeats that check.
Serverless platforms
In a serverless platform you deploy a function or container and the provider starts and stops instances as work arrives. Idle cost is low and there are no servers to patch. The limits are the main design constraint.
| Service | Limit seen in November 2026 |
|---|---|
| AWS Lambda standard functions | 15 minutes per invocation |
| AWS Lambda Managed Instances | 90 minutes for asynchronous and event-source invocations |
| Google Cloud Run services | Request timeout 5 minutes by default, up to 60 |
| Google Cloud Run jobs | Up to 7 days per task, 1 hour with GPUs |
| Amazon Bedrock AgentCore Runtime | Idle timeout 15 minutes by default; maximum session lifetime 8 hours by default on microVMs |
Sources: the AWS 90-minute timeout announcement, which also describes durable executions lasting up to a year; Cloud Run quotas; and AgentCore lifecycle settings. On Cloud Run, WebSocket connections are also subject to the request timeout, so clients must be ready to reconnect.
Check more than duration:
- Cold starts add delay when a new instance loads libraries or indexes.
- Concurrency settings decide how many tasks share an instance and its memory.
- Payload and response size limits affect documents and long streams.
- Billing may count the time spent waiting for a model.
- Scale-out speed can overwhelm a database or a provider quota.
- Background work after the reply may be paused or throttled unless the platform supports it.
An agent that fits inside one invocation today may not after a new tool is added. If a task can exceed the limit, split it into steps that each save progress, or move long work to jobs, containers or a durable workflow service.
Background jobs and queues
A queue separates accepting work from doing it. It absorbs bursts, lets workers scale independently and keeps tasks safe while workers restart.
A lease, often called a visibility timeout, hides a claimed message for a period. If the worker finishes, it removes the message. If the worker disappears, the lease expires and another worker receives it. Long tasks must renew the lease while they work.
Leases, retries and a dead letter
The example builds the essentials on SQLite: duplicate submissions, an expired lease, a worker that finishes too late and a task that always fails.
"""An asynchronous job API in miniature: submit, lease, retry, dead letter."""
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("""CREATE TABLE jobs(
id INTEGER PRIMARY KEY, request_key TEXT UNIQUE, task TEXT,
state TEXT DEFAULT 'queued', attempts INTEGER DEFAULT 0,
lease_until INTEGER DEFAULT 0, owner TEXT)""")
def submit(request_key, task):
"""The same request key never creates a second job."""
db.execute("INSERT OR IGNORE INTO jobs(request_key, task) VALUES (?, ?)",
(request_key, task))
return db.execute("SELECT id FROM jobs WHERE request_key = ?",
(request_key,)).fetchone()[0]
def claim(worker, now, lease=30, max_attempts=3):
db.execute("""UPDATE jobs SET state = 'dead' WHERE state = 'running'
AND lease_until <= ? AND attempts >= ?""", (now, max_attempts))
row = db.execute("""SELECT id FROM jobs WHERE state = 'queued'
OR (state = 'running' AND lease_until <= ?)
ORDER BY id LIMIT 1""", (now,)).fetchone()
if not row:
return None
db.execute("""UPDATE jobs SET state = 'running', owner = ?, lease_until = ?,
attempts = attempts + 1 WHERE id = ?""", (worker, now + lease, row[0]))
return row[0]
def finish(job, worker):
"""Only the current owner may complete the job."""
changed = db.execute("""UPDATE jobs SET state = 'done'
WHERE id = ? AND owner = ? AND state = 'running'""", (job, worker)).rowcount
return changed == 1
if __name__ == "__main__":
first = submit("req-1", "summarize contracts")
again = submit("req-1", "summarize contracts")
print(f"submitted twice, job ids: {first} and {again}")
print("t=0 A claims job", claim("A", 0))
print("t=10 B claims job", claim("B", 10))
print("t=40 B claims job", claim("B", 40), "(A's lease expired)")
print("t=45 A finishes:", finish(first, "A"), "(stale owner rejected)")
print("t=50 B finishes:", finish(first, "B"))
bad = submit("req-2", "task that always crashes")
for now in (100, 140, 180, 220):
print(f"t={now} claim:", claim("C", now))
print("job", bad, "state:",
db.execute("SELECT state, attempts FROM jobs WHERE id = ?", (bad,)).fetchone())
Output:
submitted twice, job ids: 1 and 1
t=0 A claims job 1
t=10 B claims job None
t=40 B claims job 1 (A's lease expired)
t=45 A finishes: False (stale owner rejected)
t=50 B finishes: True
t=100 claim: 2
t=140 claim: 2
t=180 claim: 2
t=220 claim: None
job 2 state: ('dead', 3)
Read the output in order:
- The repeated request created one job, because the request key is unique.
- Worker B got nothing while A held the lease.
- After the lease expired, B took the job. A was merely slow, so both may have done some of the work.
- A's late completion was rejected because A no longer owned the job.
- The failing task was claimed three times and then parked as dead for a person to inspect.
The ownership check protects only the database record. If A had already sent an email, rejecting its completion would not unsend it. Actions need their own protection (Reliable Tool Execution and Error Recovery). This single-process sketch also claims jobs in two statements; with several processes, use the atomic claim your database or queue service provides.
Assume messages arrive more than once
Many queues promise at-least-once delivery. Some offer exactly-once features within their own boundary, but that does not extend to the outside systems your tools call. Design handlers so that repeating them is safe:
| Risk | Protection |
|---|---|
| Duplicate message | Record processed identifiers and check them first |
| Crash after an action, before saving | Idempotency key sent to the tool, or look before acting |
| Saved state but message not sent | Write both in one transaction, then publish from that record |
| Messages out of order | Carry a version number and ignore older ones |
| Message that always fails | Retry limit, then a dead-letter queue with an owner |
| Retry storm during an outage | Increasing delays with random jitter and a circuit breaker |
The third row is the outbox pattern: the task change and the message to be sent are stored together, and a separate process delivers messages from the table. It avoids the gap where one write succeeds and the other fails.
Queue design for fairness and urgency
- Separate interactive and batch work so a nightly run cannot delay people.
- Limit tasks in progress per tenant, not only in total (Scaling, Hardware, Quotas and Caching).
- Give messages an expiry: answering an old chat request may be worse than failing it.
- Keep messages small. Put documents in object storage and send a reference.
- Watch the age of the oldest message, which shows user impact better than count alone.
- Review the dead-letter queue on a schedule and add its cases to your tests.
Event-driven triggers and webhooks
Agents often start because something happened: a file arrived, a ticket changed or a schedule fired. Treat each event as untrusted input. Event-Driven and Background Agents covers trigger design in detail.
When your service calls a customer back with a webhook:
- Sign each delivery and include a timestamp, so the receiver can verify the sender and reject old copies.
- Retry with increasing delays and stop after a defined period.
- Include an event identifier so duplicates can be ignored.
- Send a reference rather than sensitive results, and let the receiver fetch them with authentication.
- Check destination addresses so users cannot point callbacks at internal systems.
Durable state and checkpoints
Workers should be replaceable. Everything needed to continue a task belongs outside them:
| Data | Suitable store | Retention question |
|---|---|---|
| Task record and state | Relational or document database | How long must results stay available? |
| Checkpoints | Database or workflow engine | When can old steps be removed? |
| Files and large outputs | Object storage | Who may download them, and until when? |
| Conversation history | Database with per-user access | What may users delete? |
| Short-lived cache and locks | In-memory store | Is losing it harmless? |
A checkpoint records enough to resume: the messages so far, completed tool calls and their results, the next intended step, the versions of the prompt and tools, and limits already consumed. Write it after each meaningful step, particularly after any action with an effect.
Update with a version number: "change this record only if it is still version 7". Two workers then cannot silently overwrite each other (Parallelism, Deadlocks and Conflict Resolution). For approval waits lasting days, frequent timers or complex branching, a durable workflow engine saves you from rebuilding these mechanisms (Durable Execution, Checkpoints and Approvals).
Test the failure paths
| Experiment in a test environment | Expected result |
|---|---|
| Stop a worker mid-task | Another resumes; no action is repeated |
| Deliver the same message twice | One result and one effect |
| Make the store briefly unavailable | Tasks wait or fail clearly; nothing is half-recorded |
| Close the client connection | The task continues and can be reread |
| Send ten times the normal load | Queue grows, limits hold, interactive work still moves |
| Cancel during a slow tool call | State becomes canceled and later steps do not run |
Common mistakes
| Mistake | Better approach |
|---|---|
| Holding one request open for the whole run | Create a job and let clients watch it |
| Retrying creation without a key | Require an idempotency key |
| Assuming a message is delivered once | Make handlers repeatable |
| Letting a lease expire during healthy work | Renew it while progress continues |
| Designing to a limit read long ago | Check current platform quotas and test near them |
| No owner for failed messages | Alert on the dead-letter queue and review it |
Checklist
- The interaction style matches the slowest realistic run.
- Task states, errors and cancellation are documented.
- Every create call is idempotent and every read checks ownership.
- Streams can resume and expose only safe fields.
- Platform time, size and concurrency limits are recorded and tested.
- Leases, retries, delays and dead letters are configured.
- Checkpoints allow another worker to continue.
- Failure experiments have been run, not just planned.
Frequently asked questions
Server-sent events or WebSockets?
Use server-sent events for one-way progress and WebSockets when the client must send data continuously, such as audio or interruptions.
Can serverless functions run agents?
Yes, when each invocation fits the platform limits and state is stored externally; split or move longer work.
Can a database serve as the queue?
Often at modest volume, provided claims are atomic and you monitor load; adopt a queue service when its features or scale are needed.
How should cancellation work?
Record the request, have workers check it between steps, stop further actions and report anything already completed.
References and further reading
- AWS: 90-minute function timeout on Lambda Managed Instances.
- Cloud Run quotas and limits.
- Cloud Run: using WebSockets.
- AgentCore Runtime lifecycle settings.
- HTML Standard: server-sent events.
Next steps
Scaling, Hardware, Quotas and Caching
Keep queues healthy within quotas.
Durable Execution, Checkpoints and Approvals
Resume long workflows safely.
CI/CD, Infrastructure as Code and Safe Releases
Release changes while tasks are running.