TL;DR
- Start: a per-boot
boot_idswitched with CAS rejects reports from a replaced container. - Run: the core API’s claim decides which boot owns a job, and nothing is retried automatically (at-most-once).
- Save: PUT to a new key with
If-None-Match: *, and the core API reads the SHA-256 back before advancing the revision with CAS. A 412 alone is not success. - Stop: the container answers prepare-to-stop with 409 or 204, and SIGTERM comes only after 204. PID 1 escalates to SIGKILL after 5 seconds.
I am moving the environment that runs agents from per-workspace VMs to containers on Cloudflare Containers. A container starts when a job arrives and stops when there is no more work.
With VMs, the disk persisted, each workspace had one machine, and it was stopped only after 15 minutes of idle time. With containers, replacements, saves that overlap a stop, and forced terminations have to be treated as normal events. This post follows one job from start to stop, and for each stage it shows what breaks and which technique prevents it.
1. Why I moved from VMs to containers
Each workspace had its own VM, stopped after 15 minutes of idle time. While it ran, the VM cost money even with no work, and while it was stopped, its disk still cost money. A job that arrived after the stop waited for the VM to boot. Cloudflare Containers bills only while a container runs, and cold starts are often in the 1–3 second range for small images The Durable Object is billed separately. Starting a container per job and stopping it afterwards fit better than keeping a VM per workspace.
The roles are split like this:
- Core API: the source of truth for which container may run which job. It keeps jobs, results, execution state, and saved revisions in its database.
- Durable Object: one per workspace, holding exactly one container. It starts the container, checks that it is ready, and stops it. A container can only be reached through its Durable Object, so notifications and stop-prepare calls from the core API also go through it.
- Container: runs the agent CLI. Its disk disappears when it stops.
- R2: holds what the next start needs, such as conversation files and changes not pushed yet.
The Durable Object only operates the container. It does not keep a job queue or a record of who is running what. If the same information lived in two places, there would be no way to decide which one to trust when they disagree.
On the normal path, one job goes through these steps:
The rest of this post walks through this flow with one job: a workspace gets a job that writes a reply in a chat.
2. Start: fencing off the old container
The container authenticates with a token that the core API signs with Ed25519 and that expires in 10 minutes. Requests from the core API to the Worker and to the container carry tokens signed with the same key.
Only the core API holds the private key. The Worker and the container get only the public key, so they can verify tokens but cannot mint them. With a shared HMAC key, any verifier could also mint tokens.
A completion report from the replaced container arrives late
The container stops responding, so the Durable Object calls destroy() on it and starts a new one. A Durable Object holds one container, so the two never run side by side.
But the old container was only slow, and before it stopped it had already sent a “done” report. That report does not go through the Durable Object, so it reaches the core API after the replacement. The token is still valid. Accepting it would overwrite the new boot’s work with the old result.
A signature and an expiry say nothing about “this container has been replaced”. To revoke it, the server has to check its own state on every request.
Switching a per-boot ID with CAS instead of keeping a denylist
I considered three options:
- Shorten the expiry. Even with one minute, old results get through during that minute.
- A denylist (OWASP JWT Cheat Sheet). Refreshes leave several tokens per container, and every replacement has to register all of them. Missing one lets it through.
- Introspection (RFC 7662). The receiver asks the issuer every time. What “active” means still has to be decided separately.
I kept the per-request server check from introspection and made the unit a boot instead of a token. Each start puts a random boot_id in the token, and the core API keeps one row per container with the current boot. Rewriting that row shuts out every token from the old boot.
The rewrite is a CAS. On the first start boot_id is NULL, so it compares with IS NOT DISTINCT FROM.
UPDATE instances
SET boot_id = $2, state = 'STARTING'
WHERE id = $1 AND boot_id IS NOT DISTINCT FROM $3; -- $3 = expected boot_id (NULL on first start)
If no row was updated, another start already switched the boot. The container start is requested only after this commits, and the Durable Object stores the same boot_id before calling ctx.container.start().
Every request from the container, token refreshes included, is checked against this row. The result is not cached, because a cache delays revocation. The Durable Object also compares the token’s boot_id with the one it stored.
The 10-minute expiry stays. It caps the damage if an endpoint misses the check or a token leaks.
3. Run: not losing work when a container vanishes
The core API stores the job and notifies the container through the Durable Object. The container claims the job, starts the CLI, and only then answers 202 Accepted.
202 means “started”, not “done”. If the container vanishes from OOM or similar after that, the notifier cannot tell how far the work got.
The core API’s claim decides who owns the work
Progress is tracked through a claim in the core API.
- A claim is exclusive: only one boot can hold a given job.
- Reports, saves, and token refreshes are accepted only from the boot that holds the claim. A late report from a replaced container is rejected here.
- While the agent waits a long time for an LLM response, the core API side sends keepalives to the Durable Object.
Job queues commonly redeliver unacknowledged work automatically, as with the SQS visibility timeout (at-least-once). That requires idempotent processing.
This job replies in a chat and creates tasks, so an automatic retry can send the reply twice. Making external side effects idempotent is hard, so this system is at-most-once. OOM and forced terminations are failures and go to an explicit recovery path.
Recovery starts from the last save committed in section 4. Saves also happen at checkpoints during a run, and work after the last save is not recovered.
4. Save: handing state to the next container
Container disk is ephemeral, and the next start gets a fresh one. To continue the conversation, state has to be saved to R2 before the stop and restored on the next start.
Cloudflare also offers filesystem snapshots and mounting R2 with FUSE. A snapshot keeps credentials and caches too. For FUSE, the docs say not to expect SSD-like performance, which does not suit a conversation file the CLI writes constantly.
What I keep is the conversation file, selected files, and the Git changes from the base commit. They go into a tar.gz of up to 64 MiB that is PUT to R2. Credentials stay out of it, in a separate encrypted store.
A save that overlaps a stop leaves no clear current version
The simple approach is to PUT with a presigned URL and, on 200, delete the local files and stop. This goes wrong in two ways:
- PUTs from the old container and the new boot write to the same key from the same revision. Both get 200, and the last one wins.
- After an old object is deleted, a container with an unexpired URL PUTs again, and the deleted version comes back.
A 200 on PUT means R2 received the body, not that the version to restore next is decided.
A URL that writes once, committed after the server reads it back
The container sends the core API the size, the SHA-256, and the base revision. The core API records them and returns a presigned URL for a new key every time.
url = s3.generate_presigned_url(
"put_object",
Params={
"Bucket": BUCKET,
"Key": f"state/{uuid.uuid4().hex}.tar.gz",
"ContentLength": size,
"IfNoneMatch": "*",
},
ExpiresIn=300,
)
The values in Params are part of the SigV4 signature, so the PUT must send the same headers. If-None-Match: * means “write only if the key is empty”, and R2 evaluates it atomically as part of the write. Every save uses a new key, so a failed save leaves the previous version intact.
After the PUT, the core API reads the object back and checks the size and SHA-256 against the record. If they match, it advances the revision with a CAS, only if the base revision is still the latest. Of two saves from the same revision, only the first to commit wins. A commit from an old container is rejected earlier, by the boot and claim checks.
The save is complete only when the revision advances. A failed commit is retried every second. Deleting local files, reporting the result, and answering the stop all come after this.
A retried PUT can return 412 Precondition Failed. A 412 only says something already exists at the key, not that it is what the container meant to send. So on 412 the container still asks for the commit: if the read-back matches, the state is saved; if not, it starts over with a new key.
With S3, the common practice is a checksum such as Content-MD5 verified on write, and R2 supports it. Signed into the URL, it rejects a PUT with a different body. Even so, the core API’s CAS decides which version wins. With a 64 MiB limit, the read-back costs little.
Old objects are deleted well after the URL expires, because deleting earlier frees the key for the same URL to write again.
5. Stop: when the container may exit
The reply and report are done, and there is no more work. After 15 minutes with no work, the runtime stops the container.
Sending SIGTERM right away cuts off the save or the report
Stopping a Cloudflare container sends SIGTERM, waits up to 15 minutes, then sends SIGKILL. A rollout under the default policy does the same. That cuts off the save and report that follow the 202, and tool processes started by the CLI may stay behind.
Making the container answer 409 or 204 before the stop
Pod termination in Kubernetes runs the preStop hook, then sends SIGTERM, and sends SIGKILL after terminationGracePeriodSeconds (30 seconds by default). I kept the idea of closing intake and waiting for work to finish. Cloudflare Containers has no hook before SIGTERM, so this is done over HTTP:
- The core API calls the container’s “prepare to stop” endpoint through the Durable Object.
- The runtime starts draining. It returns 409 while work remains, and once everything is done it seals intake and returns 204. New requests in the meantime get 425.
- On 409, the core API waits and calls again. On 204, it uses a row lock and CAS to check that the boot and interruption generation have not changed and no work is pending. It marks the instance STOPPED and asks for the stop.
- If the boot does not match, the Durable Object refuses with 409. Otherwise it stores STOPPING and a deadline 15 seconds out, sets an alarm, and sends SIGTERM.
Unlike preStop, this lets the stopper postpone the stop on a 409.
PID 1 sends SIGTERM to its children at once and SIGKILL after 5 seconds
The usual PID 1 is tini or dumb-init. My container, though, starts the management runtime and the execution engine under separate UIDs, each in its own session. tini and dumb-init start a single child, and neither escalates to SIGKILL after a deadline. So I wrote a small single-loop init in Python.
def on_sigterm(signum, frame):
global stopping
stopping = True # only a flag; the loop below does the work
while True:
try:
while os.waitpid(-1, os.WNOHANG)[0] > 0:
pass # reap every child that exited, adopted orphans included
except ChildProcessError:
sys.exit(1 if forced else 0) # no children left
if stopping:
deadline = deadline or time.monotonic() + 5
forced = time.monotonic() >= deadline
for pid in children(): # read from /proc/1/task/1/children
if forced or pid not in signalled:
os.kill(pid, signal.SIGKILL if forced else signal.SIGTERM)
signalled.add(pid)
time.sleep(0.05)
The handler only sets a flag; only the loop sends signals and reaps. Killing inside the handler would conflict with whatever the loop was halfway through.
Once stopping, the loop sends SIGTERM at once to the two direct children and any orphans PID 1 adopted. Whatever remains after 5 seconds gets SIGKILL, and once all are reaped the init exits with status 1. If one child exits first, the same steps stop the rest.
There are two ways a stop happens:
- Through prepare-to-stop. The work is done at the 204, so the 5 seconds are only for reaping leftovers. That is shorter than the Durable Object’s 15 seconds, so PID 1 exits on its own. The alarm is stored durably, and if the container is still running after 15 seconds, it calls
destroy(). - SIGTERM without prepare-to-stop. This is a rollout or an inactivity timeout. There is no drain: the runtime closes its HTTP server immediately, and in-flight work is cancelled without saving or reporting. PID 1 escalates to SIGKILL after 5 seconds. The Durable Object records FAILED, and nothing is retried automatically.
On the second path, uncommitted state is lost. But a result is reported only after its save is confirmed, so a half-finished save is never treated as done.
So every normal stop goes through the 204. To avoid the inactivity timeout, the Durable Object sets setInactivityTimeout to 3 minutes and keeps extending it with a 60-second alarm and keepalives.
SIGTERM is an order to stop, not an answer to whether stopping is safe. The container gives that answer with a 204 after closing intake, and the core API decides after checking the boot and claims.