Clusters: rolling a deploy, and changing what nodes say to each other

On this page

A deploy to a cluster is a roll: one node after another. While it runs, and for as long as a failed roll or a partition leaves it, the cluster is mixed: some nodes run release N, some N+1. Everything that crosses a node boundary has to work between the two.

This guide covers what the library guarantees about the roll, and the one thing it cannot do for you: change a message format between nodes.

What a roll does

Hotcode.Rollout.deploy_cluster(signed_envelope)

(mix hotcode.deploy calls this on the node it talks to; every node that runs Hotcode and is connected to it is a target. Tooling nodes, a remote shell or an observer, are not.)

  1. Wait for old code (only with --wait-for-old-code or config :hotcode, wait_for_old_code:). Every node verifies the envelope (signatures, audience, expiry, replay counter, module policy) and then waits for processes on the code it replaces to end. An envelope that does not verify makes no node wait. The wait comes before the roll lock below is taken, so it holds nothing.
  2. Preflight. Every node is asked, one by one, whether it would accept the patch right now (Hotcode.Loader.preflight_binary/1). That runs every check a deploy runs, the signature threshold, audience, expiry, replay counter, base code, requires, module policy and the analyzer's blocks, and it changes nothing. If any node would refuse, the roll stops here: {:error, %{node: n, stage: :plan, reason: r, rolled_back: []}}. No node ran the new code, not for a moment, so no client ever saw it come and go.
  3. Deploy, node by node, each node verifying the signed envelope itself. The coordinator is not trusted: it carries bytes, it cannot vouch for them.
  4. Health check after each node. A failure, or a failure the dry run cannot predict (a crash while loading), puts the nodes already done back, and reports stage: :health or :deploy. The undo is aimed at this roll's patch (its version and signed seq): a node where something else is on top by then is not touched, and is listed under needs_attention.

One roll at a time. A roll holds a cluster-wide lock (:global, on the coordinator and every connected target) from its preflight to its last health check or undo. A second roll, started from any node while the first runs, does not wait and does not touch anything:

{:error, %{node: coordinator, stage: :plan, reason: :roll_in_progress, rolled_back: []}}

Run it again when the first one has returned. (It does not queue, because its preflight answers would be stale by then.) The lock goes when the roll returns or its process dies. A signed rollback does not take it: undoing an incident never waits for a roll.

What a roll does not do: it is not a transaction. A node that dies between preflight and its turn fails the roll at :deploy, and the nodes before it are rolled back. A node that is partitioned away is not a target; see below. A node that is connected but slow (its loader busy, or the whole VM stalled) stays a target: the roll fails at :plan on it after node_timeout, and the gate counts it as "not applied". Two coordinators that cannot see each other (a partition) do not share the lock either; expected_nodes and the preflight are what stop a roll from passing a node it cannot reach.

Known limits of requires and Hotcode.Cluster.applied?/2:

  • Releases a node got cold. They count the hot patches a node has live (applied and not rolled back, since boot or restored from its store) plus the releases the node's image declares it contains. Without the declaration a release folded into a new image is never "applied", and a later --requires on it fails safe forever. Declare it in the image's config:

    # this image was built from a tree that includes r1 and r2
    config :hotcode, releases: ["r1", "r2"]

    Hotcode.Loader.status/0 reports it as releases. The node takes the list on trust, like the rest of its config: list only what the image really contains.

  • Names, not contents. They match the name of a release (the bundle version), which by default is the git short SHA, and two builds of one dirty commit share it. Build any release you will require with --version NAME so the name identifies one build. There is no content binding (NAME@sha256): a node that took a release cold has no patch hash to compare, and stored patches are re-applied at boot without one, so the check would fail on exactly the nodes it is meant to admit.

The mixed cluster, and why the receiver cannot translate

Suppose release 2 changes a message from {:ping, n} to {:ping, %{n: n, v: 2}}. During the roll, a node on release 1 receives it, and release 1's code has no clause for it. It crashes.

Making the receiver translate works in one direction only. Release 2 can learn to read the old format, because release 2's code is new. Release 1 can never learn to read the new one, because release 1's code is already running and cannot be changed. So whichever direction runs from a new node to an old node breaks, and an old node stays around for as long as the roll, a failed roll or a partition lasts.

The only order that works is expand, then contract, in three releases:

release receivers senders safe to roll back?
R1 read the old and the new format still send the old yes
R2 unchanged send the new, only where every node has R1 yes, back to R1
R3 drop the old-format clause not below R2

It is the same shape as the supervisor child you add in one deploy and use in the next, and the Postgres migration you expand before the code that needs it.

Calls whose target a patch changes

A remote call is a contract too. A function the patch removes (or whose arity it changes) is still called by the nodes on the old release; a function it adds is not there yet on them. The plan (--dry-run, the preflight of a roll, every deploy) reads the compiled code of the app (the modules loaded under allowed_prefixes and the patch itself) for calls to other nodes with a literal module and function, and reports each one whose target changes as :cross_node_contract, a warning:

# release 1, still running on the nodes not yet upgraded
def total(node, id), do: :erpc.call(node, MyApp.Cart, :total, [id])

# the patch changes MyApp.Cart.total/1 to total/2: the plan says
# [warn] MyApp.Remote calls MyApp.Cart.total/1 on other nodes (erpc:call/4) and this patch
#        removes it: while the roll runs, a node on the old release calling an upgraded one
#        gets :undef. Change a cross-node contract in three releases: ...

Recognised: :erpc.call/cast/multicall/multicast/send_request, :rpc.call/cast/multicall/ async_call/block_call/eval_everywhere, Node.spawn and :erlang.spawn* with a node, and :gen_rpc.call/cast/async_call/multicall. The arity is known when the argument list is a literal or built in place. Not seen, so still yours to check: an MFA held in a variable or in config (Quantum jobs, {M, F, A} options), job arguments, GenServer.call({name, node}, msg) (the message shape is the contract), and Phoenix.PubSub payloads. The fix is the same three releases: add the new function beside the old one (R1), switch the callers gated by Hotcode.Cluster.applied?/1 (R2), remove the old function (R3).

What the library provides

1. requires: the order, signed

mix hotcode.build https://node-a:4747 --out r2.hcp --key alice.key --requires r1 --version r2

--requires r1 puts "requires": ["r1"] in the signed statement: release r1 must be live (applied and not rolled back) on a node for it to accept this patch. Because the preflight asks every node, the roll does not start unless every node has r1:

{:error, %{node: n, stage: :plan, reason: {:requires_not_applied, ["r1"]}, rolled_back: []}}

The signers state the order; nobody has to remember it, and nobody can strip it, because it is under the signature.

2. Hotcode.Cluster.applied?/1: the gate for the sender

Release R2 writes the new format only when it is safe:

defmodule MyApp.Wire do
  def send_ping(node, n) do
    if Hotcode.Cluster.applied?("r1"),
      do: GenServer.cast({MyApp.Inbox, node}, {:ping, %{n: n, v: 2}}),
      else: GenServer.cast({MyApp.Inbox, node}, {:ping, n})
  end
end

requires guarantees R1 was everywhere when R2 was applied. The gate covers what happens after: a node that joins later on the bare release, a node that came back from a restart without its patches (within one cache period: the gate may keep its last answer for cluster_cache_ms). It answers from a cache of config :hotcode, cluster_cache_ms: 1_000, so it is cheap enough for a hot path, and it is conservative: a node that does not answer, or answers too slowly, counts as "not applied", so the old format keeps flowing until the answer is yes.

When the cache expires, callers do not each probe the cluster: one refresh runs per release and everyone asking meanwhile shares its answer. An expired "no" is returned at once while that refresh runs (no is always safe); an expired "yes" is never served, the callers wait for the refresh. A slow refresh that finishes after a newer one cannot overwrite its answer.

3. expected_nodes: the partition case

A node cut off from the rest cannot be seen, so the visible nodes might all have R1 while the hidden one does not, and the gate would open. Name every node that must be heard from:

config :hotcode, expected_nodes: [:"app@10.0.0.1", :"app@10.0.0.2", :"app@10.0.0.3"]

An expected node that does not answer closes the gate. The test a partition hides a node from the gate in test/cluster_wire_test.exs shows both behaviours.

Every node watches the cluster

A roll is judged by whoever ran it. A node that never got the patch, a coordinator that died half way, a node that came back from a restart on the old release: nobody sees it. So every node keeps a table of every node of the cluster and the release it runs:

Hotcode.Cluster.members()
#=> [%{node: :"app@10.0.0.1", status: :up, version: "r2", releases: ["r2", "r1"],
#=>    seen_ms_ago: 3_100, on_version_ms: 41_000, diverged_ms: nil},
#=>   %{node: :"app@10.0.0.2", status: :up, version: "r1", ..., diverged_ms: 38_000}]

It is kept fresh three ways: a node that deploys or rolls back announces it to its peers at once, :net_kernel.monitor_nodes/1 notices a node that goes away, and every interval_ms (10 s) each node probes all of them again, which catches whatever an announcement missed.

The convergence check reads that table. It starts in report mode, which changes nothing:

config :hotcode, convergence: [mode: :report, after_ms: 60_000, interval_ms: 10_000]

A cluster that is still on more than one release after_ms after the last roll ended is reported: a warning in the log, the audit event :cluster_diverged, and telemetry [:hotcode, :cluster, :diverged] with the release of every node, the one most nodes run and the nodes off it. [:hotcode, :cluster, :converged] follows when it is one release again. Hotcode.Cluster.Members.report/0 gives the current verdict. mode: :off turns it all off.

Two things are deliberately not judged:

  • A roll in progress. The coordinator tells every node when a roll starts and ends, and the clock starts when it ends.
  • A node that cannot be reached. It may be dead, slow or cut off, and the others cannot tell which. It is reported once ([:hotcode, :cluster, :node_down], audit :cluster_node_down) and left alone, because a partition must never make two halves undo each other.

Converging forward

In mode: :converge a node that is reachable but behind catches up by itself. Nothing of this runs in :report (the default) or :off.

config :hotcode,
  convergence: [mode: :converge, after_ms: 60_000, attempts: 3, backoff_ms: 5_000]

Who is ahead. Versions are names, not numbers, so direction comes from history: a node whose releases contain another node's release is ahead of it. A node pulls only when the reachable nodes form one line: exactly one release is ahead of all the others, and every other node runs a release in its history. Two releases that are not in each other's history (a fork: two patches built on the same base and applied to different nodes) are never resolved automatically: after after_ms every node reports [:hotcode, :cluster, :cannot_converge] and the audit event :cluster_cannot_converge, once, and an operator decides.

Who acts. Each lagging node, for itself, once it has been behind for after_ms (the clock restarts when a roll ends). Not while a roll is in progress: the pull takes the same lock a roll takes on that node. Not while the node is locked or in failure lockout (Hotcode.Guard), not while its loader is busy, and one pull at a time. It pulls from a random node that is ahead and :up, after a random part of backoff_ms, so a dozen lagging nodes do not all ask the same node at the same instant. A node that cannot be reached is never a source, and nobody pushes to a node: the lagging node asks, or nothing happens.

What is pulled. The signed envelopes of the releases the node lacks, in order, read from the source's store_dir (Hotcode.Store.stored/0 and envelope/1). Only a node with a store_dir can be a source: without one, the envelope of a hot patch is not kept anywhere after the deploy, and there is nothing to pull (the attempt fails with :no_stored_envelope). The bytes are not trusted: each envelope goes through the lagging node's own Hotcode.Loader.deploy_binary/2, exactly like an upload, with its own threshold, audience, expiry, replay counter, base, requires, module policy, analyzer blocks and before_deploy hook. A node configured for two signatures refuses a one-signature envelope that its peer accepted.

The TTL is a hard limit. An envelope expires (mix hotcode.sign --ttl-minutes, 15 by default). A node that lags for longer than that cannot catch up from it: the deploy is refused as :expired. This is the signers' deadline, by design. Every copy carries the same expiry, so it is reported at once and not retried. Such a node needs a new signed envelope (or a new image), as it would without this mode.

Bounded. At most attempts pulls, backoff_ms apart and doubling each time. Then the node stops and alerts: [:hotcode, :cluster, :converge_failed] and the audit event :cluster_converge_failed, with the reason (:expired, {:base_mismatch, _}, {:blocked, _}, {:requires_not_applied, _}, {:insufficient_signatures, _}, :no_stored_envelope, ...). Each attempt is audited as :cluster_converge_attempt (source, versions, result). The count starts over when the cluster is on one release again or a new roll starts. A refused envelope counts toward the failure lockout (five in a minute) like any other refusal, which is why attempts defaults to 3. A pull in progress holds the roll lock on its node, so a roll that targets that node meanwhile is refused with :roll_in_progress; start it again a moment later.

Hotcode.Cluster.Members.report().converge
#=> %{state: :failed, attempts: 1, last_error: :expired}

state is :idle, :pulling, :failed (gave up until convergence or the next roll) or :done (caught up by pulling). Hotcode.Cluster.Members.lineage/0 shows how the reachable releases relate (:converged, :behind, :forked), which nodes are ahead and behind, and how many nodes are reachable out of those known.

test/cluster_converge_test.exs runs it on real nodes: a node left out of a roll catches up from a peer's store; a tampered envelope and a one-signature envelope on a two-signature node are refused by the lagging node, three attempts and one alert; an expired envelope is reported as :expired after one attempt; :report never pulls; a fork pulls nothing and is reported; no pull during a roll; and a node cut off from the only node ahead neither pulls nor is pulled for until the partition heals.

Deadman rollback

Converging forward fails for good reasons: a node that needs two signatures, an envelope past its TTL, a base that does not match. The cluster then stays on two releases until someone looks. The deadman is the other way out: the signers of a release say, in the statement they sign, that it should be taken back if the cluster has not followed it within a deadline.

mix hotcode.build app@10.0.0.1 --out patch.hcp --auto-rollback-after 120s

The statement gains one field, "auto_rollback": {"after_ms": 120000} (and "attempts": N with --auto-rollback-attempts N). mix hotcode.deploy takes the same flags. The duration is a whole number of seconds or minutes (90s, 5m), at least 10 s and at most 24 h; anything else is a usage error (exit 2) before anything is built. A co-signer running mix hotcode.sign sees it before signing:

  type:        deploy
  audience:    prod-eu
  version:     r7
  ...
  AUTO-ROLLBACK: undone cluster-wide if a reachable node has not progressed after 120 s
  replaces:    MyApp.Billing
  signatures:  1 so far

The field is under the signatures like every other: changing, adding or removing it breaks them (:insufficient_signatures), and a malformed one (after_ms under 1 s or over 24 h, attempts outside 1..100, any other key) is refused as :bad_statement. Without the flag the statement has no such field at all, byte for byte what it was before, and nothing is ever undone automatically, whatever the mode.

Every node that applies the release keeps the policy in its stack entry, with the signed seq and when it applied it; Hotcode.Loader.status/0 shows it as head:

Hotcode.Loader.status().head
#=> %{version: "r7", seq: 1_767_225_600_000, requires: [],
#=>   auto_rollback: %{after_ms: 120_000, attempts: nil},
#=>   applied_at: -576_460_741_208, applied_at_wall: 1_767_225_612_345}

It acts only in mode: :auto:

convergence: [mode: ...] watches and reports pulls forward deadman rollback
:off no no no
:report (default) yes no no
:converge yes yes no
:auto yes yes yes, for releases whose statement carries auto_rollback
:spread yes yes, releases without a rollout policy no deadman; only the undo of a halted spread, for a release whose statement carries both a rollout policy and auto_rollback
config :hotcode,
  convergence: [mode: :auto, after_ms: 60_000, attempts: 3, backoff_ms: 5_000]

When. All of this, read from one node's table, in this order:

  1. the reachable nodes form one line (lineage/0 is :behind): never on a fork, never when they all run one release;
  2. this node runs the head release, and is the coordinator: the lowest node name among the nodes on the head. Every other node only watches;
  3. the head's stack entry here carries the signed policy;
  4. it was not applied before the last automatic rollback (see "never twice" below), and this {version, seq} was not acted on already;
  5. after_ms of the policy has passed since this node applied it, and every lagging node has been on its release at least that long;
  6. a strict majority of the nodes the table knows (up * 2 > known, expected_nodes included) is reachable;
  7. no node that cannot be reached was last seen running the head (it could not be undone there);
  8. no node, reachable or not, runs a patch that requires the head;
  9. then, from the coordinator: every lagging node answers that it gave up pulling (its converge state is :failed, or it made the policy's attempts), and the roll lock can be taken on every node involved, at once, without waiting. A roll in progress holds it, so the deadman never runs during a roll and no roll starts during it.

What. Only the head release, only on the nodes that run it, each through Hotcode.Loader.auto_rollback(version, seq) on that node, which checks again, locally, that its own convergence mode is :auto, that this exact entry is on top of its stack, that it carries the signed policy, that no newer entry requires it, and that the node is not locked. A node where it is already gone answers {:ok, :not_applied}. No new signature is asked for: the statement that deployed the release authorized its undo, and inside the cluster the cookie is the trust boundary, as for a roll.

Afterwards. The coordinator records the audit event :cluster_auto_rollback (who coordinated, which release and seq, which nodes, the lagging nodes, why: elapsed time, nodes up and known) and emits telemetry [:hotcode, :cluster, :auto_rollback]; every node's report().converge says state: :rolled_back with the same details under auto_rollback:. Each undo is also an ordinary :rolled_back event on its node, with via: :auto_rollback.

Never twice, never further. A release is acted on once. And an automatic rollback disarms the deadman for every release applied before it: if the release now on top also carries a policy, it is not undone in turn (no cascade down the stack). It re-arms with the next release applied.

A failure is not retried. If any node refuses or fails its undo, the coordinator records :cluster_auto_rollback_failed (with every node's answer), the telemetry event carries result: :error, every node reports state: :rollback_failed, and nothing is tried again for that release: the cluster is now in a state an operator has to look at.

On a partition, nothing happens. Each half sees half or less of the cluster, or sees the other half as down; the lagging nodes it cannot reach are not lagging as far as it can tell, and a node on the head it cannot reach blocks the undo. It alerts (:cluster_node_down, :cluster_diverged) and waits. When the partition heals, the whole cluster is judged again.

test/cluster_autorollback_test.exs runs it on real nodes: a three-node cluster, a release with --auto-rollback-after that one node cannot take (it needs two signatures); its pulls fail; the release is undone on the other two by one coordinator, under client traffic that never sees an error; and one test per rail (no policy, a minority, only unreachable laggards, an unreachable node on the head, the roll lock, the :converge and :report modes, a release another requires, a partition into halves, never twice, a failed undo not retried).

Spreading a release (mode: :spread)

For a large cluster, a roll driven by one node is slow and needs someone watching. With convergence: [mode: :spread] on every node and a rollout policy in the signed statement (--rollout-soak 10m --rollout-max-unavailable 10% ...), the operator deploys to a few canaries only (hotcode push r.hcp TARGET --canary 2); they soak and promote themselves, and every other node pulls the release from a node that has it, at most a capped share of the cluster (or of a group of nodes sharing a metadata value, with group_by) at a time, verifying it itself. Too many failures halt it, and a release that also carries auto_rollback is then undone with the deadman's rails. A node that runs the release decides with the policy of its own stack entry, which its loader verified; nodes that report different policies for the same release halt it ({:policy_conflict, nodes}). The version table can be kept in a :syn scope (members_backend: :syn) instead of probing every node. Everything above about message formats applies with more force: the mixed window lasts the whole spread. Rolling out to a large cluster has the roles, the policy, the rails and the failure modes.

Rolling back

Rolling R2 back is always safe: R1 reads both formats. Rolling R1 back is not, once anything wrote the new format: the nodes that took R1 back cannot read what is already in flight. The order above means you only ever roll back the newest release, which is the safe direction. That is a convention, not something the node enforces: a signed rollback is accepted on any node whose top release it names, so do not roll R1 back while R2 is anywhere.

Every rollback undoes the top of a node's stack and only that, and it says which: a signed rollback names the release it undoes and is refused where another one is on top (rollback_target_mismatch). The undo of a failed roll is held to the same rule, and to the exact signed deploy (seq) it made: on a node where another patch landed on top during the roll, it is refused with {:not_top, version, top}, nothing is undone there, and the node is listed under needs_attention. Look at it (mix hotcode.status), then roll back by hand, newest first. A rolled-back release is no longer live: requires and the gate stop counting it at once.

What was tested

test/cluster_wire_test.exs runs a real Demo.Inbox process on each of three nodes, and a pinger on each node that sends numbered messages to all of them for the whole scenario, through whatever Demo.Wire is live at that millisecond:

  • the three-release order, rolled across three nodes under that traffic: every message received, in order, no inbox crashed;
  • R2 refused cluster-wide before any node changes while one node lacks R1;
  • R2 applied early on one node holds the old format back until the laggards catch up, then switches by itself;
  • the same change in one release: the old nodes' inboxes crash;
  • rolling R2 back under traffic: no message lost;
  • a partitioned node: the documented blind spot, and expected_nodes closing it.

test/cluster_e2e_test.exs covers the roll itself on real nodes (a refusing node, a node that needs two signatures, the kill switch, a stale base, a replayed envelope, a dead node, a partition and its repair, a late joiner, a restart with the store, two operators at once), and test/cluster_gaps_test.exs the concurrency limits above: a failed roll that leaves another patch on top alone, a second roll refused with :roll_in_progress, fifty gate callers sharing one refresh against a node whose loader is stuck, a frozen node kept as a target, and releases declared by the image; and test/e2e/cluster_e2e_test.exs drives two real mix run nodes with the real mix hotcode.* tasks over HTTP.