How it works

On this page

This guide explains what happens inside a deploy, why each step is there, and what the library does when a step fails. You do not need it to use Hotcode; read it to decide whether to trust it.

Design

  1. The live node is the baseline. There is no stored release manifest to drift. To build a patch, the tooling asks the running node what it has and diffs against that.
  2. Switch code atomically, around suspended processes. The BEAM already knows how to hold two versions of a module; the hard part is state and timing, which is what Hotcode manages.
  3. Everything is undoable, or the node says it is not. Every step has a defined reverse, and when a reverse cannot be completed the node refuses further deploys rather than carry on in a state nobody can describe.

Building a patch

mix hotcode.build (and deploy) does this on your machine:

compile  ──▶  GET /manifest  ──▶  diff  ──▶  pack  ──▶  envelope
  • Manifest (Hotcode.Manifest): the node's list of modules, each with its MD5, its owning application and a SHA-256 code digest.
  • Diff (Hotcode.Patch): a module ships when its digest differs from the node's, or when the node does not have it but a running application owns it. A module is removed when its application is part of your build and the module is gone. Hotcode itself and applications the node is not running are never shipped.
  • Pack (Hotcode.Bundle): a .tar.gz of the changed beams plus a manifest of their digests.
  • Envelope (Hotcode.Envelope): the patch plus a statement about it (audience, expiry, the code it replaces, flags) plus signatures over that statement.

Because the diff covers the whole build, everything the compiler rebuilt is included: callers that inlined a changed macro or attribute, changed dependencies, re-consolidated protocols. You never list modules by hand.

Two digests, two jobs

digest covers used for
code digest the chunks that define behaviour (atoms, code, literals, imports, exports, funs, attributes) and nothing else deciding what changed. The same source built in another directory gets the same digest
file digest the exact bytes the signature, so the signed patch cannot change by a single byte

Debug info, line tables and @external_resource paths are excluded from the code digest because they record where a module was built, not what it does. The VM only exposes MD5 for loaded modules, so MD5 appears where a loaded module is compared with a beam; it is never used to authenticate anything.

The node side: a deploy, step by step

Everything below runs inside one process, Hotcode.Loader, so deploys on a node are serialized.

1. Verify (Hotcode.Trust)

In order, and stopping at the first failure: the node is not locked; enough distinct trusted keys signed; the statement is a deploy for this audience, inside its window, with a sequence number above the last accepted; the patch hashes to what was signed; it unpacks; every module touched is allowed by policy. Then the patch's base (the MD5 of every module it replaces) must equal what the node runs right now.

2. Plan and analyze (Hotcode.Analyzer)

The node works out what changes and what is risky, and may refuse (see Troubleshooting for each finding). --dry-run stops here.

The plan also reads, without suspending anything, the states of the processes step 5 will suspend and of the processes that may hold a changed struct (one :sys.get_state each, 16 at a time, 300 ms each; see struct scan settings). In those states it looks for closures defined in a patched module (Hotcode.Closures): such a closure raises :badfun once the version it points at is purged, so each one is reported as :closure_in_state, a warning (a block with config :hotcode, block_on_closure_in_state: true), with the process, the module and a path into the state (state.callbacks.0). The walk stops after 24 levels or 20 000 terms per state. And it reads the app's compiled code for calls to other nodes (:erpc, :rpc, Node.spawn, :gen_rpc with a literal module and function) whose target the patch removes or adds: :cross_node_contract (see Clusters).

3. Snapshot

To roll back, the node needs the beam it is about to replace. The VM keeps no copy of a loaded module, so it uses the one it loaded earlier through Hotcode, or re-reads it from disk only if its MD5 equals the loaded module's. If neither is available the deploy is blocked rather than made un-rollbackable.

4. Purge old code

The BEAM keeps at most two versions of a module. Loading a third kills any process still running the oldest. Hotcode uses a soft purge, garbage-collects processes that merely hold stale references, and if any process still runs old code it aborts instead of letting a hard purge kill it.

5. Suspend

The processes whose behaviour module changed (found through gen_server, gen_statem and supervisor initial calls) are suspended with :sys.suspend/2, and so are the processes whose initial call is in a changed module under allowed_prefixes (a Phoenix channel reports {MyChannel, :join, 3} while it runs inside Phoenix.Channel.Server): a request one of them is handling at the switch would otherwise run half on the old code and half on the new. Messages queue in their mailboxes; sockets they own stay open. Nothing is lost. A channel or LiveView process of a changed module (its module declares @behaviour Phoenix.Channel or Phoenix.LiveView) is handled like a hosted behaviour: its code_change/3 runs in step 8, through Phoenix's, with the socket as the state.

6. Check on copies, before loading

A release the node refuses must not run, not even between loading it and finding out. So what can be checked on a copy is checked before anything is loaded. The node loads each module it needs under another name (a shadow: the module name is rewritten in the beam, so no process can reach it), runs it on copies of the live data, and unloads it again:

  • every Hotcode.Table whose module changes: all its rows through the new upgrade/2 chain, and a sample of the result back down the downgrade/2 chain. This runs before applications are stopped for a restart and before processes are suspended.
  • every suspended Hotcode.Versioned process (and the user state of a hosted one): its changed structs reshaped, then the upgrade/2 chain, then the downgrade/2 chain. The processes are suspended, so the state checked is the state that will be migrated.

A failure here refuses the release with the error a failure after loading would give ({:table_migration_failed, info} or {:migration_failed, info}), with info.loaded == false. Step 8 runs the same checks again on the loaded code and keeps its undo, for what a shadow cannot show (see refused before or after loading).

7. Load, atomically

All new modules switch at once (:code.prepare_loading + :code.finish_loading). There is no window in which half the modules are new. (@on_load modules cannot join an atomic load. A new one is loaded first, before the batch, so nothing that the batch switches on can call a module that is not there yet, and it is unloaded again if the batch fails. Replacing a loaded one is blocked: it would unload its library under running processes.)

# what steps 7 and 8 do for one process, in order (simplified from Hotcode.Loader):
:sys.suspend(pid)                                   # messages queue, sockets stay open
:code.prepare_loading(binaries)                     # all or nothing
:code.finish_loading(prepared)                      # every module switches at once
:sys.replace_state(pid, &Hotcode.StructMigrator.migrate(&1, changed_structs))
:sys.change_code(pid, mod, old_vsn, extra)          # your code_change/3, or Hotcode.Versioned
:sys.resume(pid)

8. Migrate, per process

For each suspended process, in a fixed order: structs in its state that changed shape are rebuilt (Hotcode.StructMigrator), then :sys.change_code/4 runs the module's code_change/3 (or Hotcode.Versioned's generated one).

9. Resume, reconcile, persist

Processes resume. If a supervisor's module changed, its children are reconciled (added, removed or restarted, see the restart-free guide). The patch is written to store_dir, the replay counter advances, hooks and telemetry fire, and the audit log is written.

When something fails

Every failure leaves the node either as it was or in a state that is reported, and locked when the old code cannot be confirmed. It is never left half-upgraded without a report.

failure what happens
a process cannot migrate processes already migrated are downgraded by the new code (the only code that knows its own state), then the old code is reloaded. A process that cannot be downgraded is killed so its supervisor restarts it clean
the old code cannot be put back (a process still runs a displaced version) processes not yet migrated would crash on their next message, so exactly those are recycled; the rest keep the new code consistently. Reported, not hidden
an exception mid-deploy the loader survives it, tries to put the old code back, and locks the node if it cannot confirm that
an application will not start on the new code the whole deploy is undone, including state shapes; every application comes back on the old code
writing the store fails the code is already live, so the deploy still succeeds, reported as not persisted
a rollout step times out the node is reported as needs_attention, not rolled back blindly, because it may still finish

Refused before or after loading

Refused before any module of the release is loaded, so no process ever runs it:

  • verification, base, requires, policy (step 1); analyzer blocks and the before_deploy veto (step 2); a module whose loaded beam cannot be snapshotted (step 3); old code still running (step 4); a process that cannot be suspended in time (step 5);
  • a table chain: a missing upgrade/2 or downgrade/2 clause, a step that raises, a vsn lower than the rows' (step 6, loaded: false);
  • a Hotcode.Versioned chain on a live state: a missing upgrade/2 clause, a step that raises, a missing or raising downgrade/2 clause, a jump from a release that was not Hotcode.Versioned straight to vsn: 2 or higher (step 6, loaded: false). Adopting it at vsn: 1 keeps the live state and is not refused.

Found only once the release is loaded, then undone as described above (loaded: true):

  • a plain code_change/3 (not Hotcode.Versioned) that returns an error or raises, and a supervisor's code_change: they are your code and may have side effects, so they are not run on a copy;
  • a struct migration a process cannot take (it died, or did not answer);
  • an application restarted in place (Hotcode.AppSwap) that does not start on the new code;
  • a check of step 6 that could not run there: a module with @on_load (loading a shadow would run the hook); a step that raised in a module that calls another module of the same release (the shadow calls that module's old version, so only the loaded code can tell); a state that could not be read within 5 seconds;
  • rows written to a table, between step 6 and the migration, by a process the deploy does not suspend.

The checks of step 6 need a shadow: the new module loaded under another name, so its chains run on a copy while every process still runs the old code. When a shadow cannot be loaded (an @on_load module, or a beam the node cannot rewrite on its OTP version), that module's checks run after loading instead: the release is loaded, checked, and undone if a check fails (loaded: true). A release is never accepted because a check could not run. Any reason other than @on_load is unexpected: it is logged once as a warning and reported as telemetry [:hotcode, :shadow, :unavailable] (metadata %{module:, reason:}).

The check runs the upgrade/2 and downgrade/2 chains that the generated code_change/3 runs. A module that overrides code_change/3 is still checked against those chains.

When applications are restarted in place, they are stopped before processes are suspended, so a process state refused in step 6 still means those applications were stopped and started again, on the old code.

A locked node refuses every deploy until an operator has looked and called Hotcode.unlock/0. See the runbook.

Rollback

A rollback is a signed statement that names the version it undoes. The node downgrades state first (while the new code is still loaded), then reloads the old binaries, lets each changed supervisor re-read its child specs from the old code, and reconciles its children. It first checks that the old code can be put back, so it never downgrades state it cannot then match with code.

After a restart

A hot-loaded module lives only in memory, so a node that restarts from the old release would silently boot the old code. With store_dir set, each applied patch is stored as the raw signed envelope and re-verified at boot, before your application starts, in order and only while it still fits:

  • a patch whose modules are already at its version (a newer release contains it) is a no-op;
  • one whose modules are at neither its base nor its version (the release moved on) is discarded, along with every later patch;
  • a rolled-back patch is recorded in a revoked set and never replayed;
  • a node started locked replays nothing.

The store directory is treated as untrusted input; see Security.

Clusters

Hotcode.Rollout first asks every node for a dry run (Loader.preflight_binary/1) and stops if any would refuse. Then it deploys node by node. After each node it waits (settle), runs the health check, and only then moves on. A failure undoes the nodes already done. Each node verifies the signed patch itself, so a compromised coordinator cannot make a node accept anything the signers did not sign. Tooling nodes that merely joined the cluster (your mix task, a remote shell) are not deploy targets.

Map of the code

module role
Hotcode.Loader the deploy/rollback state machine
Hotcode.Trust, Envelope, Guard, Audit authorization, brakes, trail
Hotcode.Patch, Manifest, Bundle, Hash building and diffing
Hotcode.Analyzer preflight findings
Hotcode.StructMigrator, Versioned state migration
Hotcode.Holder, Handoff, Swap, Supervision, AppSwap replacing processes without losing state or sockets
Hotcode.Rollout, Health, Store, Server, Client cluster, boot replay, transport

Pitfalls it does not solve

Found by reviewing the engine against the BEAM's behaviour. Design around each of them; the Credo rules find the ones that show in source.

  • Closures stored anywhere die at the second deploy. Hotcode keeps the displaced version of a module until the next deploy (one grace version, like the VM's own two), and purges it then. An fn or a local capture (&helper/1) in state, ETS, :persistent_term, a message or a timer works for one more deploy and raises :badfun after the next one that replaces its module. A process holding one does not keep old code alive, so the purge does not see it. The plan reports those it finds in the states of the processes the deploy touches (:closure_in_state); closures in other processes, ETS, :persistent_term, messages and timers are not looked for. Store &Mod.fun/arity or {mod, fun}.

  • :telemetry handlers attached with a closure are detached, at the first event after the second deploy of their module (telemetry logs it). Attach with &Mod.handle/4.

  • A worker that traps exits must check Hotcode.Swap.swapping?/0 in terminate/2. Swap.child stops the old process with the supervisor's ordinary :shutdown, so its terminate/2 runs, after its sockets were handed over. Any process can close a port, owner or not, so a terminate/2 that closes its socket closes the replacement's connection. Skip what was handed over when the process is being swapped, keep the rest of the cleanup:

    def terminate(_reason, state) do
      unless Hotcode.Swap.swapping?(), do: :gen_tcp.close(state.socket)
      flush_metrics(state)
    end

    A terminate/2 that ignores it is caught: the swap returns {:error, {:closed_in_terminate, ports}} and logs it, but the client connection is gone. (AppSwap kills its workers instead, so their terminate/2 does not run at all.)

  • Swap does not buffer what is sent by name during the gap. Messages already waiting in the old mailbox are re-sent to the new process; a call among them is run there, but its caller monitors the old process and has already exited with :shutdown, so a caller that retries runs it twice. From the moment that mailbox is read until the new process registers the name, a cast by name is dropped, a send/2 to the name raises and a call exits (:shutdown or :noproc); right after registering, the new process can answer once with the fresh state of its init/1. A proxy holding the name cannot close this: the child's start registers the name itself. Callers should retry requests that are safe to run twice (see restart-free).

  • A busy process is migrated, or the deploy fails. A struct holder that does not answer :sys.get_state in 300 ms is treated as a holder (suspended, which waits for it), never skipped. Suspension is sequential by default (struct_scan: [suspend_concurrency: n] runs n at a time): every affected process stays suspended until the last is migrated, so a caller using the default 5 s call timeout may give up meanwhile, and two processes that call each other can make the deploy fail with suspend_failed. On a node whose schedulers are saturated every one of those reads and suspensions waits in the run queue: measured costs and the settings are in Operations. Deploy at a quiet moment, and keep carriers narrow.

  • Hosted behaviours are not migrated unless their host is listed. A process whose behaviour is hosted by a library (GenStage, Broadway, gen_event) is reported under the library's module, not yours: by default its code_change/3 is not run and its state is not migrated. List the host in config :hotcode, hosts: [GenStage, :gen_event, ...] and the deploy reads your module out of the host's state, then suspends and migrates the process through the host's code_change/3 (see State migration). Broadway has no built-in entry, and its stages run no code_change/3 of yours.

  • A protocol implementation outside allowed_prefixes is not shipped. String.Chars.MyApp.Money does not start with MyApp, and it would only dispatch once the consolidated String.Chars (a standard-library module no patch may replace) is replaced as well. So a patch that adds it carries on without it: the build prints warning: String.Chars.MyApp.Money (defimpl String.Chars, for: MyApp.Money) is NOT shipped ... and the summary carries a :protocol_impl_not_shipped finding, and to_string/1 raises Protocol.UndefinedError on the new type. Deploy new implementations of standard-library protocols with a release. Protocols under your prefix (and their consolidated module) ship like any other module. Why there is no exception: security guide.

  • Compile-time values are the build's. @url Application.get_env(...) and compile_env are read when the patch is compiled. The analyzer warns about a build outside MIX_ENV=prod (:build_env); it cannot know what a module captured.

  • Removed functions are warned about, not checked. The analyzer lists the exports a changed module drops (:removed_exports), and the remote calls to them it can read in the code (:cross_node_contract); an MFA in a job queue, in config or in a message in flight that names one still fails with undef.

  • ETS is handled by Hotcode.Table: create tables with it and the rows are migrated and the table survives its owner. A plain :ets.new/2 table is neither, and is lost with a replaced process.

  • A supervisor's init/1 runs again (in a scratch process, to compare children). Keep init/1 free of side effects such as :ets.new, :persistent_term.put or :telemetry.attach.