skip to content

In Cloudflare Containers, what happens when a request reaches a stopped instance, and what keeps an instance running between requests?

level: middleimportance: should knowfreq 30%

answer

  1. running is not ready
  2. seconds, not milliseconds
  3. the Durable Object's activity decides
  4. setInactivityTimeout or sleepAfter
  5. disk starts fresh

basics

~20 s

A stopped instance cold-starts in seconds, and start() returns before its port is ready, so code polls first. It runs while its Durable Object is active, then for the inactivity timeout or sleepAfter, and restarts with a fresh disk.

solid answer

~40 s

`ctx.container.start()` returns once its options validate; `running` turns `true` at once, but a request sent before the process listens fails (locally with `Container is not listening to port 8080`), so the Durable Object polls a health path before forwarding. Cold starts are typically 1 to 3 seconds, depending on the image and entrypoint. An instance runs while its Durable Object is active (a request, an alarm, a stream or an accepted WebSocket), then for the time set with `setInactivityTimeout()`, at most 6 hours; a restarted object loses that timeout, so set it again in the constructor. Work inside the container does not count as activity. The `Container` class uses `sleepAfter`, default `"10m"`, reset by incoming requests or `renewActivityTimeout()`. After a stop, the next start gets a fresh disk from the image.

code

javascript · 45 lines
javascript
import { DurableObject } from "cloudflare:workers";

const PORT = 8080;
const IDLE_MS = 10 * 60 * 1000;

export class Converter extends DurableObject {
  constructor(ctx, env) {
    super(ctx, env);
    if (ctx.container.running) {
      ctx.blockConcurrencyWhile(() => ctx.container.setInactivityTimeout(IDLE_MS));
    }
  }

  async ensureReady() {
    const container = this.ctx.container;
    if (!container.running) {
      container.start({ enableInternet: false });
      await container.setInactivityTimeout(IDLE_MS);
    }
    const port = container.getTcpPort(PORT);
    for (let attempt = 0; attempt < 50; attempt++) {
      try {
        return await port.fetch("http://container/health");
      } catch {
        await scheduler.wait(200);
      }
    }
    throw new Error("converter did not open port 8080");
  }

  async fetch(request) {
    await this.ensureReady();
    const url = new URL(request.url);
    return this.ctx.container
      .getTcpPort(PORT)
      .fetch(new Request(`http://container${url.pathname}`, request));
  }
}

export default {
  async fetch(request, env) {
    const doc = new URL(request.url).searchParams.get("doc") ?? "default";
    return env.CONVERTER.getByName(doc).fetch(request);
  },
};

go deeper

for a junior

Recall that a stopped container takes seconds to start, that start() does not wait for readiness, and that its disk is wiped when it sleeps.

for a middle

Explain the activity rule: a container lives while its Durable Object is active, then for setInactivityTimeout() or sleepAfter, and what resets each timer.

for a senior

Show the production traps: a job killed mid-run because in-container work is not activity, a lost timeout after a deploy, and racing starts on a cold instance.

for a principal

Treat the inactivity timeout as a cost and latency dial set from traffic shape, and decide when pre-warming earns its idle cost.

## From stopped to serving A container instance is either running or stopped, and a stopped one must boot before it can answer. When a Durable Object calls `this.ctx.container.start()`, Cloudflare picks capacity that already holds the image, boots a fresh instance and runs the image's entrypoint. Cloudflare's documentation puts typical **cold starts in the 1 to 3 second range**, depending on image size and on what the entrypoint does before it listens. Three details make that gap visible in code: - `start()` returns once it has validated its options; it does not wait for the process. - `ctx.container.running` becomes `true` immediately, before any port is open. - A request sent too early fails; locally the error reads `Container is not listening to port 8080`. So the Durable Object needs a **readiness check**: poll a health path through `getTcpPort(port).fetch()` with a short delay until it answers, and only then forward real traffic. Calling `start()` on a running container throws `start() cannot be called on a container that is already running.`, so guard it with `if (!container.running)`. The `Container` class from `@cloudflare/containers` packages this work: its inherited `fetch()` starts the container automatically, and `startAndWaitForPorts()` resolves only when the configured ports accept connections, with a default `portReadyTimeoutMS` of 20,000. ## What keeps an instance running With the Durable Object Container API, the container's life follows its Durable Object: 1. While the object is **active**, handling a request, running an alarm, streaming a response or holding an accepted WebSocket, its container keeps running. 2. When the object goes inactive, the container keeps running for the duration passed to `setInactivityTimeout(ms)`. The value must be above 0 (0 throws a `TypeError`) and at most 6 hours. 3. With no timeout set, Cloudflare stops the container shortly after the object goes inactive. Two traps follow. First, the timeout belongs to the Durable Object instance, and a restarted object, for example after a deploy, starts without one; set it after `start()` and again in the constructor when `ctx.container.running` is already `true`. Second, **work inside the container is not activity**. A 40-minute conversion started by one request, with no requests after it, is stopped when the timeout ends, mid-job. Keep the object active while the job runs: hold the request open, or set a Durable Object alarm that fires more often than the timeout and checks on the job. The `Container` class expresses the same idea as `sleepAfter`, default `"10m"`, accepting seconds or a string such as `"30s"` or `"1h"`. Incoming requests reset the timer, background work calls `renewActivityTimeout()`, and on expiry `onActivityExpired()` runs, whose default calls `stop()`. An override that calls neither `stop()` nor `destroy()` keeps the container awake, and the hook fires again at the next expiry. ## What survives a stop | Survives | Ends with the instance | | --- | --- | | The name, the Durable Object and its `ctx.storage` | The container's processes and memory | | Objects written to an R2 bucket | Files written to the container's disk | | A snapshot you saved (`durable_object` policy only) | In-flight requests to that instance | Disk is ephemeral: the next start gets a fresh filesystem from the image. Keep job state, such as the input key and the output location, in Durable Object storage, and write results somewhere durable before replying. ## How an instance is told to stop For a rollout or a host shutdown, Cloudflare sends `SIGTERM` to the main process, waits up to 15 minutes, then sends `SIGKILL`. For an inactivity timeout the sandbox documentation is stricter: processes get `SIGTERM` and the instance stops shortly after, whether or not they exit, so do not count on a long drain there. `destroy()` kills the container at once. A converter that traps `SIGTERM` can still checkpoint the current document. ## The cost and latency dial Charges start when a request reaches the container or it is started manually, and stop when the instance goes to sleep. The timeout is therefore a dial: a short one scales to zero quickly but makes the next user wait for a cold start, while a long one keeps a warm converter billed for its provisioned memory and disk while it sits idle. Pick it from the traffic pattern, and pre-warm with a `start()` from an alarm or a scheduled request when a burst is predictable.

  • How would you keep a long conversion alive when no further requests arrive?
    Keep the Durable Object active: hold the triggering request open until the job ends, or set a `ctx.storage.setAlarm()` that fires more often than the inactivity timeout and checks the job's progress. With the `Container` class, call `renewActivityTimeout()` from that background work. Process activity inside the container does not extend its life.
  • Two requests for a stopped instance arrive together. What can go wrong and how do you guard it?
    Unless code checks first, both may call `start()`, and the second throws because the container is already running. Check `ctx.container.running` before calling `start()`, and let concurrent callers share one readiness wait, for example a stored promise, before forwarding. The `Container` class coordinates concurrent starts in `start()` and `startAndWaitForPorts()`.
  • Why set the inactivity timeout again in the Durable Object's constructor?
    The timeout belongs to the Durable Object instance. After a deploy or an eviction, a new object instance can find the container still running but has no timeout of its own, so the container would stop shortly after the object goes idle. Re-arming it in the constructor when `ctx.container.running` is true keeps the intended lifetime.

  • Assumes ctx.container.start() waits until the container's port is ready.
  • Treats running === true as proof that the process accepts requests.
  • Believes a busy process inside the container keeps the instance alive.
  • Expects files on the container disk to be there after it slept.
  • Thinks container cold starts take milliseconds like isolate starts.
  • Overrides onActivityExpired() without calling stop() and expects the container to sleep.

Assumes Cloudflare's platform as of 2026-10-10: setInactivityTimeout() on ctx.container is the recommended control for new code, and the Container class's sleepAfter default is "10m".