AI Agent Graceful Shutdown 2026
A user waited three minutes while an agent analyzed page eight, then a restart killed the request. Graceful shutdown means four things: stop accepting, drain, force-kill on timeout, and resume afterwards.
📜 Table of Contents
📖 Keep reading
Graceful Shutdown: Do Not Kill a Running Task Midway
Agent tasks run far longer than HTTP requests. A document analysis can take two or three minutes with tool calls in between. Restart the service and every in-flight request dies; the user waited three minutes for "service restarting". Worse, some tasks already had side effects - a database write, an email - so a retry duplicates them.
Graceful shutdown is about thirty seconds of discipline: stop accepting, finish what is running, leave a resumable state for the rest.
Four actions
- Drain: reject new work with 503 plus Retry-After
- Wait for in-flight tasks, with a hard ceiling
- Force-cancel on timeout, mark failed, record where it stopped
- Resume after restart from the last completed step
Step four is the one people skip. Without it, long tasks still die - just thirty seconds later.
Correct implementation
class AgentServer:
def __init__(self):
self.draining = False
self.active = set()
async def handle(self, req):
if self.draining:
raise ServiceUnavailable("restarting, retry in 10s")
task = asyncio.current_task()
self.active.add(task)
try:
return await run_agent(req)
finally:
self.active.discard(task)
async def drain(self, grace=25):
self.draining = True
tasks = list(self.active)
if not tasks:
return
done, pending = await asyncio.wait(tasks, timeout=grace)
for t in pending:
t.cancel()
await asyncio.gather(*pending, return_exceptions=True)
Common mistakes: ignoring the pending set (which means no timeout handling at all), awaiting inside a signal handler instead of create_task, and setting draining after snapshotting tasks.
Choosing the timeout
Grace period should be shorter than your longest task and longer than your typical one - roughly P95 duration plus ten seconds, and below the platform's hard limit.
In Kubernetes, terminationGracePeriodSeconds defaults to 30 and preStop runs before SIGTERM:
lifecycle:
preStop:
exec: {command: ["sh","-c","sleep 5"]}
terminationGracePeriodSeconds: 40
The sleep is not padding; it lets the load balancer stop routing before the signal arrives.
Persist state to actually resume
- Write
task_id, current step, completed step outputs on every step boundary - After restart, a recovery job picks up tasks marked running with a stale heartbeat
- Steps must be re-entrant: skip what is already done
def run_step(task, step_name, fn):
if step_name in task["done_steps"]:
return task["step_outputs"][step_name]
out = fn(task)
task["done_steps"].append(step_name)
task["step_outputs"][step_name] = out
save(task)
return out
This is worth more than the shutdown logic: it turns restarts from incidents into routine operations.
Three strategies
| Strategy | Behaviour | User experience | Fits |
|---|---|---|---|
| Immediate | Everything cut | Sudden failure | Stateless, dev |
| Graceful | Drain and wait | Invisible if tasks are short | Frequent deploys |
| Graceful + resume | Persist, continue after restart | Slower but succeeds | Long tasks with side effects |
Rule: if the average task exceeds half the grace period, you need resume.
FAQ
Do frameworks handle this? uvicorn and gunicorn stop accepting connections and wait for in-flight requests, but task registration and cancellation are yours. uvicorn exposes --timeout-graceful-shutdown; check the default in current docs.
How do I notify users of cancelled tasks? Catch CancelledError, mark the task interrupted, save the checkpoint, then notify by email or in-app message. Never fail silently.
Rolling updates without downtime? Small maxUnavailable, working readiness probes, multiple replicas plus drain mode.
Note: framework defaults change by version - check official docs.
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.