Replacing processes without a restart
On this page
- The holder
- What can be handed off
Hotcode.Swapterminate/2of a swapped process: checkswapping?/0- Supervision reconciliation
- When others call the process you swap
- Add the child first, then use it
- In-place application restart
- It needs two opt-ins
- What survives and what does not
- Dynamic children
- NIFs: ship a new module beside the old one
- Replacing a NIF in place: in its own application
- WebSockets and Bandit
- If it goes wrong
- Between start and restore
- Recommendation
In-place upgrade (code_change/3) cannot do everything. A child spec that changed, a process
whose init/1 changed, an Application.start/2 that now starts something new: these need a
new process, and a restart normally loses state and closes every socket the old process
owned.
This guide covers the mechanisms that make those changes without dropping connections:
the holder, swap, supervision reconciliation, and in-place application
restart. The test suite exercises each of them (test/handoff_test.exs, test/app_swap_test.exs),
and examples/pulse shows them under load, watched from outside: v8 adds a supervisor child,
v9 uses it and replaces the process that owns four TCP connections through the holder, v10
restarts a second OTP application in place.
The holder
Hotcode.Holder is a small, stable process that never runs deployed code, so it is never
itself replaced. It keeps a process's state and sockets while a replacement starts:
old process ──extract──▶ Holder ◀──attach── new process (fresh init, new code)
A socket survives because it is only ever owned by a live process. Ownership moves old process → holder → new process; the kernel keeps buffering bytes in between, and messages that had already reached the old mailbox travel with the socket and are replayed to the new owner in order. Verified with 300 pipelined requests in flight during a swap: none lost, none repeated, order preserved.
Entries expire (30 s once claimable) and close their sockets, so a failed handoff cannot leak connections.
What can be handed off
Hotcode.Handoff.unsafe/2 checks a process before anything is touched, and refuses:
| reason | why |
|---|---|
{:linked_pids, _} |
the state points at processes linked to the old one; they die with it |
{:foreign_ports, _} / {:unsupported_ports, _} |
ports the holder cannot move (files, external programs) |
{:listening_sockets, _} |
the replacement's own init/1 must bind the port; handing it the old state would leave it holding a closed listener |
{:socket_backend_sockets, _} |
sockets of the :socket inet backend are not ports, so they cannot be handed over and would silently close |
The check does not prove a handoff safe: a state can still reference an ETS table or a monitor owned by the old process. Handoff is therefore opt-in for ordinary use (see below).
Hotcode.Swap
Swap.child/3 replaces one supervised child with a fresh process from the current code,
carrying its state and sockets:
{:ok, new_pid} = Hotcode.Swap.child(supervisor, :greeter)
The supervisor sees an ordinary terminate and restart, so restart intensity is not consumed.
It works for static children only; DynamicSupervisor and :temporary children cannot be
recreated from outside. On {:error, {:unsafe_state, reasons}} nothing was touched.
terminate/2 of a swapped process: check swapping?/0
The old process is stopped with the supervisor's own :shutdown, so a worker that traps exits
runs its terminate/2, after its sockets were handed to the holder. Any process can close a
port, owner or not, so a terminate/2 that closes its socket closes the connection the
replacement is about to get. Hotcode.Swap.swapping?/0 is true inside a process that is
being swapped (and false on any other shutdown): skip what was handed over, keep the rest.
def terminate(_reason, state) do
# the socket moved to the new process: closing it would drop the client
unless Hotcode.Swap.swapping?(), do: :gen_tcp.close(state.socket)
flush_metrics(state)
end
The signal is not carried in the exit reason on purpose: a reason such as
{:shutdown, :hotcode_swap} would reach the supervisor as an unexpected exit, and it would
restart a :permanent child itself and count that against restart intensity.
A terminate/2 that ignores the signal is detected after the fact: Swap.child/3 returns
{:error, {:closed_in_terminate, ports}} and logs an error naming swapping?/0. The child is
running again, with the fresh state of its init/1, but that client connection is lost.
swapping?/0 is only set by Hotcode.Swap. An in-place application restart
(Hotcode.AppSwap, below) does not set it, because it does not need to: the workers whose
state and sockets it hands over are killed, so their terminate/2 does not run at all (nothing
in it runs, the flush in the example above included), and the workers it does not hand over
stop normally and should close what they own, which they do with swapping?/0 false.
Supervision reconciliation
A supervisor's init/1 can change in a deploy. :sys.change_code refreshes its child specs
but starts and stops nothing. Hotcode does the rest, after the supervisor has resumed:
| change | what happens |
|---|---|
| a child added | started |
| a child removed | terminated and deleted |
| a child spec changed | restarted so the new spec takes effect; state is lost unless the child is listed in retain_state, in which case it is swapped through the holder |
config :hotcode,
supervision: :auto, # :report only reports instead of applying
retain_state: [:cache] # child ids whose state survives a spec change
Removals need the supervisor's init arguments, read from its state; if that layout is not what
is expected, removals are skipped and reported instead of guessed. Rollback reconciles the
tree back: the supervisor re-reads its child specs once the old code is loaded again, so a
child the deploy added is removed and a changed spec is changed back (with retain_state,
through the holder again).
When others call the process you swap
A swap replaces a process. Messages already waiting in the old mailbox are re-sent to the new one, but nothing sent by name afterwards is buffered.
A call waiting in the old mailbox is run by the new process, yet its caller does not get the
answer: GenServer.call monitors the pid it called, the old one, which exits with :shutdown
before the new one starts. The caller exits with {:shutdown, {GenServer, :call, _}} every
time, and the new process's reply is dropped. The request has run all the same, so a caller
that retries on that exit runs it twice.
If a registered process is swapped:
- from the moment the old mailbox is read until the new process registers the name (which
GenServer.start_link/3does beforeinit/1; typically well under a millisecond, plus the oldterminate/2), aGenServer.cast/2by name is dropped silently,send/2to the name raisesArgumentError, and a call exits (:shutdownif it reached the old process after its mailbox was read,:noproconce the name is free; neither call is run); - between that registration and the swap suspending the new process, a call can be answered
with the fresh state of the new
init/1, before the old state is installed.
A buffer cannot close this soundly: the child's own start function registers the name, so a
proxy holding it would make that start fail with {:already_started, proxy}, and a forwarding
proxy breaks GenServer.call (the caller monitors the proxy) and per-sender message order.
A plain GenServer.call/2 caught in that window in a connection process would crash that
process and drop its socket. Callers of a process that may be swapped (or whose child spec you
may change) should tolerate the gap, typically with a short bounded retry in the client API.
Retry only requests that are safe to run twice: after a :shutdown exit the request may have
been run by the new process. A read is safe; for a write, make it set a value rather than add
to one, or give each request an id the server remembers and ignores when it sees it again.
# a read: running it twice is harmless
def count(tries \\ 50) do
GenServer.call(__MODULE__, :count)
catch
:exit, _ when tries > 0 ->
Process.sleep(5)
count(tries - 1)
end
This was found by an outside observer in an earlier example (ten_versions, now in the git
history): without the retry, the deploy that swapped the Ticker dropped the connection.
Add the child first, then use it
Children are added or restarted after the suspended processes resume. Code in the same
deploy that calls a new child can therefore run before that child exists. Treat it like a
database migration: expand, then contract. Ship the child in one deploy, and the code that
uses it in the next. (examples/pulse does this: v8 adds Pulse.Census to the tree,
v9 is the first release whose ticker calls it.)
Why retain_state is opt-in: a changed child spec usually means a changed argument, and
restoring old state over what the new init/1 built can overwrite exactly the thing you
changed it to get.
In-place application restart
Some changes are applied only when an application starts: a new Application.start/2, a
replaced module with @on_load, a replaced NIF. Hotcode normally blocks these. (A new
NIF module is not one of them: see NIFs, which
needs no restart at all.) Instead of a node restart,
Hotcode can restart that one application inside the VM, with its workers' state and
sockets held in the holder meanwhile (Hotcode.AppSwap):
stash: for every static worker in the app's tree, hand state and sockets to the holder
freeze: suspend the app's supervisors so killing a worker does not restart it
kill: the stashed workers, so a terminate/2 cannot close a socket that was handed away
(their terminate/2 does not run; Hotcode.Swap.swapping?/0 is not set)
stop: Application.stop(app)
load: the new code
start: Application.ensure_all_started(app, original_restart_type): the NEW start/2
restore: every worker found at the same path gets its state (migrated) and sockets back
It needs two opt-ins
Restarting an application interrupts it, so the signers and the operator both have to allow it:
mix hotcode.build ... --restart-app my_app # the signers ask, inside the signed statement
config :hotcode, allow_app_restart: [:my_app] # the node's operator allows it
Neither alone is enough. Core apps, Hotcode itself, and any app another running application depends on or includes are never restartable.
What survives and what does not
| in the application | across the restart |
|---|---|
static gen_* worker with safe state |
state and sockets kept |
| worker that owns a listening socket | restarted fresh (the new start/2 binds the port); listed under lost |
Agent / Task child, plain process |
lost, listed under lost |
| state holding linked pids or foreign ports | lost, listed under lost |
DynamicSupervisor children |
held and offered to your hook (below) |
:ssl connections |
lost (they are processes, not ports) |
Dynamic children
A DynamicSupervisor's children cannot be recreated from outside, so Hotcode holds their
state and sockets and offers them to c:Hotcode.Hook.after_app_restart/1, which can start
replacements and give each its state with Hotcode.Handoff.restore/3:
def after_app_restart(%{app: :my_app, keys: keys}) do
for key <- keys do
{:ok, pid} = DynamicSupervisor.start_child(MyApp.Sessions, MyApp.Session.child_spec(nil))
:sys.suspend(pid)
:ok = Hotcode.Handoff.restore(pid, key)
:sys.resume(pid)
end
end
Anything unclaimed expires after 30 seconds and its sockets are closed.
NIFs: ship a new module beside the old one
A loaded NIF library cannot be replaced under running processes, and Rustler NIFs cannot be
upgraded in place at all: loading a library over a module that already has one returns
{:error, {:upgrade, 'Upgrade not supported by this NIF library.'}}. So do not upgrade it.
Ship the new version as a new module next to the old one and change only the facade that
callers use (examples/pulse, v3, with a Rust crate per version):
defmodule Pulse.Native do # the facade: the only module callers know
@nif Pulse.Native.V1 # v3 of the release changes this line to V2
def checksum(binary) when is_binary(binary), do: @nif.checksum(binary)
end
- A patch adds
Pulse.Native.V2(its crate innative/crates/v2, its library embedded in the beam, see below) and changesNative. Hotcode loads the new NIF module first and the facade in the atomic batch, so the facade never calls a module that is not there yet. A new@on_load/ NIF module is only a warning: nothing is replaced, so nothing can be killed. - Nothing restarts. No socket, no process, no application is touched.
- If the new library fails to load (a missing file, a wrong ABI) the deploy is refused and the new module is unloaded again; the old one never stopped working.
- Rollback restores the facade and unloads
V2. A later release can deleteV1once nothing needs it. - Ship the library with the patch. A patch carries only beams, so embed the shared library
in the module's beam (
@so File.read!(...), an@external_resource, and an@on_loadthat writes it to a fresh temporary file and calls:erlang.load_nif/2). - Build it reproducibly. The beam embeds the library's bytes and a linker stamps a fresh UUID into every build, so two builds of the same crate differ. If the node and your build machine each compile it, every deploy looks like a NIF change. Build once and reuse the artifact (the example caches each crate by the hash of its source).
Replacing a NIF in place: in its own application
When you cannot go side by side (a C library with an upgrade callback, say) the pattern is
an application restart (an earlier example, live_edge, now in the git history, demonstrated it
with a C NIF):
- Put the NIF in its own OTP application, separate from the one that holds your sockets,
and start it from the main application (
Application.ensure_all_started/1). List it in your dependencies withruntime: falseso the main application does not depend on it (an application that another running application depends on is never restarted in place). - Ship the native code with the patch. A patch carries only beams, so embed the shared
library in the module's beam (
@so File.read!(...)plus@on_loadthat writes it to a fresh temporary file and calls:erlang.load_nif/2), or arrange for the new library to be on the node's disk by other means. Give the C library anupgradecallback: loading a new version over a loaded one fails without it (Rustler offers none). - Ask for the restart, twice.
mix hotcode.build ... --restart-app native(the signers) andallow_app_restart: [:native](the operator). Hotcode stops:native, loads the new code, starts it again and restores its workers' state. Sockets in other applications are untouched. - Build the library reproducibly. The beam embeds the library's bytes, and a linker stamps a fresh UUID into every build, so two builds of the same C file differ. If the node and your build machine each compile it, every deploy looks like a NIF change and is blocked. Build once and reuse the artifact.
- Make callers tolerate the restart window. For a few milliseconds the native application's processes do not exist. Use casts for fire-and-forget calls and a short bounded retry for calls that need an answer.
WebSockets and Bandit
Bandit runs every WebSocket connection in its own process (Bandit.DelegatingHandler) holding
your handler state, and Bandit is outside allowed_prefixes, so it is not found by itself.
Add it to carriers and Hotcode will suspend those processes and migrate
your structs inside them on every deploy, so a struct shared by TCP sessions and WebSocket
handlers changes in both at once:
config :hotcode, carriers: [Bandit.DelegatingHandler]
(A LiveView or channel needs none of this: it runs your code, so it is found by inspecting
its state whenever a struct changes, and its code_change/3 runs when its own module changes,
see State migration.) Hotcode's own HTTP endpoint is also a Bandit server; its processes are never treated as deploy
targets, whatever carriers says.
If it goes wrong
- The new code cannot start the app: the whole deploy is undone, state shapes included, and every application comes back on the old code.
- Several applications: all are started on the new code before any state is restored. If one fails, the ones that started are stopped again and every app is restored on the old code.
- An undo that cannot complete locks the node (
:node_lockedaudit event) until an operator has inspected it. - A held socket that could not be restored is never silent: it is listed under
droppedin the report and written to the audit log asapp_restore_degraded.
Between start and restore
The new start/2 starts the workers with the state their own init/1 builds, and each gets
its old state (and its sockets) back right after start/2 returns: a short moment, but not
none. Sockets are attached only at the restore, so no socket traffic
reaches a fresh worker. A call from another process can: it is answered from the fresh
state, and the restore then overwrites whatever that call changed. Hotcode cannot close that
window from outside (a registered process is reachable from the moment it registers, before
its init/1 has even run).
If a worker must not serve from its fresh state, let it wait for the old one. The stats
counter in examples/pulse (stats/lib/pulse_stats/counter.ex) does this: its application
knows a restart from a first start (its start/2 has run before in this VM), a counter started
by a restart answers :not_ready until the restore replaces its state (with a time limit), and
its callers retry. The checker verifies the result: the counter counts every answer exactly
once across two in-place restarts.
Recommendation
Leave allow_app_restart empty until you have exercised an in-place restart against your
real application tree, including its supervision shape, listeners and any dynamic children.
It is the one mechanism in Hotcode that interrupts running code. It has been tested with
purpose-built applications, and examples/pulse restarts one (pulse_stats, a counter) in place
inside a running Phoenix node while 16 channels and 4 TCP connections of the other application
stay up; Phoenix or Bandit themselves have never been restarted this way.