Operations

On this page

Running Hotcode in production: configuration, commands, observability, clusters, and what to do when something goes wrong.

Configuration reference

All keys live under config :hotcode. Configure with config/runtime.exs. Required for any deploy to be accepted: trusted_keys, audience, allowed_prefixes.

key default meaning
trusted_keys [] Ed25519 public keys: base64 strings or %{name: "alice", public: "..."}
audience none environment name every signed statement must carry
allowed_prefixes [] module prefixes a patch may touch. "MyApp" matches MyApp and MyApp.*; a trailing * is a plain string prefix
threshold 1 distinct signers required for a deploy or a rollback
store_dir none persist patches, the replay counter, the revoked set and the audit log
store_fetch none {m, f, a} returning {:ok, [signed_envelope]}, called at boot: the envelopes this node should run, verified and re-applied like stored ones. For nodes without a durable disk; see Ephemeral disks and immutable images
wait_for_old_code 0 ms a deploy waits, before its preflight, for processes that still run the old version of a module it replaces (at most 10 minutes); a caller's --wait-for-old-code overrides it. See Draining long-running work
server none [port: 4747, ip: {127,0,0,1}, tls: [certfile: "...", keyfile: "..."]]
public_urls [] the URLs operators and CI use to reach THIS node (["https://node-a.internal:4747", "https://10.0.0.5:4747"], as written in --targets). Every request signs the address it was sent to; with this set the node refuses a request signed for any other address, so a hostile fleet target cannot relay an operator's signed request to it. Empty: any address is accepted. See The HTTP endpoint
allow_app_restart [] applications that may be restarted in place (the signers must also ask)
retain_state [] supervisor child ids whose state survives a spec change
supervision :auto :report reports child changes instead of applying them
carriers [] modules outside allowed_prefixes whose processes hold your structs and should be struct-migrated too (processes running your own code are found automatically)
hosts [] libraries that host your behaviour, so a deploy changing your module reaches their processes: GenStage and :gen_event (built in), {Host, mod_key}, {Host, mod_key, state_key} or {Host, {M, F}}. See State migration
hooks [] modules implementing Hotcode.Hook
block_on_closure_in_state false true: a closure of a patched module found in the state of a process the deploy touches is a block (:closure_in_state), not a warning. See Troubleshooting
struct_scan [concurrency: 16, suspend_concurrency: 1, timeout_ms: 300, max_processes: 50_000] how a deploy reads states and suspends processes: states read at the same time, suspensions at the same time (1: one after the other), the :sys.get_state timeout per process (a process slower than that counts as a holder and is suspended); max_processes: n refuses in the plan a struct scan that would read more states (:struct_scan_limit) and caps the states read for closures (:infinity removes the cap); only: [MyApp.Session, "MyAppWeb.*"] reads, for a changed struct, only processes whose initial-call module matches. Only processes that answer :sys are read. See Struct scan at scale
plan_new_atoms [per_plan: 20_000, per_boot: 100_000] a plan signed by fewer than threshold keys may create at most per_plan atoms this node does not have yet, and all such plans together at most per_boot until the node restarts; over either, {:too_many_atoms, count, limit}. See Security
table_check [timeout_ms: 60_000, max_rows: 10_000_000] the check of a Hotcode.Table's rows on a copy before loading: a check that does not finish in timeout_ms (an upgrade/2 step that loops) refuses the release, and so does a table with more than max_rows rows, before any row is copied
health_check none {module, function, args} returning :ok/true or {:error, _}, run on each upgraded node
settle 0 ms to wait before the health check
node_timeout 600_000 ms to wait for one node during a rollout
releases [] releases this node's image already contains (built in, not hot-patched). They count as live for --requires and Hotcode.Cluster.applied?/2, next to the live hot patches. See Clusters
expected_nodes [] nodes the applied? gate must hear from; one that does not answer closes it
cluster_cache_ms 1_000 how long Hotcode.Cluster.applied?/2 keeps an answer
convergence [mode: :report, after_ms: 60_000, interval_ms: 10_000, attempts: 3, backoff_ms: 5_000] the cluster-wide version table and its report: mode: :off disables it, :report reports and changes nothing, :converge also lets a reachable node that is behind pull the signed envelopes it lacks from a peer's store_dir and verify and deploy them itself (Converging forward); after_ms is how long a cluster may stay on two releases after a roll before it is reported (and before a lagging node pulls), interval_ms how often every node probes the others, attempts the pulls a node makes before it gives up and alerts, backoff_ms the wait between them (doubling). :auto does all of :converge and also runs the deadman: a release whose SIGNED statement carries auto_rollback (--auto-rollback-after) is undone on every node that has it when a reachable node has not caught up by the signed deadline, decided by one coordinator under the roll lock with a majority of the cluster visible (Deadman rollback); every node that should take part must run :auto, a node in another mode refuses the undo. :spread spreads a release whose signed statement carries a rollout policy from its canaries to every node (Rolling out to a large cluster), and converges forward the others as :converge does
members_backend :local how the version table is kept: :local (announcements and a probe of every node) or :syn (a :syn scope; needs the :syn dependency). Every node of a cluster must use the same. See Hotcode.Cluster.Members.Backend
syn_scope :hotcode the :syn scope of members_backend: :syn
metadata %{} this node's free-form labels, a map or {m, f, a} returning one (%{"region" => "eu-west-1", "tier" => "edge"}). Hotcode gives no key a meaning: a rollout policy picks canaries by a match on it and may group the spread by one key (group_by). See "Node metadata" in Rolling out to a large cluster
canary false true: picked first among the canaries by hotcode push --canary N / --canary-match
canary_check Hotcode.Health.check/0 {m, f, a} sampled on a canary every sample_ms: :ok/true good, false/{:error, _} bad, or a number from 0 to 1
spread [sample_ms: 5_000, jitter_ms: 2_000, backoff_ms: 2_000, settle_ms: 0, tick_ms: 500, pull: true] mode: :spread timing: canary samples, the random wait before a pull, the wait after a busy source or a full cap (and between two pushes of one pusher), the wait before the health check after a pull, how often a node decides; pull: false: this node never fetches and asks to be pushed. See Rolling out to a large cluster
undo_concurrency 8 holders the undo of a halted spread rolls back at the same time (the deadman's undo goes one node after the other)
locked false start with the kill switch engaged
allow_core_overrides [] core modules a signed patch may touch (almost never)
insecure_http false allow plain HTTP off loopback. Do not
unsafe_allow_unsigned false tests only. Logs an error at boot

Commands

task purpose
mix hotcode.gen_key NAME create an Ed25519 key pair (private key 0600, never overwritten)
mix hotcode.build TARGET --out FILE diff your build against the live node and write an unsigned envelope. Options: --restart-app APP (repeatable), --accept-major APP (repeatable), --requires VERSION (repeatable), --force, --ttl-minutes N, --version V, --auto-rollback-after D, the --rollout-* flags and --require-promote (Rolling out to a large cluster), --cacert PEM, --json
mix hotcode.build --manifest FILE --out FILE the same, against a manifest saved at release time instead of a live node (Building without reaching the node)
mix hotcode.manifest --out FILE save the manifest of a build or of an assembled release (--release DIR), for build --manifest
mix hotcode.sign FILE --key K show what it authorizes, ask, add a signature. --yes skips the question
mix hotcode.push FILE TARGET upload. --dry-run plans only; --local limits to the node that answers; --canary N / --canary-match KEY=VALUE to the canaries of a release with a rollout policy; --wait-for-old-code 60s waits for processes on displaced code before refusing
mix hotcode.push FILE --targets LIST the same envelope to each node of a fleet that is not an Erlang cluster: canary, soak, bounded parallelism, health checks, undo on failure (Fleets without distribution)
mix hotcode.deploy TARGET --key K build, sign and push in one step, for single-signer setups
mix hotcode.rollback TARGET --key K signed rollback. For a two-person rollback use --out FILE, mix hotcode.sign, then --file FILE
mix hotcode.status TARGET --key K version, history and whether the node is accepting deploys. --spread: the spread of a release as that node sees the cluster. --targets LIST: each node of a fleet, one line each
mix hotcode.wait TARGET wait for a spread to finish (--done, default) or halt (--halted), --timeout 30m, --interval 5s: exit 0, 5 halted, 6 still going
mix hotcode.resume TARGET --key K the signed resume of a HALTED spread (before its undo started); refused as :undone after it
mix hotcode.promote TARGET --key K the signed promote of a release built with --require-promote (two signers: --out, mix hotcode.sign, --file)
mix hotcode.describe FILE what an envelope authorizes (audience, versions, modules, patch sha256, signatures), without signing or sending; for a manifest, where it comes from and what it lists
mix hotcode.check the Hotcode Credo rules on your code, no configuration needed (Credo rules)
mix hotcode.credo.install add the rules to your .credo.exs
mix hotcode.install with Igniter (mix igniter.install hotcode): the node's configuration, Credo, the rules

Every task that talks to a node takes --json, --cacert PEM, --key FILE or env:NAME, and exits with a code that says what happened: see Deploying from CI. A stand-alone hotcode command does describe, sign, push, rollback, status, wait, promote, resume and gen-key without your project.

TARGET is https://host:4747 (needs --key to sign the request) or a node name with --cookie.

Observability

Audit log

store_dir/audit.log is append-only JSON lines. Each entry has event, node, at and event-specific fields.

event meaning alert?
deployed a patch was applied; includes signers and the version info
rolled_back a patch was undone info
rollback_requested a rollback request arrived over HTTP info
rejected an envelope or stored patch was refused; reason says why yes, in bulk
lockout five rejections in a minute: deploys locked for five minutes yes
failed a deploy was accepted but failed (migration, load, ...) yes
deploy_crashed an exception mid-deploy; code_restored says if the old code is back yes
node_locked the node locked itself (incomplete undo, unrecoverable crash) page someone
persist_failed the code is live but could not be written to store_dir yes
app_restore_degraded an in-place restart lost a held socket yes

Unauthenticated HTTP noise is not written to the file (anyone could flood it); it is logged and emitted as telemetry only.

Telemetry

event measurements metadata
[:hotcode, :deploy] duration_ms version, result (:ok or :error)
[:hotcode, :rollback] duration_ms version, result
[:hotcode, :audit] none everything in the audit entry

Cluster convergence adds [:hotcode, :cluster, :diverged], :converged, :node_down, :cannot_converge, :converge_failed and :auto_rollback, described in Clusters.

# an exported function, not a closure: telemetry detaches a handler whose module a deploy replaced
:telemetry.attach("hotcode-alerts", [:hotcode, :audit], &MyApp.Alerts.handle/4, nil)

defmodule MyApp.Alerts do
  def handle(_event, _measurements, %{event: e} = meta, _config) do
    if e in [:rejected, :lockout, :node_locked], do: page(meta)
  end
end

Hooks

Hotcode.Hook runs your code around a deploy, inside the loader (keep it quick):

defmodule MyApp.HotHooks do
  @behaviour Hotcode.Hook

  @impl true
  def before_deploy(%{changed: changed}) do
    if MyApp.Billing in changed and MyApp.Billing.run_active?(),
      do: {:error, :billing_run_active},
      else: :ok
  end

  @impl true
  def after_deploy(_report), do: MyApp.Config.reload()
end

config :hotcode, hooks: [MyApp.HotHooks]

before_deploy/1 may veto ({:error, reason}), and a before_deploy/1 that raises vetoes too (the safe reading). after_deploy/1, after_rollback/1 and after_app_restart/1 are notifications: if one raises, it is ignored and the deploy stands.

The after_deploy/1 report carries version, changed, new (modules the patch added), removed, processes, migrated, lingering, warnings and supervision; the after_rollback/1 report carries rolled_back, to, modules (what the undo touched) and unloaded (the modules the undone patch had added).

A registry of modules (every module implementing a behaviour, a plugin or connector list) built from Application.spec(app, :modules) misses modules a patch adds: a hot deploy does not change the .app file. Build it from Hotcode.Loader.modules/1 and rebuild it when the module set changes:

defmodule MyApp.Connectors do
  def all do
    modules =
      if Process.whereis(Hotcode.Loader),
        do: Hotcode.Loader.modules(:my_app),
        else: Application.spec(:my_app, :modules)

    for mod <- modules, Code.ensure_loaded?(mod), MyApp.Connector in behaviours(mod), do: mod
  end

  defp behaviours(mod), do: mod.module_info(:attributes) |> Keyword.get_values(:behaviour) |> List.flatten()
end

# in the hook module
@impl true
def after_deploy(%{new: new, removed: removed}) when new != [] or removed != [],
  do: :persistent_term.put(MyApp.Connectors, MyApp.Connectors.all())

def after_deploy(_report), do: :ok

@impl true
def after_rollback(_report), do: :persistent_term.put(MyApp.Connectors, MyApp.Connectors.all())

examples/pulse configures one (lib/pulse/hooks.ex): its before_deploy/1 vetoes every deploy while a maintenance flag file exists ({:error, :maintenance_window}, v8 is refused that way and deployed once the flag is gone), and its after_deploy/1 and after_rollback/1 log what the deploy did to the supervision tree and which application was restarted, and announce the move to the connected clients. Hooks also run when stored patches are re-applied at boot, before your application has started: check that what a hook uses is running.

Draining long-running work

A process that still runs the previous version of a module (a plain spawn loop, a Task in the middle of a long job, a stream, a worker that calls a local function in a loop) makes the next deploy of that module refuse with {:lingering_old_code, %{module => [pid]}}: purging that version would kill it, and Hotcode never kills it. Nothing changes; the refusal names the modules and the processes.

When those processes end by themselves, ask the deploy to wait for them instead of refusing at once:

hotcode push patch.hcp https://app-1:4747 --key env:HOTCODE_KEY --wait-for-old-code 2m

(also mix hotcode.deploy --wait-for-old-code, and the fleet push). Before its preflight, every node the deploy targets verifies the envelope (signatures from threshold trusted keys, audience, expiry, replay counter, module policy; one that does not verify makes no node wait), then re-checks those modules every 250 ms until no process runs their old code, or the time is up (at most 10 minutes); whatever still lingers then is refused as before. The wait happens outside the loader and before the roll lock is taken, so status requests, other rolls and a spread's pulls go on meanwhile. config :hotcode, wait_for_old_code: 60_000 makes it the node's default for every deploy that does not ask for a time itself.

For work that does not end by itself in time, drain it in a before_deploy/1 hook: stop taking new work, wait for what runs, then check the code (Hotcode.Drain). The hook runs inside the loader, before the preflight's own check, and also for the dry run of a roll, so keep the wait bounded.

defmodule MyApp.HotHooks do
  @behaviour Hotcode.Hook

  # Tasks started with Task.Supervisor.start_child(MyApp.JobSup, ...)
  @impl true
  def before_deploy(%{changed: changed, removed: removed}) do
    if Enum.any?(changed ++ removed, &(&1 in [MyApp.Jobs, MyApp.Jobs.Import])) do
      MyApp.Jobs.pause_intake()

      result =
        with :ok <- Hotcode.Drain.await_children(MyApp.JobSup, 120_000),
             do: Hotcode.Drain.wait_for_old_code(changed ++ removed, 10_000)

      # a veto is followed by no after_deploy/1: take work again here
      if result != :ok, do: MyApp.Jobs.resume_intake()
      result
    else
      :ok
    end
  end

  @impl true
  def after_deploy(_report), do: MyApp.Jobs.resume_intake()
end

pause_intake/0 and resume_intake/0 are yours (a flag the code that starts jobs reads). An {:error, _} from the hook vetoes the deploy ({:vetoed_by_hook, hook, reason}) and nothing changes. A deploy that fails after the hook (a health check) also runs no after_deploy/1: after_rollback/1 is the place to take work again in that case.

With Oban, pause the queues whose workers the patch changes, on this node only, and wait until nothing of theirs runs here. Check the function names against your Oban version (Oban.pause_queue/2, Oban.check_queue/2 and Oban.resume_queue/2 with local_only: true exist in Oban 2.x):

def before_deploy(%{changed: changed}) do
  if MyApp.Workers.Export in changed do
    :ok = Oban.pause_queue(queue: :exports, local_only: true)
    wait_idle(:exports, System.monotonic_time(:millisecond) + 120_000)
  else
    :ok
  end
end

defp wait_idle(queue, deadline) do
  cond do
    Oban.check_queue(queue: queue).running == [] ->
      :ok

    System.monotonic_time(:millisecond) > deadline ->
      {:error, {:queue_busy, queue}}

    true ->
      Process.sleep(500)
      wait_idle(queue, deadline)
  end
end

def after_deploy(_report), do: Oban.resume_queue(queue: :exports, local_only: true)

A job that runs for hours is better split into steps than waited for.

Struct scan at scale

When a patch changes a struct, the plan and the deploy look for the processes that hold it: every process whose initial call is a module under allowed_prefixes has its state read with :sys.get_state (no suspension), and those that hold the struct, or do not answer in timeout_ms, are suspended with the processes of the changed modules, migrated, and resumed. The same reads serve the closure check (:closure_in_state). A deploy reads twice (its plan, then the processes to suspend), so its time includes two scans.

Only processes that speak the :sys protocol are read: a gen_server, gen_statem or gen_event loop (a LiveView or a channel runs in one). A Task, an Agent started with a fun or a spawned loop under allowed_prefixes is sent nothing, since it would never answer: the plan lists such processes in one :state_not_read warning. One of them that holds a struct the patch changes keeps the old shape. The test is the process's current stack: a server loop frame in it means :sys; a stack of 8 frames or more (the rest is cut off) or none (hibernating) is read as before. A state larger than 20 000 terms or deeper than 24 levels is not walked to the end: the process counts as a holder and is suspended, as a process that does not answer in time is.

Measured with mix test --only bench test/struct_scan_bench_test.exs on an Apple M5 Pro (18 schedulers), OTP 29, Elixir 1.20. The holders are GenServers whose state holds the struct; "busy" holders handle one 2 ms message after another, so the run queue holds about as many processes as there are holders. "schedulers" is the busy share of all schedulers, dirty ones included, so 50% is the ceiling here; "ticker" is the longest delay a process waiting 1 ms saw.

scenario plan deploy memory during the deploy ticker
20 000 idle holders, 100-element payload, defaults 0.19 s 0.58 s (rollback 0.41 s) +22 MB 2 ms
same, concurrency: 64 0.21 s 2 ms
same, suspend_concurrency: 64 0.71 s (rollback 0.51 s) +60 MB 2 ms
same, only: matching none of them 0.07 s 2 ms
same, max_processes: 1000 (refused, nothing read) 0.07 s 2 ms
500 busy holders, 10 000-element payload, defaults 3.4 s 9.0 s +147 MB 21 ms
same, concurrency: 64, suspend_concurrency: 64 3.4 s 8.2 s +97 MB 10 ms
5 000 busy holders, 10 000-element payload, defaults 334 s not measured 91 ms
same, concurrency: 256 more than 15 minutes, stopped

What the numbers say:

  • Idle processes are cheap: 20 000 reads take a fifth of a second, and a full deploy with sequential suspension well under a second. Before this measurement the scan tested every process against allowed_prefixes by rebuilding the set of core modules each time, which took 1.1 of the 1.3 seconds of the same plan; it is now computed once per scan.
  • On saturated schedulers the cost is the run queue, not the number of reads in flight: each read and each suspension waits for the target to be scheduled, and so do the loader and its read tasks, which wait behind the same busy processes. More concurrency did not help (at 5 000 busy processes it made the plan slower). A process that does not answer in timeout_ms is treated as a holder and suspended, which waits for it again.
  • Parallel suspension saves little: once a process is suspended it only answers system messages, so migration is fast; the time goes into reaching each process the first time.

The settings (config :hotcode, struct_scan: [...]):

  • only: [MyAppWeb.UserSocket, "MyApp.Sessions.*"]: for a struct change, read only processes whose initial-call module matches (module names or allowed_prefixes-style prefixes). The cheapest way to keep tens of thousands of unrelated processes out of the scan. A process whose own module is in the patch is always reached. A holder left out keeps the old struct shape under the new code: list every module whose processes can hold the struct.
  • max_processes: n (default 50 000): the plan refuses (:struct_scan_limit, a block) a struct scan that would read more than n states, before reading any, and reads at most n states of the processes the deploy suspends anyway when looking for closures (:closure_scan_sampled). A deploy on an unexpectedly large node then stops with a reason instead of stalling. A node that really holds more candidate processes narrows them with only: or raises the number (:infinity turns the limit off).
  • concurrency (default 16) and timeout_ms (default 300): reads in flight and the time a process has to answer. Raising either helps only when the node has idle schedulers.
  • suspend_concurrency (default 1, one after the other): suspensions in flight. All or none, as with one at a time.

On a node whose run queue is long (:erlang.statistics(:run_queue) in the thousands), do not deploy a struct change that reaches the busy processes: wait for a quieter moment, narrow it with only:, or ship it with a restart.

Clusters

mix hotcode.deploy against any node rolls across that node and its peers that run Hotcode, one at a time:

node 1: deploy ─▶ settle ─▶ health check ✓ ─▶ node 2: deploy ─▶ settle ─▶ health check ✗
                                                              ╰─▶ undo node 2 and node 1
  • Configure health_check to something that proves the node is serving, not merely alive.
  • settle gives new code time to take traffic before the check runs.
  • A node whose call exceeds node_timeout is reported under needs_attention and is not rolled back blindly: it may still finish and commit. Check it by hand.
  • Every node is asked for a dry run before any node is touched, so a patch one node would refuse never runs on the others, even briefly.
  • One roll at a time: a roll started while another runs returns reason: :roll_in_progress at stage: :plan and touches nothing. Run it again once the first has returned.
  • A failed roll undoes only the patch it applied. A node where another patch is on top by then is left alone and listed under needs_attention.
  • During a rollout the cluster briefly runs two versions. Messages between nodes must be compatible across both, and a format change takes three releases (readers, then writers gated by Hotcode.Cluster.applied?/1 and --requires, then cleanup). See Clusters and mixed versions.
  • --local deploys only to the node that answers, which works as a canary.
  • For hundreds of nodes, let them spread the release themselves: mode: :spread and a signed rollout policy (Rolling out to a large cluster).

Fleets that are not an Erlang cluster

Independent releases behind a load balancer, ECS tasks, Fly machines without clustering: no node knows the others, so the roll above does not exist. The command does it from outside:

hotcode push patch.hcp --targets targets.txt --key env:HOTCODE_KEY \
  --canary 1 --soak 5m --max-parallel 4 --max-failures 0 \
  --health-url "https://{host}/healthz" --json

Every target is surveyed first (status and a dry run; a target already on the release is skipped, so running the same command again resumes), then the canaries are deployed and checked, the soak passes, and the rest follow, a bounded number at a time (group by group of a metadata key with --group-by). Each node verifies the envelope itself, as for a single push, and runs its own health_check. Past --max-failures the push stops and rolls back the nodes it changed with a signed rollback (the same keys, or --rollback-file for a rollback signed in advance by the threshold). There is no Hotcode.Cluster.applied?/1 and no convergence between such nodes: a message format change needs its readers deployed everywhere before any writer. The target list, the flags, the exit codes and recipes for Fly.io, ECS and an SSH tunnel are in Deploying from CI.

Dependency bumps

Bumping a dependency is an ordinary deploy: mix deps.update, mix hotcode.deploy. The build diffs every application in _build, so the changed modules of the dependency are shipped together with your own, and re-consolidated protocols travel with them. Three things decide whether it is allowed:

  1. allowed_prefixes. A dependency's modules are shipped only if their prefix is listed ("Phoenix.LiveView", "Jason"). Otherwise they are reported as not shipped and the node keeps running the old ones. Listing a prefix is the operator saying "this dependency may be hot-loaded"; leave out anything you would rather restart for.

  2. Semantic versioning. The patch records the version of every application it changes modules of (from the .app file), and the node classifies the change against what it runs (Hotcode.Semver):

    change example result
    patch 1.4.3 -> 1.4.4 allowed, reported
    minor 1.4.4 -> 1.5.0 allowed, reported
    pre-release 1.5.0-rc.1 -> 1.5.0-rc.2 allowed with a warning
    major, or 0.x minor 1.5.0 -> 2.0.0, 0.4.9 -> 0.5.0 blocked unless the signers accept it
    downgrade 1.5.0 -> 1.4.2 blocked unless the signers accept it
    not valid semver nightly blocked unless the signers accept it

    Accepting is explicit and signed: mix hotcode.deploy ... --accept-major jason. It is part of the signed statement and shown by mix hotcode.sign, so a second signer sees it and a caller cannot add it later. Semver is the dependency author's promise, not proof: it decides whether to ask, it does not replace reading the changelog.

  3. Structs held in other processes. If the bump changes a struct (yours or a dependency's), every process running code under allowed_prefixes that holds it in its state is migrated too, even though its own module did not change. They are found by looking at their state (nothing is suspended unless it holds the struct). Processes of code outside allowed_prefixes still need carriers.

What a bump cannot change: the .app file of a running application (Application.spec/2 keeps reporting the version the node booted with; Hotcode tracks the deployed version for the next patch and reports it in the manifest), files in priv/, and anything an @on_load or NIF does (see NIFs). A rolling restart brings the node onto the new mix.lock for real.

examples/pulse (v6) bumps phoenix and jason under 16 open Phoenix channels, replacing Phoenix.Channel.Server under them, then rolls the bump back. Its mix.lock is part of every version: resolve dependencies once, not separately on each machine that builds.

Releases

  • Same toolchain. Build deploys with the same OTP and Elixir as the running release; the patch records its builder's versions and the node refuses an OTP mismatch.
  • Same path, ideally. Beams embed source paths in places (?FILE in Erlang dependencies). Deploys do not fail when a dependency differs byte for byte (see Troubleshooting), but building in the same path as the release avoids spurious differences in your own code.
  • After a rolling restart. Patches in store_dir are re-verified and re-applied before your application starts. When you ship a new release that already contains a patch, the stored patch becomes a no-op; when the release has moved past it, it is discarded.

Ephemeral disks and immutable images

A hot patch lives in memory, and in store_dir if there is one. What survives a restart:

the node restarts... store_dir on a durable disk no durable disk no disk, store_fetch
on the same image patches re-verified and re-applied at boot lost: the node runs the image's code re-fetched, re-verified, re-applied at boot
on a new image that contains the patches stored patches are no-ops nothing to do fetched patches are no-ops
on a new image that moved past them discarded (no_longer_fits_this_release) nothing to do discarded, as stored ones

A container replaced by its scheduler (an ECS task after a health failure, a pod rescheduled, a Fly machine without a volume) is "the same image, no durable disk": it comes back on the image's code and nothing tells it that it is behind. Three ways to handle it, from simplest:

  1. Bake each patch into the next image, soon. Merge every hot change to the branch the image is built from, build and roll the image out as usual; until then, accept that a replaced container runs the older code for a while. The new image contains the patch, so the stored or fetched copies become no-ops: drop them from the store and the bucket after that rollout. If later patches are built with --requires, declare in the image the releases it contains, so that a fresh node counts them as live: for example a file written at image build and read in config/runtime.exs:

    config :hotcode, releases: "/app/HOTCODE_RELEASES" |> File.read!() |> String.split()

    (echo "$PATCH_VERSIONS" > /app/HOTCODE_RELEASES in the Dockerfile, with the --version names of the hot patches the image now contains).

  2. Fetch the patches at boot. Upload every signed envelope you push (the same bytes) to a bucket or a shared volume, and give the node a function that returns them:

    config :hotcode, store_fetch: {MyApp.Patches, :fetch, []}
    
    defmodule MyApp.Patches do
      # runs at boot, before your application: start what it needs itself
      def fetch do
        {:ok, _} = Application.ensure_all_started([:inets, :ssl])
        base = System.fetch_env!("HOTCODE_PATCHES_URL")
    
        # `index` lists the envelope files, one per line; their order does not matter
        with {:ok, index} <- get(base <> "/index") do
          {:ok, for(name <- String.split(index), {:ok, bin} <- [get(base <> "/" <> name)], do: bin)}
        end
      end
    
      defp get(url) do
        case :httpc.request(:get, {String.to_charlist(url), []}, [], body_format: :binary) do
          {:ok, {{_, 200, _}, _, body}} -> {:ok, body}
          other -> {:error, other}
        end
      end
    end

    or, for a mounted directory, store_fetch: {Hotcode.Store, :fetch_dir, ["/mnt/patches"]}. Every envelope is verified at boot exactly like a stored one (signatures against the node's trusted_keys, audience, patch hash, module policy, increasing seq, the base fit), so the bucket needs no more trust than store_dir: whoever writes there can withhold or delete patches, not run unsigned code. Remove an envelope from the bucket when you roll it back: a fresh container does not know it was undone. With store_dir also set, fetched envelopes that apply are written there.

  3. Give the node a durable store_dir: a volume (Fly), EFS (ECS), a PersistentVolume (Kubernetes StatefulSet), StateDirectory= (systemd).

A policy of immutable images (no code may run that the image does not contain) rules out hot patches as such: say so to whoever owns the policy rather than working around it.

  • Releasing Hotcode itself. A patch cannot replace Hotcode's own modules (they are refused). Upgrade the library with a normal rolling deploy.

Runbook

A node is locked (node_locked, or accepting: false in status)

The node could not complete an undo or recover from a crash, so code and state may disagree.

  1. Read the audit log and Logger output around the node_locked event.
  2. Inspect the node. mix hotcode.status; check the application's health.
  3. If the node is fine, call Hotcode.unlock/0 on it. If not, restart it: with store_dir set it re-applies verified patches, which is a known state.

deploy_crashed

An exception happened after the deploy started. If code_restored: true the node is back on the old code and consistent; fix the cause (the Logger output has the stacktrace) and retry. If false the node is locked: see above.

Deploys refused after repeated failures (lockout)

Five rejected envelopes in a minute lock deploys for five minutes. Find out who sent them (rejected entries). When resolved, wait, or call Hotcode.unlock/0. Refused plans (POST /plan, which needs one signature), refused signed promotes and refused signed resumes count too, and a locked-out node refuses promotes and resumes as it refuses deploys. A signed rollback still works.

Revoking a signer

Remove their key from trusted_keys and deploy the config. They stop counting at once; stored patches signed only by them stop verifying at the next boot.

Emergency stop

Hotcode.lock() on a node refuses every deploy until Hotcode.unlock().

A deploy needs to be undone now

mix hotcode.rollback TARGET --key K. It needs the same signers as a deploy, and works while the node is in failure lockout (but not while it is manually locked).