Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

My Cloudflare Container never went to sleep, and two small bugs were why

I run a small site checker on Cloudflare Containers. A Worker takes a URL, starts a container with Node and Chromium, and the container loads the site at several screen widths and writes a report. A check takes a few min

I run a small site checker on Cloudflare Containers. A Worker takes a URL, starts a container with Node and Chromium, and the container loads the site at several screen widths and writes a report. A check takes a few minutes, and most days there are only a handful.

So I set sleepAfter = "5m" and expected to pay for a few minutes of container time a day.

On Nov 24 I got a budget alert. The bill for the month so far was $11.39, and $10.82 of that was container memory. The container had been awake for about 205 hours and had done about 3.6 hours of CPU work. The memory chart was a flat line at about 0.5 GiB, between checks too.

There were two bugs, and either one alone was enough to keep it awake.

The setup

With the @cloudflare/containers package, the container class is short:

import { Container } from "@cloudflare/containers"

export class Checker extends Container {
    defaultPort = 8080
    sleepAfter = "5m"
}

The Worker talks to it with fetch: start a job, poll its status, download the report, then send a cleanup request. When nothing has talked to the container for sleepAfter, the library stops it.

Bug 1: a response body nobody read

The cleanup request was fire and forget. I only cared that it was sent, so the code awaited container.fetch(...) and never touched the response.

In version 0.3.7 of @cloudflare/containers, every proxied request bumps an in-flight counter. For a response with a body, the counter only goes back down once the body has been piped through to the caller:

// inside the library, simplified
this.inflightRequests++
const res = await tcpPort.fetch(containerUrl, request)
if (res.body !== null) {
    const { readable, writable } = new IdentityTransformStream()
    res.body.pipeTo(writable).finally(() => this.decrementInflight())
    return new Response(readable, res)
}

And the sleep check won't expire while that counter is above zero:

isActivityExpired() {
    if (this.inflightRequests > 0) {
        this.renewActivityTimeout()
        return false
    }
    return this.sleepAfterMs <= Date.now()
}

An IdentityTransformStream only moves data when someone reads the other end. My code never read it, so the pipe never finished, the counter never got back to zero, and the timer kept renewing itself. A tiny {"ok":true} reply was enough to keep the container up.

The fix is to read or cancel every response you don't need. I put it in one helper and used it everywhere the Worker ignores a reply:

// The library counts a request as open until its response body is read.
const drop = (res) => res?.body?.cancel().catch(() => {})

const res = await container.fetch(clearUrl, { method: "POST" })
await drop(res)

await res.text() works too. cancel() just skips reading bytes you're going to throw away.

Bug 2: Node as PID 1 ignored the stop signal

With the first bug fixed, the library started trying to stop the container. When the timer runs out, it calls this.stop(), which sends SIGTERM to the container's main process.

My Dockerfile ends with:

CMD ["node", "/app/server.mjs"]

That makes Node PID 1 inside the container, and Linux treats PID 1 differently: a signal it has no handler for is ignored instead of getting the default action, which for SIGTERM is to exit. Node doesn't install a SIGTERM handler by default, so the signal did nothing.

I reproduced it in plain Docker. docker stop waited out its grace period, then killed the container, and it exited with code 137 (SIGKILL). On Cloudflare, it just kept running.

The fix is two lines at the end of the server:

// Node is PID 1 here, and PID 1 ignores SIGTERM unless it handles it.
for (const sig of ["SIGTERM", "SIGINT"]) process.on(sig, () => process.exit(0))

After that, docker stop returned right away with exit code 0.

The usual alternative is an init process: tini as the entrypoint, or docker run --init locally. It forwards signals to your app and also reaps zombie processes. A handler was enough for me because when PID 1 exits, the kernel kills every other process in the container, Chromium included, and the server has nothing it needs to finish first. If your app starts a lot of short-lived child processes, use tini for the zombie reaping.

Did it work?

Both fixes went out on Nov 24. The last check that evening finished at 8:19 PM, and by 8:24 the instance showed as inactive, five minutes later, as configured. After that the memory chart sat at zero between checks.

What I'd check on any Cloudflare Container

  • Read or cancel every response body from container.fetch, including the ones you think of as fire and forget.
  • If your CMD starts your app directly, it is PID 1. Handle SIGTERM or use an init process.
  • Test the stop locally with docker stop and look at the exit code. 137 means the signal was ignored and Docker had to kill it.
  • Set a budget alert on day one. Mine is how I found this, about $11 in.

The checker this runs is Template QA. It tests live Framer sites at widths from small phones to big monitors.

Have you had a container or serverless function cost more than it should? What was keeping it alive?

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.