DEV Community

Anton Shvein
Anton Shvein

Posted on Edited on Originally published at t0ha.dev AI-assisted

Docker Swarm Assumes Containers Are Interchangeable. Mine Weren't.

Every orchestrator I have used is built on one comfortable assumption: your containers are interchangeable. If one dies, start another. If a node goes away, reschedule. The new container is as good as the old one, because all the state that matters lives somewhere else.

That assumption is correct for web applications. It is why Swarm and Kubernetes work at all.

It is wrong for what I am running.

A Camelot AI agent session is one CLI process, inside one container, working on a checked-out repository, for up to forty minutes. It is stateful, it is long, and it is pinned to a specific container. If that container goes away in the middle, the run is not "rescheduled". It is lost, together with whatever it was in the middle of doing.

Almost every infrastructure bug I have shipped in the last six months comes out of that one mismatch. Here are the ones worth your time.

1. Swarm remembers dead tasks, and I picked one

To run an agent I need a container to exec into. So I ask the Swarm manager for the tasks of a service and find the running one.

My first version did the obvious thing: find the task whose Status.State is "running".

That is wrong, and it is wrong in a way that is invisible on a healthy cluster.

Swarm keeps historical task records. When a replica is shut down, or when the node it lives on becomes unreachable, or is so short of memory that it never gets around to reporting the shutdown, the old task can sit in Status.State: "running" long after a replacement has been scheduled somewhere else.

Status.State is what the node last told the manager. DesiredState is what the manager intends. When a node is starving or partitioned, those two disagree, and the one you want is DesiredState.

def pick_running_task(tasks) do
  Enum.find_value(tasks, :pending, fn task ->
    desired = task["DesiredState"]
    state = get_in(task, ["Status", "State"])
    # ... require BOTH to be "running"
  end)
end
Enter fullscreen mode Exit fullscreen mode

Until I fixed that, Camelot AI would occasionally route an exec at a container that Swarm had already given up on. The agent never started, the transport eventually timed out, and the task failed with something unhelpful.

The funny part is that the reconciler in the same codebase had been doing it correctly all along. It queried with a "desired-state": ["running"] filter. Two places, same question, different answers. That is usually a sign the question deserves one function.

2. The forty-minute run that lost all of its output

This one took me the longest to believe.

A planning session, about three minutes, worked perfectly. An executing session on the identical code path, same container, same everything, lost 100% of its output. The task ended in error with the message empty output, and there was nothing in the logs.

The mechanism, once I found it, is almost elegant. A bit too elegant for the amount of pain it caused me.

The agent was invoked with --output-format json. That means it prints nothing at all while it works, and emits a single JSON blob at the very end. Meanwhile, Camelot AI reads stdout through a streaming HTTP request to the Docker exec endpoint, via a socket proxy, over an overlay network.

That stream sits idle for forty minutes.

Something in the middle severed it. HAProxy, the overlay, a kernel timeout, I never pinned down which. Not with an error. The stream just ended, cleanly, with zero bytes delivered.

And the exit code arrives over a completely separate channel: an independent poll loop watching the exec's status. That loop saw ExitCode: 0 and reported success.

So the application received: the process finished, exit code 0, and here is an empty buffer. Which parses to exactly what you would expect:

def parse(:claude_code_json, "") do
  {:error, "empty output"}
end
Enter fullscreen mode Exit fullscreen mode

The parser was right. Everything downstream of the parser was right. The bug was that I had built a system where "successful run" and "total data loss" produce identical observations.

The three-minute session survived because three minutes is not long enough for anything to get bored.

The fix was to stop trusting the stream as the system of record. Every agent invocation now goes through a wrapper that tees output to a file inside the container:

out="/tmp/camelot-output-${CAMELOT_SESSION_ID:-session}.log"
set +e
"$@" 2>&1 | tee "$out"
code=${PIPESTATUS[0]}
set -e
Enter fullscreen mode Exit fullscreen mode

After the process exits, the application fetches that file with a short docker exec cat and uses it in preference to whatever the live stream managed to deliver. The stream is now a nice-to-have that powers live output in the UI. The file is the truth.

I also switched the agent to streaming output, which keeps the connection warm as a side effect. But that is defence in depth. The real fix is that a long idle stream is not a place to keep your only copy of anything.

3. Orphans, and the deploy that would not finish

For weeks, the production app service kept ending up at 2/1: two containers running where one was wanted, with a stale orphan that docker rm would not reap, because Swarm believed it was supposed to be there.

The chain took me a while to reconstruct:

  • The app image was amd64 only.
  • The cluster had picked up an ARM node, and the service had no placement constraint.
  • On each deploy, Swarm uses start-first: bring up the new container, then stop the old one.
  • Some new containers landed on the ARM node and died immediately, exit 255.
  • MaxFailureRatio was 0 and FailureAction was pause. Any failed task pauses the whole update.
  • A paused start-first update never reaches its final step, the one that stops the old container.

So the old container was stranded, seemingly forever, by a deploy that was technically still in progress. RestartPolicy: any with unlimited attempts kept feeding the loop.

You can see it directly:

$ docker service inspect <svc> --format '{{.UpdateStatus.State}}'
Enter fullscreen mode Exit fullscreen mode

If it answers paused, you probably have the same problem.

The immediate fix was to pin the architecture and force a converge, which clears the paused state and lets start-first finally reap the orphan with no downtime:

$ docker service update \
  --constraint-add "node.platform.arch==x86_64" \
  --force srv-captain--camelotai
Enter fullscreen mode Exit fullscreen mode

(The arch string reported by docker node inspect is x86_64, not amd64. I lost twenty minutes to that.)

The real fix was building multi-arch images in CI.

But the interesting part is what the orphan did while it was alive. It was an old container, holding the old environment, including a POOL_SIZE of 100, from before I had learned that the managed Postgres behind production allows 25 connections in total.

The new container, correctly configured with a small pool, could not boot. Its startup migrations hit FATAL 53300 too_many_connections, because a container that a paused deploy had forgotten to kill was holding every slot.

Production crash-looped for five hours. The root cause was an architecture mismatch two layers away.

4. Rebuilding the swarm quietly invalidates your secrets

At one point I had to recreate the swarm from scratch, the same one the OpenTelemetry collector runs on. CapRover came back up, logged "Fresh installation!", and preserved its config file completely: applications, domains, SSL, password hash, all intact.

And almost nothing worked.

A fresh initialisation regenerates the captain-salt Docker secret. Everything derived from that salt breaks at once, and each one breaks in a way that does not mention salt:

  • The dashboard password. The stored hash was computed with the old salt, so it no longer verifies. You are locked out of your own orchestrator.
  • The registry credentials. They are stored AES-encrypted under a salt-derived key. They now decrypt to garbage, so every image pull returns 403 denied. This looks exactly like an expired token, and I went and regenerated a perfectly good one before I understood.
  • Node labels, which live in raft state and are simply gone. Agent runners are pinned with a placement constraint on a node label, so every task container sat 0/1 Pending with "no suitable node (scheduling constraints not satisfied)".

Three unrelated-looking failures, one cause. Write this one down before you need it.

5. The Docker API will not resolve a tag for you

A small one, but it cost me an afternoon of confusion.

I wanted the application to keep long-lived runner services up to date: if a service's image uses a floating tag, re-pin it to the newest published digest at boot.

So I posted a service update with the image ghcr.io/…/runner:latest and expected Swarm to resolve it.

It does not. POST /services/{id}/update with a bare tag stores the tag verbatim, even with an X-Registry-Auth header. The resolution you are used to is done by the Docker CLI, client-side, before it ever talks to the daemon. docker service update --image x:latest and posting the same spec through the API are genuinely different operations.

And a bare :latest with no digest is unsafe in Swarm anyway, because different nodes may have different things cached under that name.

So the application resolves the digest itself, against the registry, with Req: request the manifest, get a 401 with a WWW-Authenticate header, fetch a token from the realm it names, retry, read Docker-Content-Digest. About forty lines.

I could not shortcut it through the daemon's own /distribution endpoint, because the socket proxy in front of the daemon only allows the handful of paths the application legitimately needs, and that is not one of them. Which is the socket proxy doing its job.

The rules I would give myself

  • Bound every wait. Especially the ones polling for something inside a container you do not control the lifetime of.
  • Never keep your only copy in a stream. Long-lived idle connections fail silently and without an error, and you will not find out until the data is gone.
  • Assume you will not finish in the container you started in. Reschedules, OOM kills and image rolls are normal operations, not incidents.
  • When two channels tell you about one event, they will disagree. Exit code and output arriving separately is how "success with zero bytes" becomes representable. Decide in advance which one wins.
  • Check DesiredState, not just Status.State. The manager's intention is the fact; the node's last report is a rumour.

Conclusion

None of this makes Swarm a bad tool. It does exactly what it says: it keeps services running and replaces containers freely. The mismatch is mine. I brought a stateful, long-lived, pinned workload to an orchestrator built on the premise that no such thing exists.

If I were starting again I would probably not pick a different orchestrator. They all seem to make this assumption. I would accept it up front and design so that losing any given container costs me a retry, not a run: durable output outside the container, bounded waits everywhere, and a reconciler that expects to be lied to.

Next up, a shorter one about the abstraction that sits on top of all this: a behaviour with three backends, and how normalising them to one message shape hid a failure mode that only existed in one.

Top comments (0)