Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 9 — Mix, Releases & Running OTP Apps

Chapter 03 gave you daily-driver Mix: new, compile, test, format. This chapter goes one level deeper — how Mix actually orchestrates the compiler you met in Ch 08, how mix release assembles a self-contained OTP release, and how to operate a live node: foreground, daemonized, remoted into, upgraded while running.

Why this matters: everything here has an Erlang analogue — rebar3 profiles ↔ Mix environments, sys.config ↔ runtime.exs, systools + release_handler ↔ mix release plus a hand-driven release_handler. You are learning new names for machinery you already trust.

One difference is worth naming before you need it: the .appup file is yours. rebar3 could generate relups from a callback module; Mix does not, because it cannot know what your processes should do with new state. Ch 09.8 is the chapter section where that bites.

9.1 What Mix Actually Does

Mix is an orchestrator, not a compiler. When you run mix compile, it:

  1. Loads and evaluates mix.exs (it is ordinary Elixir code)
  2. Resolves and fetches dependencies declared in deps/0
  3. Compiles dependencies first, your app last
  4. Tracks per-file changes in manifests so only stale files recompile (the graph Ch 08 §8.5 describes)
  5. Consolidates protocols (Ch 05) so dispatch stops being dynamic — those consolidated/*.beam files in the build tree are the artifact
flowchart TD
    A["mix compile"] --> B["Evaluate mix.exs"]
    B --> C["Resolve deps<br/>(Hex / git / path)"]
    C --> D["Compile dependencies<br/>_build/dev/lib/<dep>/ebin/*.beam"]
    D --> E["Compile your app<br/>.mix/compile.elixir manifests"]
    E --> F["Write your .app<br/>ebin/my_app.app"]
    F --> G["Consolidate protocols<br/>consolidated/*.beam"]
    G --> H["_build/dev/lib/my_app/ebin/*.beam<br/>+ hello.app"]

(The .ez in older diagrams is Distillery’s archive format. Mix does not produce archives — deps are plain directories with ebin/, the same shape you get from rebar3. Ch 08 §8.1 shows the tree this produces.)

Everything lands in _build/<env>/ — the same shape as rebar3’s _build, including the per-profile split you already know.

Taskrebar3 worldMix world
Profiles{profiles, [...]} in rebar.configMix.env() + MIX_ENV
Hooks{pre_hooks, ...}compiler options, custom compilers
Pluginsrebar3 pluginsMix tasks published to Hex
Lockingrebar.lockmix.lock

From Erlang you know: Mix evaluates mix.exs at every invocation — it is a program, not a config file. Anything you can express in Elixir, you can express in your build. That is Ch 06’s metaprogramming paying off in your tooling.

9.2 Environments: MIX_ENV

Three environments, each a separate build universe:

EnvSelected byUsed forConfig loaded
:devdefaulteveryday compile, iex -S mixconfig/config.exs
:testmix test automaticallyExUnit runsconfig/test.exs
:prodMIX_ENV=prod ...releasesconfig/prod.exs + runtime.exs
flowchart LR
    CMD["your command"] --> Q{"MIX_ENV?"}
    Q -->|"unset"| DEV[":dev<br/>_build/dev"]
    Q -->|"mix test"| TST[":test<br/>_build/test"]
    Q -->|"MIX_ENV=prod"| PRD[":prod<br/>_build/prod"]
    DEV --> CFG["config/config.exs"]
    TST --> CFG2["config/test.exs"]
    PRD --> CFG3["config/prod.exs<br/>+ runtime.exs"]

Each environment compiles into its own _build/<env> tree — switching envs never pollutes another build. start_permanent: Mix.env() == :prod in the generated mix.exs is why dev nodes exit when the supervision tree stops but prod nodes treat shutdown as fatal.

MIX_ENV Mechanics Worth Knowing

  • MIX_ENV selects the environment for that command only — no persisted state exists. mix compile && mix release builds the second artifact unless you repeat the prefix on both commands.
  • Dependencies compile per environment: _build/dev/lib/jason and _build/prod/lib/jason are separate artifacts, which is why switching envs recompiles dependencies the first time.
  • Mix.env() is build-time-only — valid in mix.exs, config files, and module-attribute positions, never in code that ships.
  • Dev conveniences gate exactly like rebar3 profiles: check your def project for what each env switches (start_permanent, compiler options, and friends).
$ mix compile                  # populates _build/dev/
$ MIX_ENV=prod mix compile     # populates _build/prod/
$ ls _build                    # isolated build universes
dev  prod

A bare mix release builds _build/**dev**/rel/... — the task does not select :prod for you. Verified on 1.20.4. Always write MIX_ENV=prod mix release. The other common slip compounds it: a Docker layer running plain mix deps.compile before setting MIX_ENV=prod compiles everything twice and busts the cache.

9.3 Custom Tasks and Aliases

Mix tasks are just modules — behaviour + naming convention:

# lib/mix/tasks/hello.greet.ex — file location matters for discoverability
defmodule Mix.Tasks.Hello.Greet do
  @shortdoc "Greets someone from the command line"

  @moduledoc """
  ## Usage

      mix hello.greet Ada
  """

  use Mix.Task

  @impl Mix.Task
  def run(args) do
    case args do
      [name] -> Mix.shell().info("Hello, #{name}!")
      _ -> Mix.raise("expected exactly one argument: mix hello.greet NAME")
    end
  end
end
$ mix hello.greet Ada
Hello, Ada!

$ mix hello.great Ada     # typo → Mix suggests the closest task
** (Mix) The task "hello.great" could not be found. Did you mean "hello.greet"?

$ mix help hello.greet
                                mix hello.greet
There is no documentation for this task

All three outputs are real, which means the @shortdoc in the listing only appears once you also ship a @moduledoc (as above) — mix help reads the moduledoc, mix help listing reads the shortdoc. Worth knowing before you assume your task is invisible for a mysterious reason.

Notes worth adopting immediately:

  • @shortdoc puts the task in the mix help task list; @moduledoc is what mix help <task> prints

  • @impl Mix.Task catches signature mistakes at compile time (Ch 05 habit)

  • Mix.shell().info/1 instead of IO.puts so tests can capture output

  • @requirements ["app.config"] makes a task depend on your application being configured before run/1 fires; use "app.start" if it needs the supervision tree up. This is Mix’s plugin lifecycle: "app.config" runs your task after configuration, "app.start" after boot. A mistyped requirement fails loudly at the task level:

    $ mix n.app
    ** (Mix) The task "nosuchapp.start" could not be found
    

    which is friendlier than the failure mode it replaces — a task that reads Application.get_env/3, gets nil, and misbehaves somewhere unrelated.

Aliases chain existing tasks declaratively inside mix.exs:

defp aliases do
  [
    setup: ["deps.get", "compile"],
    check: ["format --check-formatted", "credo", "test"]
  ]
end

Now mix setup and mix check work like little shell scripts — no plugin needed.

9.4 Configuration: Compile-Time vs Runtime

Elixir splits configuration along the question “when is this value evaluated?” — and getting this right is the single biggest config lesson coming from sys.config:

FileEvaluatedCan call System.get_env?Typical content
config/config.exsduring mix compileyes, but value is frozen into the buildframework defaults
config/prod.exsduring mix compile (prod)same caveatprod overrides
config/runtime.exsevery time the release bootsyes — this is its purposesecrets, hosts, pool sizes
flowchart LR
    subgraph CT["Compile time — frozen into .beam files"]
        CE["config.exs<br/>evaluates once per build"]
        CE --> BEAM["Application env baked in<br/>via compile_env"]
    end
    subgraph RT["Boot time — fresh every start"]
        RE["runtime.exs<br/>evaluates on every boot"]
        RE --> APPENV["Application.put_env<br/>before apps start"]
    end
    BUILD["mix release"] --> CT
    START["bin/app start"] --> RT
# config/runtime.exs — evaluated at VM boot, every boot
import Config

if config_env() == :prod do
  config :hello, Hello.Repo,
    url: System.fetch_env!("DATABASE_URL"),
    pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")

  config :hello, port: String.to_integer(System.get_env("PORT") || "8080")
end

The ! vs non-! choice in that snippet is a policy decision, so know what each buys:

System.get_env("PORT")                       #=> nil when unset
System.fetch_env!("PORT")                    #=> "8080", or raises:
# System.EnvError: could not fetch environment variable "PORT" because it is not set

fetch_env!/1 raising during boot is usually what you want for a value the app cannot run without — it fails at deploy time with a clear message rather than at the first request that needs the setting. Use get_env/2 (with a default) for everything genuinely optional.

Reading values back follows one rule you should burn in:

# Library code — read at RUNTIME so consumers can configure after compiling:
def timeout, do: Application.get_env(:my_lib, :timeout, 5_000)

# Your own application — compile-time read is fine, you control the build:
@port Application.compile_env!(:hello, :port)

A module attribute reading Application.get_env/3 in a library silently freezes the value at compile time — the classic “why is my config ignored” bug. Libraries read lazily; applications may read eagerly.

From Erlang you know: runtime.exs plays the role sys.config played — environment values applied before applications boot. config.exs is the extra convenience layer Erlang never had: defaults resolved at build time so the release ships self-contained.

Tracing One Value Across All Four Layers

Follow pool_size from source to process:

StageWhere writtenEvaluatedValue
Hard-coded defaultin a module functionevaluated on each call10
Build defaultsconfig/config.exsonce per buildpool_size: 10
Env overrideconfig/prod.exsmerged over defaultspool_size: 20
Runtime overrideconfig/runtime.exsevery bootfrom POOL_SIZE

Later stages win. The first three are frozen into the release: Mix evaluates them during assembly and writes the resulting terms into releases/<vsn>/sys.config. Only the last stage runs on the target host — which is why secrets belong exclusively there.

runtime.exs Internals: The Config Provider

runtime.exs is not special-cased by the VM. Mix ships it as a config provider: a module implementing the Config.Provider behaviour, registered per release, executed by the boot script after the VM starts but before applications load. That timing is exactly why it may read env vars or probe network services — and why a failure there prevents boot rather than surfacing mid-request.

Register additional providers for richer sources:

# mix.exs — the releases key inside def project
[
  releases: [
    hello: [
      config_providers: [{MyApp.EnvFileProvider, "/etc/hello/env"}]
    ]
  ]
]
# lib/my_app/env_file_provider.ex — evaluated on the target at boot
defmodule MyApp.EnvFileProvider do
  @behaviour Config.Provider

  @impl true
  def init(path), do: path

  @impl true
  def load(config, path) do
    vars =
      path
      |> File.read!()
      |> String.split("\n", trim: true)
      |> Map.new(fn kv ->
        [k, v] = String.split(kv, "=", parts: 2)
        {k, v}
      end)

    Config.Reader.merge(config,
      hello: [
        port: String.to_integer(vars["PORT"] || "4000"),
        secret_key_base: Map.fetch!(vars, "SECRET_KEY_BASE")
      ]
    )
  end
end

init/1 runs at build time and its return value is serialized into the release; load/2 receives that value on the target and returns the merged configuration. Whatever Config.Reader.merge/2 can express lands in application env before your supervision tree starts.

Evaluation Order and Branching

Config files are scripts evaluated top to bottom: later config calls override earlier keys, import_config splices another file inline at that point, and config_env() branches per environment inside one file:

# config/config.exs — order is semantics:
import Config

config :hello, pool_size: 10          # base value

if config_env() == :test do           # branch inside one file
  config :hello, pool_size: 1
end

import_config "dev.secret.exs"        # spliced HERE — overrides above

config :hello, pool_size: 5           # would override even the secret

Two habits prevent most config confusion: keep config.exs free of machine-specific values (they freeze into every build), and never import_config "runtime.exs" from a build-time file — it would evaluate at assembly time, defeating its purpose entirely.

9.5 How mix release Assembles a Release

One command turns _build/prod into a self-contained, bootable OTP release:

flowchart TD
    A["MIX_ENV=prod mix release"] --> B["Compile all deps + app<br/>in :prod"]
    B --> C["Gather ERTS<br/>(include_erts: true default)"]
    C --> D["Collect each dep as<br/>lib/name-vsn + ebin"]
    D --> E["Render templates<br/>rel/env.sh.eex · rel/vm.args.eex"]
    E --> F["Write boot scripts<br/>releases/vsn/start.boot + .rel"]
    F -->     G["Apply overlays<br/>(rel/overlays/**)"]
    G --> H["Assembled tree<br/>(add the :tar step to also<br/>emit name-vsn.tar.gz)"]

The generated tree — annotated against what rebar3’s release gives you:

_build/prod/rel/hello/
├── bin/
│   └── hello                  ← control script: start/rpc/remote/stop...
│
├── erts-17.0.5/               ← private copy of the VM — no system install needed
│                                 (the number tracks OTP: 15.x = OTP 27,
│                                  16.x = OTP 28, 17.x = OTP 29. Check
│                                  `:erlang.system_info(:otp_release)`.)
├── lib/
│   ├── hello-0.1.0/ebin/      ← your app, exactly an OTP app directory
│   ├── jason-1.4.4/ebin/
│   └── ...                    ← every dependency, vendored
├── releases/
│   ├── COOKIE                 ← distribution cookie (rotate via env var)
│   ├── start_erl.data         ← pairs ERTS version ↔ release version
│   └── 0.1.0/
│       ├── hello.rel          ← the .rel file you know from systools
│       ├── start.boot         ← compiled boot script
│       ├── sys.config         ← runtime.exs result, applied before boot
│       ├── env.sh             ← rendered from rel/env.sh.eex
│       └── vm.args            ← rendered from rel/vm.args.eex
└── tmp/ · tmp/log/            ← daemon scratch space + logs

By default mix release assembles this tree. Add the packaging step once in mix.exs to also emit a deployable tarball:

[releases: [hello: [steps: [:assemble, :tar]]]]
# → _build/prod/hello-0.1.0.tar.gz

Customize the two .eex templates and they are re-rendered on every build:

# rel/vm.args.eex — raw Erlang flags, exactly like a rebar3 vm.args
+P 1000000                       # max processes
+S 4:4                           # scheduler threads : schedulers online
-heart

# rel/env.sh.eex — sourced before the VM starts, set RELEASE_* here
case "$RELEASE_MODE" in
  daemon) export ELIXIR_ERL_OPTIONS="+MMscs 1024" ;;
esac
export RELEASE_DISTRIBUTION=name
export RELEASE_NODE="hello@$(hostname -s)"

Overlays: Shipping Extra Files Verbatim

Create rel/overlays/ and everything inside is copied to the release root on every assemble — the declarative answer to “how do I ship a systemd unit, a migrations folder, or a LICENSE alongside the VM?”:

rel/
├── env.sh.eex · vm.args.eex      # templates, re-rendered each build
└── overlays/
    ├── etc/hello/sysctl.conf     # → <release>/etc/hello/sysctl.conf
    └── bin/migrate.sh            # → <release>/bin/migrate.sh

Overlays apply last, so they can also overwrite generated files (a custom control wrapper, for instance). Because they are plain files, they diff cleanly in review — prefer an overlay over post-editing template output.

Stripping and Reproducibility

By default the release strips BEAM files (strip_beams: true), removing debug-info chunks from shipped artifacts: smaller tarballs, at the price of losing abstract_code reconstruction (Dialyzer against a stripped release, some tracing tools). Keep chunks selectively:

[
  releases: [
    hello: [strip_beams: [keep: ["Docs", "Dbgi"]]]
  ]
]

Keeping only Docs drops Dbgi, and with it abstract_code — which means no dbg call tracing, no Dialyzer PLT against these beams, and no readable disassembly in production. Keeping both costs disk and buys you the ability to debug a running node with the same tooling you use in dev. Strip aggressively only once you have decided you will never need it.

For reproducible archives, SOURCE_DATE_EPOCH pins timestamps: identical inputs plus the same epoch produce identical tarballs, making checksum-based deploy verification meaningful.

Inspecting the Tarball Before It Ships

Five minutes with the archive teaches the boot model better than any diagram:

$ mkdir /tmp/inspect && tar xzf _build/prod/hello-0.1.0.tar.gz -C /tmp/inspect
$ cat /tmp/inspect/releases/start_erl.data
17.0.5 0.1.0                    # ERTS version paired with release version
$ cat /tmp/inspect/releases/0.1.0/hello.rel
{release,{"hello","0.1.0"},
         {erts,"17.0.5"},
         [{kernel,"11.0.3",permanent},
          {stdlib,"8.0.3",permanent},
          {elixir,"1.20.4",permanent},
          {sasl,"4.4",permanent},
          {hello,"0.1.0",permanent},
          {iex,"1.20.4",none},
          {compiler,"10.0.3",permanent},
          {logger,"1.20.4",permanent}]}.
$ cat /tmp/inspect/releases/0.1.0/sys.config
%% coding: utf-8
%% RUNTIME_CONFIG=false
[].

(Real output from mix release on Elixir 1.20.4 / OTP 29. Two things an Erlang reader should notice: elixir appears in the .rel manifest, which is how the boot script knows to start the Elixir application; and sys.config is literally [] until your runtime.exs puts something in it — the RUNTIME_CONFIG=false marker is how Mix distinguishes “no runtime config” from “runtime config that happened to be empty.”)

The .rel file is the manifest you knew from systools: every application, its version, its load type. During assembly Mix feeds it through systools:script2boot to produce start.boot — the instruction sequence erl -boot executes. start_erl.data exists so bin/hello can pair the right private ERTS with the right release version.

9.6 Running the OTP App

The bin/hello script is a front-end over release_handler and plain erl. Every subcommand maps to an operation you have typed by hand before:

CommandWhat happensErlang equivalent
bin/hello startboot in foregrounderl -boot start
bin/hello start_iexboot in foreground with IEx attached-remsh to self
bin/hello daemonbackground boot via run_erl, logs to tmp/log/run_erl
bin/hello daemon_iexdaemon + IEx prompt on the tty—
bin/hello stopgraceful shutdowninit:stop()
bin/hello restartstop + start in one callinit:restart()
bin/hello rpc "EXPR"evaluate an expression on the running nodeerl -remsh + call
bin/hello remotefull remote IEx shell into the nodeerl -remsh node
bin/hello eval "EXPR"boot a throwaway VM (no apps started), evaluate, exiterl -eval
bin/hello pidprint the running node’s OS PIDcat pipe/$FP
bin/hello versionprint release name/version about to boot—

That list is the complete set, printed by bin/hello with no arguments — the one command worth typing first. Note what is absent: there is no ping (that was Distillery’s, and :net_adm.ping/1 from rpc is the equivalent) and no console; the interactive-shell commands are start_iex (boots a fresh node) and remote (attaches to one already running).

There is deliberately no upgrade command — hot upgrades need your .appup knowledge (§9.8), so Mix leaves driving release_handler to you.

MIX_ENV is not implied by the task. A bare mix release builds _build/dev/rel/...; only MIX_ENV=prod mix release produces the prod tree. Write the prefix every time — this is the single most common reason a release behaves differently than expected, because dev and prod compile different config/*.exs files and different dependency sets.

Environment variables steer behavior without editing files:

RELEASE_DISTRIBUTION=sname         # default: short names, same host
RELEASE_DISTRIBUTION=name          # longnames — required across hosts / for IPs
RELEASE_NODE=myapp@host1           # node identity when DISTRIBUTION=name
RELEASE_COOKIE=secret-from-vault   # overrides releases/COOKIE
RELEASE_TMP=/mnt/ramdisk           # where pipes/logs/tmp go
RELEASE_MODE=interactive           # see §9.6's embedded-vs-interactive note

All of these are read by bin/hello itself, not by your application — the control script is a readable shell file, so grep RELEASE_ bin/hello is a legitimate debugging move. RELEASE_COOKIE is worth internalizing: line 29 of the script is RELEASE_COOKIE="${RELEASE_COOKIE:-"$(cat "$RELEASE_ROOT/releases/COOKIE")"}", so the generated cookie file is a default, and setting the env var is how you supply a real secret instead.

Boot sequence, end to end:

flowchart TD
    A["bin/hello start"] --> B["source env.sh<br/>(releases/0.1.0)"]
    B --> C["exec erl -boot releases/0.1.0/start"]
    C --> D["kernel loads apps in .rel order"]
    D --> E["runtime.exs evaluated<br/>Application.put_env"]
    E --> F["each app's mod:start/2 runs"]
    F --> G["your supervision tree is up<br/>node is serving"]

Two operational habits from day one:

# Inspect a live daemon without attaching:
bin/hello rpc "Hello.Repo.aggregate(Hello.Accounts.User, :count)"

# Observer is a GUI: :observer.start() run via rpc opens it on the *server*,
# which on a headless host has no display. Instead, run observer locally and
# point it at the remote node:
#   bin/hello remote   # then, in that shell:
#   :observer.start()   # or start observer on your workstation and Node.connect/1

# The eval variant boots a THROWAWAY node — safe for migrations/cron:
bin/hello eval "Hello.Release.migrate()"

From Erlang you know: rpc/remote/eval are the -remsh and -eval workflows you already run — Mix just wraps the plumbing (cookie, node name, boot flags) so the incantation is one word.

vm.args and ERL_FLAGS: Tuning the Emulator

vm.args.eex accepts any erl flag — the ones you have typed for years. Start conservative; every line below is documented in erl(1):

### Capacity — raise before load tests hit defaults:
+P 2000000                       # max processes
+Q 100000                        # max ports

### Scheduler pressure — stop burning CPU on busy-wait while idle:
+sbwt none                       # none | very_short | short | medium | long | very_long
+sbwtdcpu none                   # dirty CPU schedulers, same scale
+sbwtdio none                    # dirty IO schedulers

### Distribution over IPv6-only networks:
-proto_dist inet6_tcp

(Old-timers’ +K true is gone from this list: kernel-poll is always on where available on modern OTP, and the flag is a no-op.)

Flags also arrive through the environment, which beats rebuilding images for experiments: ERL_FLAGS="+sbwt none" bin/hello console. Prefer vm.args.eex for deliberate, versioned settings; ERL_FLAGS for temporary probes.

RELEASE_MODE (default embedded) selects the code-loading mode from Ch 08: embedded preloads modules at boot for faster, more predictable startup; interactive loads on demand. Measure with your own workload — the default suits the overwhelmingly common case.

9.7 Deploying Releases

A release directory is self-contained: copy it, run it. The VM travels inside (erts-*), so targets need no Erlang installed — same OS family and architecture is the only constraint.

Copy-the-folder (works everywhere):

MIX_ENV=prod mix release
rsync -a _build/prod/rel/hello/ host:/srv/hello/
ssh host '/srv/hello/bin/hello daemon'

Docker multi-stage (the common container shape):

# ---- build stage ----
# Pin a digest in production; the floating tag is fine for a guide.
FROM hexpm/elixir:1.20-erlang-28-debian-bookworm-slim AS build
RUN apt-get update -y && apt-get install -y build-essential git && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY mix.exs mix.lock ./
RUN mix local.rebar --force && mix local.hex --force
RUN MIX_ENV=prod mix deps.get
COPY config config
# deps.compile is here for layer caching, not because mix release needs it —
# mix release compiles the whole project anyway. The MIX_ENV prefix on every
# step is the point: deps.fetched/compiled per-env, and the deps.compile layer
# only invalidates when mix.lock or a dep's source changes.
RUN MIX_ENV=prod mix deps.compile
COPY lib lib
RUN MIX_ENV=prod mix release

# ---- runtime stage: no Elixir, no Hex, no build tools ----
FROM debian:bookworm-slim
RUN apt-get update -y && apt-get install -y libssl3 && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=build /app/_build/prod/rel/hello ./
ENV RELEASE_DISTRIBUTION=none PORT=8080
CMD ["/app/bin/hello", "start"]

Secrets come from the environment at boot through runtime.exs — the image contains no credentials, matching twelve-factor expectations.

A Pre-Flight Checklist

Before the first real deploy, retire each assumption in the chain:

tar tzf hello-0.1.0.tar.gz | head         # tarball exists and is shaped
file rel/hello/erts-*/bin/erlexec          # ERTS matches the target arch
grep -r SECRET lib config rel              # nothing baked in
RELEASE_DISTRIBUTION=name bin/hello daemon && sleep 2 && bin/hello ping
bin/hello rpc ":erlang.system_info(:otp_release)"

Packaging, architecture, hygiene, boot, and finally that the running node is the OTP release you built against — five commands, five retired assumptions.

9.8 Hot Code Upgrades — The Deep Dive

The capability Erlang made famous survives intact in Mix releases: installing a new version without stopping the node. Be precise about what ships and what doesn’t: Elixir’s release script has no upgrade command — but the full OTP machinery underneath (release_handler, systools) is present in every release, and Mix automates everything around it: packaging both versions, boot scripts, and the rpc channel you drive it through. Only relup generation and state-migration callbacks are left to you, because only you know how your processes should migrate state.

One-time release configuration

# mix.exs — the releases key inside def project
[
  releases: [
    hello: [
      applications: [sasl: :permanent],   # release_handler lives in SASL
      steps: [:assemble, :tar]            # emit deployable tarballs
    ]
  ]
]

The four moving parts

PieceRoleWho provides it
.appup fileper-app instructions: which modules to load, which processes to restart, which callback migrates stateyou write it
relup scriptordered, global instruction list across all appssystools:make_relup derives it from the two .rel + .appup files
upgrade driverdrives release_handler on the targetyou do — there is no bin/app upgrade; see below
state migrationcode_change/3 callbacks, or supervised child restartsyou write it

Walkthrough: hello 0.1.0 → 0.2.0, live

Suppose Hello.Counter (a GenServer holding {integer(), pid-history}) gains a :reason field. Version 0.1.0 is already running as a daemon.

1. Freeze the currently-deployed artifact:

MIX_ENV=prod mix release
cp _build/prod/hello-0.1.0.tar.gz /tmp/v1.tar.gz

2. Make the code change, then declare the migration in priv/appups/hello.appup — plain Erlang terms, evaluated by systools:

%% priv/appups/hello.appup — instructions for upgrading hello itself
{"0.2.0",
  [{"0.1.0",
    %% High-level instructions. Valid forms are:
    %%   {load_module, Mod}
    %%   {load_module, Mod, DepMods}
    %%   {load_module, Mod, PrePurge, PostPurge, DepMods}   %% 5-tuple
    %%   {update, Mod, ModType}          ModType = soft | {advanced, Extra}
    %%   {update, Mod, ModType, Timeout}
    %%   {update, Mod, supervisor, ...}
    %%   {apply, {M,F,A}, PrePurge, PostPurge, DepMods}
    %% Note there is no 3-tuple {load_module, Mod, Purge}: the third slot is
    %% a dependency-module *list*, and purge strategies only appear in the
    %% 5-tuple form.
    [ {load_module, 'Elixir.Hello.Counter'},
      {update, 'Elixir.Hello.Counter', {advanced, []}} ]}],
  [{"0.1.0", []}]   %% downgrade: no special instructions — modules are
                    %% loaded/purged in reverse; state migrations rarely
                    %% reverse cleanly, so decide explicitly
}.

To purge aggressively, use the 5-tuple explicitly:

{load_module, 'Elixir.Hello.Counter', brutal_purge, brutal_purge, []}

What those instructions mean:

  • {load_module, Mod} — load the new code for a module whose signatures did not change
  • {update, Mod, {advanced, Extra}} — load new code and tell every process running Mod as a behaviour to call its Mod:code_change(OldVsn, State, Extra) callback — your state migration hook
  • soft_purge waits until no process still runs the old code; brutal_purge kills stragglers — choose honestly per module

3. Implement the migration hook on the GenServer:

defmodule Hello.Counter do
  use GenServer
  # ... start_link/handle_call as before ...

  @doc "Called by release_handler mid-upgrade because of the {advanced, Extra}"
  @impl true
  def code_change(_old_vsn, count, _extra) when is_integer(count) do
    {:ok, %{value: count, reason: :legacy_import}}   # old state → new shape
  end
end

4. Bump version in mix.exs to “0.2.0”, place the .appup where systools will find it, and build:

MIX_ENV=prod mix compile
cp priv/appups/hello.appup _build/prod/lib/hello/ebin/
MIX_ENV=prod mix release

(In practice this becomes a tiny script or alias — the point is: the .appup must exist as hello.appup inside lib/hello-0.2.0/ebin/ of the new release.)

5. Derive the relup with the OTP tools, using both releases:

mkdir -p /tmp/upg/hello/{0.1.0,0.2.0}
cd /tmp/upg
tar xzf /tmp/v1.tar.gz -C hello/0.1.0
tar xzf <repo>/_build/prod/hello-0.2.0.tar.gz -C hello/0.2.0

erl -noshell -eval '
  systools:make_relup("hello-0.2.0", ["hello-0.1.0"], [],
    [{path, ["hello/0.2.0/releases/0.2.0",
             "hello/0.1.0/releases/0.1.0",
             "hello/0.2.0/lib/*/ebin",
             "hello/0.1.0/lib/*/ebin"]}]),
  halt().'
# → writes ./hello-0.2.0.relup
#
# Name gotcha: Name and UpFrom are *release file basenames*, not versions.
# systools looks for <Name>.rel; for a Mix release those are
# hello-0.2.0.rel and hello-0.1.0.rel under releases/<vsn>/. Adjust to your
# own releases/*/*.rel layout.

cp hello-0.2.0.relup hello/0.2.0/releases/0.2.0/relup
(cd hello/0.2.0 && tar czf /tmp/hello-0.2.0-upgrade.tar.gz .)

6. Install it on the live node by driving release_handler through the rpc channel — three calls, exactly the classic sequence:

cp /tmp/hello-0.2.0-upgrade.tar.gz \
   _build/prod/rel/hello/releases/hello_0.2.0.tar.gz   # where release_handler looks

# Erlang's release_handler wants charlists (string()), not Elixir binaries —
# the ~c sigil keeps it a list. Plain "..." here is a badarg.
bin/hello rpc ':ok = elem(:release_handler.unpack_release(~c"hello_0.2.0"), 0)'
bin/hello rpc '{:ok, _old_vsn, _} = :release_handler.install_release(~c"0.2.0")'
bin/hello rpc ':ok = :release_handler.make_permanent(~c"0.2.0")'

bin/hello rpc "Hello.Counter.value()"    # new code answering on the SAME node

Under the hood release_handler unpacked the tarball into releases/, executed the relup instructions (suspending processes, swapping code, running your code_change/3), and switched the running version — identical to the classic install_release flow you know from LYSE. One safety net to appreciate: if the node crashes between install and make_permanent, boot falls back to 0.1.0 automatically. Permanence is your explicit, deliberate act.

Honest guidance

flowchart LR
    CHANGE["What changed between versions?"] --> M1["Module body only,<br/>same signatures"]
    CHANGE --> M2["Process state shape<br/>changed"]
    CHANGE --> M3["Supervision structure,<br/>deps, or boot changed"]
    M1 --> W1["{load_module, M}<br/>zero downtime"]
    M2 --> W2["{update, M, {advanced, X}}<br/>code_change/3 runs"]
    M3 --> W3["{update, M, supervisor}<br/>{restart_application, App}<br/>or restart_new_emulator"]
  • Most teams today ship immutable images and restart. Hot upgrades remain genuinely valuable for: telecom-grade uptime, edge devices (Nerves) where downtime costs physical access, and fleets too large to bounce at once.
  • The discipline cost is real: every released version’s tarball must be kept, appups maintained per transition, and state migrations tested. Budget for it explicitly or don’t promise it.
  • Escape hatch: restart_new_emulator in the relup upgrades by rebooting the emulator under release_handler’s control — warm restart semantics with none of the per-module bookkeeping.

Suspend → Swap → Resume: The Minute Inside {update, advanced}

Worth knowing precisely what happens between your install_release call and the moment new code answers — each step is observable and each can hang:

sequenceDiagram
    participant RH as release_handler
    participant P as GenServer running Mod
    participant SYS as sys / proc_lib
    RH->>RH: load_object_code + load (new beam ready)
    RH->>P: sys:suspend(P)
    Note over P: non-system messages queue up<br/>process keeps its state
    RH->>SYS: change_code(P, Mod, OldVsn, Extra)
    SYS->>P: Mod:code_change(OldVsn, State, Extra)
    P->>SYS: {:ok, NewState}
    RH->>P: sys:resume(P)
    Note over P: resumes the loop on NEW code<br/>old incarnation now unused

Three consequences practitioners hit:

  1. Suspension is cooperative — the process must reach its receive loop for system messages. A process stuck in a long computation delays the whole relup; watch process states while installing.
  2. Unsuspended processes keep old code — anything not mentioned in the relup runs the old incarnation until its next fully qualified call. That two-version window is why soft_purge exists.
  3. code_change must be total — raising there crashes the process into its supervisor mid-upgrade. Validate old state defensively and fall back to sane defaults rather than letting it throw.

An Appup Instruction Field Guide

The appup cookbook (linked below) lists them all; these cover daily practice:

InstructionEffectTypical trigger
{load_module, M}swap body, no callbackspure functions changed
{load_module, M, PrePurge, PostPurge, DepMods}swap with explicit purge + dependentsas above, needs stragglers killed
{update, M, {advanced, X}}swap; code_change/3 runsstate shape changed
{update, M, supervisor}swap; supervisor children restartedchild specs changed
{restart_application, App}restart a whole OTP applicationapp-level config changed
{apply, {M, F, A}, PrePurge, PostPurge, DepMods}call M:F(A) at that pointETS migration, cleanup
restart_new_emulatorreboot under the new ERTSNIF ABI changed

Note there is no {restart, [M]} high-level instruction. Restarting a module’s processes is expressed as {update, M, supervisor}, and restarting a whole application as {restart_application, App}.

Downgrade entries mirror upgrades; if you provide none, make_relup derives the reverse from symmetric instructions automatically — but state migrations rarely reverse cleanly, so decide explicitly.

Practice Loops That Keep Relups Honest

  • Script relup derivation and installation end to end — a relup you have never executed is a rumor, not a capability.
  • Run the full install against production-shaped data in CI; assert on migrated state, not just exit codes.
  • Keep every released tarball addressable by version; install_release needs the previous release present.
  • Rehearse failure: interrupt between unpack and permanent, confirm boot rolls back, then clean the half-installed version out of releases/.

From Erlang you know: this whole section is systools:make_relup, release_handler:unpack/install_release, and .appup semantics you may have lived through before. Mix changes the packaging and the wrapper script; the upgrade engine is the same battle-tested OTP machinery.

9.9 Step-by-Step Exercise

  1. mix new opsbox --sup; add @max_workers module attribute and a supervised GenServer that stores the boot timestamp.
  2. Write mix opsbox.snapshot printing the stored timestamp (@requirements ["app.start"]).
  3. Move :port and :greeting into config/runtime.exs, read from env vars with defaults; prove they change per boot without rebuilding.
  4. MIX_ENV=prod mix release; run daemon, then rpc a snapshot, then stop. Confirm tmp/log/ captured the run.
  5. Bonus (the §9.8 muscle memory): bump to 0.2.0 adding one field to the GenServer state; produce the .appup, derive the relup, and install it into the still-running 0.1.0 daemon.

Checkpoint

  1. Which config file may safely call System.fetch_env!/1, and when is it evaluated?
  2. Why must libraries avoid reading app env in module attributes?
  3. What does bin/hello eval do differently from bin/hello rpc?
  4. Which piece of a hot upgrade does Mix not generate, and why?
  5. What is the difference between soft_purge and brutal_purge?
Answers
  1. config/runtime.exs — evaluated at every VM boot, before applications start, so values come fresh from the environment.
  2. Module attributes freeze the value at the library’s compile time; consumers configuring afterwards see stale values. Read lazily via Application.get_env/3 instead.
  3. rpc connects to an already-running node and evaluates there; eval boots a temporary throwaway node, evaluates, and exits — safe for migrations and cron-style jobs.
  4. The relup script (and the .appup inputs to it) — only you know how your processes should migrate state; systools:make_relup derives the script from your appup plus the two .rel files. Mix also ships no upgrade wrapper command: you drive release_handler via rpc.
  5. soft_purge delays the instruction until no process still executes the old code; brutal_purge kills any remaining old-code holders. Soft is safer, brutal always proceeds.

Explore More

Next: Chapter 10 — Phoenix & LiveView