Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Agent keepAlive, Fiber Execution, and Durable Object Eviction

How Cloudflare Agents avoid mid-task eviction with keepAlive, fibers, and Durable Object lifecycle rules—and when to use each.

This page summarises Cloudflare documentation on Cloudflare Agents built on Durable Objects: why an agent can stop during streaming or slow APIs, what the platform already does to prevent idle shutdown, and how keepAlive(), runFiber(), and startFiber() fit together.

Durable Object eviction: why long agent work stops mid-flight

Section titled “Durable Object eviction: why long agent work stops mid-flight”

A Durable Object that backs an agent is removed from memory after a stretch of inactivity—typically 70–140 seconds with no incoming requests, WebSocket messages, or alarms—unless something else keeps it non-hibernateable or actively busy.

Durable Objects are evicted after a period of inactivity (typically 70–140 seconds with no incoming requests, WebSocket messages, or alarms). During long-running operations — streaming LLM responses, waiting on external APIs, running multi-step computations — the agent can be evicted mid-flight.

— Cloudflare, Agent class internals

Eviction is not the only interruption. Cloudflare documents three common reasons work is lost mid-task:

Durable Objects get evicted for three reasons:

Inactivity timeout — ~70–140 seconds with no incoming requests or open WebSockets
Code updates / runtime restarts — non-deterministic, 1–2x per day
Alarm handler timeout — 15 minutes

— Cloudflare, Durable execution with fibers

When eviction happens during work, in-memory state (buffers, partial streams, loop position) is gone; upstream HTTP connections are severed. Agents are durable identities with SQLite-backed state, not always-on processes—so anything that matters must be persisted or recoverable (Long-running agents).

On the lifecycle path, a Durable Object may hibernate after about 10 seconds of idle time only if strict conditions hold (no pending timers, no open outbound I/O, no waitUntil promises, and so on). If any condition fails, the object stays idle, in-memory, non-hibernateable and still incurs duration charges until the 70–140 second eviction window ends.

Platform keep-alive: outbound I/O, waitUntil, and compatibility flags

Section titled “Platform keep-alive: outbound I/O, waitUntil, and compatibility flags”

Before reaching for SDK helpers, check whether the runtime already keeps the Durable Object in memory.

Durable Objects now remain alive for the duration of active outbound connections created via connect() or an outbound WebSocket. Previously, a Durable Object would be evicted after 70-140 seconds of no incoming traffic, even if the object had an open outbound connection, which is a common pattern when streaming responses from a large language model (LLM) over TCP or an outbound WebSocket.

— Cloudflare, Outbound connections keep Durable Objects alive

After all outbound connections close, the normal inactivity window applies. Each outbound connection prevents eviction for at most 15 minutes; after that the connection may continue but no longer blocks eviction (same changelog).

For work that continues after the HTTP client disconnects, compatibility date 2026-10-01 (or flag durable_object_io_tasks_prevent_eviction) enables:

Pending service binding requests now keep Durable Objects running while they wait for a response. Pending calls to another Durable Object through remote procedure call (RPC) or fetch(), as well as this.ctx.container.monitor(), now also keep the Durable Object running.

Promises passed to this.ctx.waitUntil() and pending setTimeout() and setInterval() timers also receive this protection.

— Cloudflare, Pending I/O operations allow Durable Objects to continue long-running work without a connected client

Each such operation prevents idle shutdown until it completes or for up to 15 minutes from when it starts; starting another operation later can extend time in memory. Duration charges continue while eviction is prevented (compatibility flags, Durable Object State waitUntil).

Workers runtime updates during long streams

Section titled “Workers runtime updates during long streams”

Deploys can still interrupt in-flight work on an old isolate. Runtime updates now allow up to 20 minutes for pending requests and connections on the previous runtime version to drain (Workers platform limits — Runtime updates, changelog). Design for reconnect, retry, and state recovery; WebSockets may drop before the grace period ends.

keepAlive() and keepAliveWhile(): heartbeat during active agent work

Section titled “keepAlive() and keepAliveWhile(): heartbeat during active agent work”

When the agent is doing CPU/async work without an open outbound connection that counts against eviction—multi-step tool logic, slow APIs between calls, custom streaming paths—use the Agent SDK heartbeat.

keepAlive() prevents this by creating a 30-second heartbeat schedule. The alarm firing resets the inactivity timer. Returns a disposer function that cancels the heartbeat when called.

— Cloudflare, Agents SDK v0.7.0 changelog

In Agents SDK v0.8.0, the implementation changed: heartbeats use an in-memory reference count and share one alarm cycle; the @experimental tag was removed (v0.8.0 changelog). The heartbeat is not exposed as schedule rows and does not appear in listSchedules() (Durable execution with fibers).

keepAliveWhile() is the recommended pattern—it always stops the heartbeat when the function finishes or throws:

const result = await this.keepAliveWhile(async () => {
return await slowAPICall();
});

For manual scope control, dispose explicitly (Schedule tasks):

const dispose = await this.keepAlive();
try {
const result = await longRunningComputation();
await sendResults(result);
} finally {
dispose();
}

Multiple concurrent keepAlive() calls each get an independent disposer; disposing one does not cancel others (Schedule tasks). Sub-agents delegate the physical alarm to the parent agent because facets lack their own alarm slot (Durable execution with fibers).

AIChatAgent calls keepAlive() automatically during streaming LLM responses—you do not add it for default chat streaming (Schedule tasks, v0.7.0 changelog).

Default heartbeat interval is 30 seconds (override with static options = { keepAliveIntervalMs: 2_000 } on your Agent class) (Durable execution with fibers).

runFiber() and startFiber(): survive eviction with checkpoints

Section titled “runFiber() and startFiber(): survive eviction with checkpoints”

keepAlive() only reduces the chance of idle eviction; it does not recover after deploy, alarm timeout, or eviction.

keepAlive prevents eviction but does nothing about recovery. If the agent is evicted despite the heartbeat (code update, alarm timeout, resource limit), any in-progress work is lost.

runFiber calls keepAlive internally and persists the work in SQLite so it can be recovered.

— Cloudflare, Durable execution with fibers

Scenario Use
Waiting on a slow API call keepAlive() / keepAliveWhile()
Streaming via AIChatAgent Built-in
Multi-step work with intermediate results runFiber() + ctx.stash()
Webhook that must be accepted once, with status/cancel startFiber() + idempotencyKey
Multi-hour orchestration outside the agent Workflows (see Long-running agents)

runFiber() registers a row in SQLite, holds keepAlive() for the run, and deletes the row on success. ctx.stash(data) writes a full replacement snapshot synchronously—if eviction happens after stash() returns, the snapshot is on disk (Durable execution with fibers).

On the next activation, onFiberRecovered() runs for interrupted fibers. The original callback closure is not replayed; recovery logic must use ctx.name, ctx.snapshot, and metadata (Durable execution with fibers).

startFiber() is for durable acceptance: idempotent webhook handling, inspection via inspectFiberByKey(), cooperative cancel via cancelFiber(), and optional waitForCompletion: true (Durable execution with fibers).

destroy() and designing without shutdown hooks

Section titled “destroy() and designing without shutdown hooks”

To wipe an agent permanently:

this.destroy() drops all tables, deletes alarms, clears storage, and aborts the context.

— Cloudflare, Agent class internals

destroy() is safe from scheduled callbacks; the SDK defers ctx.abort() so the alarm handler can finish (Agent class internals, Schedule tasks).

Cloudflare does not provide reliable pre-shutdown hooks on Durable Objects. Persist progress incrementally in storage instead (Rules of Durable Objects, Lifecycle of a Durable Object).

Sandbox and container keepAlive (separate from Agent keepAlive)

Section titled “Sandbox and container keepAlive (separate from Agent keepAlive)”

Cloudflare Sandbox containers use a different keepAlive option on getSandbox(): heartbeat pings every 30 seconds and no automatic sleep until you destroy() or setKeepAlive(false) (Sandbox options, Sandbox lifecycle). That addresses container sleep, not Durable Object alarm heartbeats on a custom Agent class. Container workloads can call renewActivityTimeout() for background jobs (Container class API).

  • Relying on keepAlive() alone for work that must survive deploys or 15-minute alarm limits—use runFiber() / startFiber() and stash().
  • Forgetting to dispose manual keepAlive() calls, leaving the Durable Object billed while idle (Durable Objects FAQ — duration charges).
  • Assuming open outbound LLM streams run forever: the 15-minute anti-eviction cap per outbound connection still applies (Outbound connections changelog).
  • Expecting automatic replay of fiber callbacks—only onFiberRecovered() (or resolveFiber() for managed fibers) implements your policy.
  • Running long in-container builds without Durable Object activity: code inside the container does not reset sandbox idle timers; use alarms or monitor() so the parent Durable Object stays active (Sandbox lifetime).
  1. Reproduce fiber recovery locally: start an agent with runFiber(), trigger work, stop wrangler dev, restart, and confirm onFiberRecovered() runs as described in Durable execution with fibers.

  2. Confirm your Worker compatibility date and whether durable_object_io_tasks_prevent_eviction matches the behavior you expect for waitUntil, RPC, and setTimeout in Compatibility flags and Pending I/O changelog.

  3. Review eviction and billing states (hibernation vs non-hibernateable idle) against your agent’s open connections and timers in Lifecycle of a Durable Object and Durable Objects FAQ.

  4. For sandbox-based workloads, verify keepAlive is disabled or destroy() is called after long jobs per Run background processes.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.