One of my two backtest workers spent a night running jobs it had no way to finish. It had never joined the cluster. Every job it picked up reached for a process on another machine, found nothing there, and crashed — 2,378 times by morning. The other worker was fine, until the retries drained the database connection pool out from under it.


Where this fits

How I Keep Two Servers in Sync Without a Message Broker was the decision: a live trading node and a backtest worker sharing one broker quota and one set of OAuth tokens, held together with Distributed Erlang instead of a message broker. Clustering BEAM Nodes Across a Droplet and My House was the plumbing underneath it, as originally shipped — including a connector process with three bugs I could name in hindsight. This is the night those bugs stopped being hypothetical.

The short version of the setup: the worker never owned its own broker credentials. When a backtest needed historical bars, it asked the web node's token store and rate limiter for permission, by name, across the cluster. That's the right design when the cluster is up. This post is about what it does when the cluster isn't.

What the night looked like

Reconstructed from the error tracker and the notes I wrote the next day:

(times UTC)
evening      worker A starts, joins the cluster
             worker B starts, tries to connect every few seconds, never succeeds
             ... connector gives up, gets restarted, tries again, all night ...
05:00        overnight optimization jobs start; the ones on worker B crash
07:00        daily backfill jobs start; the ones on worker B crash
07:05        database connection pool exhausted — now worker A's jobs fail too
08:00–09:00  peak error volume, both workers failing
morning      2,378 crashed jobs: 462 optimization, 1,916 backfill

What gave it away was a spike in AppSignal's error count. Nothing else noticed. A worker that can't reach anything still reports itself as running, and Kubernetes had no reason to think otherwise. The pod was up, the BEAM was up, Oban was up and pulling jobs. The only part of the system that knew why was a connector process logging a retry every few seconds to a log nobody was reading.

Why worker B never got in gets its own post. The short version: I was bringing up a second worker on a second laptop, before I'd set any node placement rules, and before I'd given each worker its own identity. Both pods came up with the same BEAM node name and the same Tailscale identity. The cluster already had a member by that name, and it was worker A.

Why every job crashed instantly

The worker's market data client fetched bars in chunks, and before each chunk it checked the rate limit and asked for a token:

case TSSession.check_rate(state.session_args, :barchart) do
  {:ok, _} ->
    token = TokenStore.get_token(state.token)
    # ...

Both of those are calls to globally registered names on the web node. The rate limiter's call had picked up a fail-open wrapper a couple of weeks earlier — it catches the exit and returns {:ok, 0} — so the check passed. That's the opposite of what a shared limiter is for: a disconnected worker would have spent the budget unchecked if the very next call hadn't crashed first. The token store's call wasn't wrapped:

def get_token(%TradeStationToken{} = token) do
  GenServer.call({:global, __MODULE__}, {:get_token, token.id})
end

In the post on keeping two servers in sync, I said this call doesn't wait — it exits the caller. This is what that looks like at volume. :global's name table is replicated to every connected node, so resolving a name is a local lookup. On a node that has never joined the cluster, the table is empty, the lookup fails, and the call exits with :noproc immediately. No network, no wait.

So a job that should have spent minutes downloading bars crashed in milliseconds. Oban recorded the exit, scheduled a retry with backoff, and moved on to the next job, which crashed the same way. Concurrency on those queues was one — by then the worker ran a queue per job type, not the single back_tests queue it shipped with. The volume didn't come from parallelism. It came from failing fast enough that the queue never ran out of things to fail.

And each crash cost a database connection. A job that died mid-run left its connection leased, and the pool didn't take it back until the lease timed out. The retries leased new ones faster than the old ones expired, until there were none left — for worker B's crashing jobs or worker A's healthy ones.

Why reordering the supervision tree did nothing

The clustering post listed three bugs in the connector. One of them was that it started last in the worker's child list, after Oban, so the worker could pull jobs before it had even tried to join the cluster.

That one had been fixed a couple of weeks before this night. I'd moved the connector ahead of Oban and had it call :global.sync() once connected. It made no difference, because the connector's init/1 still looked like this:

send(self(), :connect)
{:ok, %{nodes: nodes, attempts: 0, connected: false}}

A supervisor starts its children in order, but "in order" only means each child's init/1 has returned. This one returned immediately and did its connecting afterward, in handle_info. The first connection attempt went out at roughly the same moment Oban started, and it took seconds to succeed even on a good day — on worker B, it never did. Reordering a child list buys you nothing if the child you moved doesn't block.

Fix one: don't start until you're connected

The connector became a gate. init/1 now does the connecting itself and doesn't return until it succeeds, so nothing after it in the child list — Oban included — starts on a worker that isn't in the cluster:

def start_link(opts) do
  GenServer.start_link(__MODULE__, opts, name: __MODULE__, timeout: :infinity)
end

@impl true
def init(_opts) do
  nodes = get_cluster_nodes()

  if nodes == [] do
    info("No CLUSTER_NODES configured, skipping cluster connection")
    :ignore
  else
    connect_with_retry(nodes)
    :global.sync()
    :net_kernel.monitor_nodes(true)
    {:ok, %{nodes: nodes}}
  end
end

defp connect_with_retry(nodes) do
  all_connected? =
    nodes
    |> Enum.map(fn node ->
      case Node.connect(node) do
        true ->
          info("Connected to #{node}")
          :connected

        false ->
          warning("Failed to connect to #{node}")
          :failed

        :ignored ->
          info("Already connected to #{node}")
          :ignored
      end
    end)
    |> Enum.all?(&(&1 in [:connected, :ignored]))

  unless all_connected? do
    info("Retrying cluster connection in #{div(@retry_interval, 1000)}s...")
    Process.sleep(@retry_interval)
    connect_with_retry(nodes)
  end
end

Three details in there, and I only got one of them right for the right reason.

:global.sync() after connecting was already there, and it matters. A successful Node.connect doesn't mean the name tables have merged yet, and a job that started in that gap would fail the same way the overnight ones did.

The timeout: :infinity doesn't matter. I added it believing start_link would otherwise give init/1 five seconds. It wouldn't — GenServer.start_link already defaults to :infinity; the five seconds I was remembering belongs to GenServer.call. It stays as documentation of intent.

The design notes from the time also insist the loop use Process.sleep rather than a receive, because node-up and node-down messages "would be silently consumed." That reasoning doesn't hold up either: Process.sleep/1 is a receive with only an after clause, and the process doesn't subscribe to node events until after the loop finishes, so there was nothing to consume.

The habit is still a good one: a startup loop with no message patterns can't eat a message meant for handle_info. It just wasn't load-bearing here.

Fix two: stop taking work when the link drops

Blocking at boot covers a worker that never joins. It does nothing for a worker that joined and then lost the connection. For that, the connector now subscribes to node events and pauses the job queues when the web node disappears:

@impl true
def handle_info({:nodedown, node}, state) do
  if node in state.nodes do
    error("Cluster node #{node} disconnected — pausing all Oban queues")
    Enum.each(@worker_queues, fn queue -> Oban.pause_queue(queue: queue) end)
  end

  {:noreply, state}
end

@impl true
def handle_info({:nodeup, node}, state) do
  if node in state.nodes do
    :global.sync()
    Enum.each(@worker_queues, fn queue -> Oban.resume_queue(queue: queue) end)
  end

  {:noreply, state}
end

The node in state.nodes guard is there because :net_kernel.monitor_nodes/1 reports every node in the cluster, not just the ones you care about. With two workers, each one sees the other come and go. Without the guard, a sibling worker restarting would pause your queues.

A paused job isn't a failed job. Pausing stops new jobs from being fetched — anything already mid-run when the link drops can still fail — but everything still queued sits there until the link is back, then runs. That's the behavior the overnight crashes should have had.

Fix three: take the token off the critical path

The first two fixes stop jobs from running without a cluster. The third makes the most common job need the cluster less.

Every chunk of every backtest download made a cross-node call for a token. But the worker could already read the token row from Postgres, and it had the key to decrypt it. So it got its own token store: a local GenServer that reads the row, caches it for a minute, and refreshes it itself if it has expired.

That's a second process refreshing the same credential — the thing the original design existed to prevent. It's safe here only because of the premise I hadn't checked: TradeStation doesn't rotate refresh tokens, so two refreshers each end up with a valid access token and the last write wins.

defmodule MyApp.Connections.TradeStation.WorkerTokenStore do
  use GenServer

  @cache_ttl_ms 60_000

  def get_token(%TradeStationToken{} = token) do
    GenServer.call(__MODULE__, {:get_token, token})
  end

  @impl true
  def handle_call({:get_token, %TradeStationToken{id: token_id}}, _from, state) do
    now = System.monotonic_time(:millisecond)

    case state.cache do
      %{^token_id => {cached_token, fetched_at}} when now - fetched_at < @cache_ttl_ms ->
        {:reply, {:ok, cached_token}, state}

      _ ->
        {result, new_state} = fetch_and_cache(token_id, state, now)
        {:reply, result, new_state}
    end
  end
end

This one did not ship cleanly. The same market data client runs on the web node too, for live trading sessions, and the first version switched it to the worker's token store unconditionally. The web node doesn't start WorkerTokenStore, so the next day market data stopped flowing to live sessions, and I reverted the wiring.

The revert broke too: the call site still expected {:ok, token}, the original store returns a bare token, and production spent another half hour raising CaseClauseError before that was fixed. The version that stuck, a couple of weeks later, first gave both stores the same return shape ({:ok, token, meta}), then picks the store at call time:

defp token_store_backend do
  case System.get_env("RELEASE_MODE") do
    "worker" -> WorkerTokenStore
    _ -> TokenStore
  end
end

The rate limiter stayed global, on purpose. A rate limit is shared mutable state — two workers each holding a local copy of "how many requests are left" is two workers each spending the whole budget. With the queues paused on disconnect, no new job should be starting to ask it anyway.

Three more outages the fixes didn't cover

All three fixes were correct for the failure I'd just had. Each of the next three failures found something they didn't cover.

Paused, forever. A couple of months later, the web node restarted. The worker saw :nodedown and paused its queues, exactly as designed. Then it waited for :nodeup. That never came, because nothing was trying to reconnect: a freshly booted web node doesn't dial the worker, and the connector only dialed at startup. The queues sat paused for about twenty hours. The pods reported Running and Ready the whole time, because "the BEAM is up" was all the liveness probe checked. The probe now checks the cluster connection and the database, and kills a worker that has been disconnected for more than a few minutes.

Paused by the cluster itself. Later still, a worker deploy tripped :global's protection against overlapping partitions: the running worker tried to connect to the newly started one before the new worker's hostname would resolve, and :global responded by disconnecting the web node instead. Every worker paused. Nothing reconnected until the liveness probe started killing pods six and a half minutes later. That one finally got the connector a real reconnect loop — bounded backoff, resume only once every configured node is back — and a bounded wait at startup until a fresh worker's own tailnet hostname resolves, so its peers can dial back before it joins.

The same bug, in a new job. The most recent one was the original failure again, in miniature. A new candle backfill job, added months after the incident, called the global token store directly from the worker. It crashed 135 times in one burst when the web node went away. The job now catches that exit and snoozes instead of crashing. It also turned out to be in a queue the pause fix didn't know about — the list of queues to pause was hardcoded, and nobody had added the new one. The pause and resume now cover every queue on the node instead of a hardcoded list. They also cover only that node. The original calls were cluster-wide by default, so one worker's reconnect had been resuming every other worker's queues too.

defp pause_queues(%{queues_paused?: true} = state), do: state

defp pause_queues(state) do
  Oban.pause_all_queues(local_only: true)
  %{state | queues_paused?: true}
end

What the cluster was actually telling me

The title says the cluster lied. It didn't. When the broker lied, it really did — it accepted an order and didn't execute it. Here nothing lied. The worker reported itself running because it was running. The connector reported that it was retrying because it was retrying. Oban reported crashed jobs because the jobs crashed. Each piece told the truth about itself, and none of them was responsible for the question that mattered: can this node do the work it's taking?

The fixes all ended up answering that question in a different place — at boot, on a node event, in the liveness probe, at the call site. An owner for that question is what I'd have built first, if I'd started from the failure path instead of the happy one. A name that resolves locally fails locally, and fast. Anything that depends on a remote name needs an owner for "and what if it isn't there," because the call itself won't wait around to find out.


Why the second worker could never join in the first place gets its own post.