Elixir/Phoenix web deployments
A Phoenix LiveView app, an agent and a few machines make a loop with no CI, registry or scheduler in it: someone reports a problem on the running site, the agent changes the code, builds a release and hot-upgrades the running app, and the reporter’s open tab shows the fix without a reload, seconds after the report. A larger feature gets machines of its own and a review site before it reaches production.
This page shows the setup, the bugfix loop and the feature loop, with example scripts for each. Adapt them to your app: they are a starting point, not part of AgentSpaces.
Basic space setup
Why LiveView
A LiveView’s render/1 is module code. When a hot upgrade replaces the module, an open tab
shows the new code at its next render: no reload, no lost state. The root layout and JS hooks
are the exceptions (they load once per page), so keep what changes often, markup and styles,
inside the LiveView module.
An idle LiveView doesn’t render by itself after an upgrade (its code_change changes
nothing), so tell it: every LiveView subscribes to a deploys topic in an on_mount hook,
and a new version re-renders it.
# lib/shop_web/live/deploys.ex; the router's live_session has on_mount: ShopWeb.Live.Deploys.
defmodule ShopWeb.Live.Deploys do
import Phoenix.LiveView
import Phoenix.Component, only: [assign: 3]
def on_mount(:default, _params, _session, socket) do
if connected?(socket), do: Phoenix.PubSub.subscribe(Shop.PubSub, "deploys")
{:cont,
socket
|> assign(:release, Application.spec(:shop, :vsn))
|> attach_hook(:deploys, :handle_info, fn
{:deployed, vsn}, socket -> {:halt, assign(socket, :release, vsn)}
_other, socket -> {:cont, socket}
end)}
end
endThe deployer broadcasts once the new version is installed:
bin/shop rpc 'Phoenix.PubSub.broadcast(Shop.PubSub, "deploys", {:deployed, Application.spec(:shop, :vsn)})'.
The machines
| Machine | Size | What it holds |
|---|---|---|
shop-build | 2 vCPUs, 2 GiB | The toolchain (Erlang/OTP, Elixir), a checkout of main in /srv/src and every release shipped so far in /srv/artifacts. |
shop-app | 1 vCPU, 512 MiB | Only the release, which brings its own runtime, behind a web portal. |
| the agent’s machine | The agent that drives the loop. |
The split is the point: a release is self-contained, so the machine that runs it can be tiny, while the build machine keeps the toolchain and the archive of old releases that every upgrade needs (an upgrade is written from the version that runs).
Create the two machines from the agent’s machine:
space-env machines create shop-build --vcpus 2 --mem 2048
space-env machines create shop-app --vcpus 1 --mem 512The agent works in them by moving its tools there (space-env tools attach shop-build):
its commands then run in that machine.
The repository and the Spacebar
Keep the app, with its ops/ scripts, in a repository of your organization’s git. On the
build machine and the app machine:
space-env git setup
git clone space:shop /srv/srcOn the app machine, put the site behind a web portal:
space-env web-portal attach --port 4000A site served from a checkout of your organization’s git is a development site, and your organization’s members see the Spacebar on every page. A release runs from its own directory, not from the checkout, so name the checkout (the deployer keeps it at the commit that runs):
space-env web-portal source /srv/srcThe bar says what runs (acme/shop · main @ 3f9c2a1). A member who clicks it sees the
site’s feedback, the reports filed on it with their status (Reply, Open, Fixed
here once the site serves the fix), and files a new one: it becomes an issue in the
repository, opened as that member, labelled spacebar, with a screenshot, the page’s
console errors and failed requests, the commit that was served and the machine. Only
members get the bar and can report; everyone else sees the site as it will be in
production.
Hot upgrades
Castle upgrades the running node in place: castle unpack NEW, upgradable, install NEW (running, not yet permanent), then commit (boots
NEW from now on). install pauses the node, loads the new modules, runs code_change and
resumes; the app’s state stays. A failure before commit is undone by a restart.
Two rules keep this safe:
- A change to dependencies or the supervision tree needs a cold deploy:
ship.sh(below) refuses it. - Keep GenServer state stable, so that an upgrade only ever has to reload page modules.
The deployer
A small service on the app machine installs each release: it fetches it, upgrades the running app, checks the site and commits or rolls back. It must not keep the machine awake while it waits, so the app machine can be suspended when nobody uses it, and resumed by the next release.
The build machine owns a release topic and publishes to it; the app machine subscribes with
--qos notify, so a release resumes it when it is suspended:
# on shop-build, once
space-env topic create project/shop/release
# on shop-app, once
space-env subscribe project/shop/release --qos notify --reason "install each release of shop"On the app machine the deployer is a service, so it starts at every boot, also when a release resumed the machine:
space-env services create deployer -- /srv/src/ops/deployer.shIt looks for messages with space-env waiting, which doesn’t count as use of the machine,
and receives only when one is there:
#!/bin/sh
# ops/deployer.sh: install each release that arrives, without keeping the machine awake.
field() { printf '%s' "$msg" | jq -r --arg k "$1" '[.. | objects | select(has($k)) | .[$k]][0]'; }
while sleep 5; do
[ -n "$(space-env waiting)" ] || continue # a poll: the machine can still suspend
msg=$(space-env receive --timeout 0) || continue # take it
# Get, install, check, commit or roll back; whatever happens, the shipper gets an answer.
if out=$(/srv/src/ops/install.sh "$msg" 2>&1); then ok=true; else ok=false; fi
space-env send "$(field reply_to)" --context "$(field context)" --data "$(jq -nc --argjson ok "$ok" \
--arg version "$(field version)" --arg reason "$out" \
'{ok: $ok, version: $version, reason: $reason}')"
doneinstall.sh reads release and version from the message, fetches the release with
space-env artifact get "$release" -o FILE, runs Castle’s steps and the health check, moves
/srv/src to the release’s commit (git fetch --tags and git reset --hard "v$version" on
the branch it is on, so the Spacebar names both), broadcasts the new version to the open
LiveViews, and exits 0; or rolls back and exits non-zero with the reason on its output. The
deployer answers the machine that shipped it either way, also when install.sh dies halfway,
so a release is never lost without a word.
space-env receive --timeout N in a loop works too: a waiting receive lets the machine be
suspended, and a release sent with --qos notify resumes it (What keeps a machine
running). The 5 seconds it sleeps
is the most a release waits once the machine runs.
Several app machines can subscribe to the same topic: build once, and every one of them upgrades itself.
A visitor’s request resumes a suspended app machine too. Pages that are files (a landing
page, Phoenix’s digested assets from priv/static) can be served by the web portal from a
bucket instead, while the machine stays suspended; LiveView pages still reach the app. See
A static site from a bucket.
The health check and rollback
Check the site before the upgrade becomes permanent; when the check fails, the deployer puts
the previous version back and reports ok: false. Write the check so it can’t fail by
itself: curl … | grep -q under set -o pipefail races (grep -q stops reading, curl
fails writing, the pipe fails, and a good release is rolled back), so download first, then
search:
curl -fsS http://localhost:4000/ -o /tmp/page.html && grep -q 'id="app"' /tmp/page.htmlBugfix workflow
The agent subscribes to the repository’s issues:
space-env subscribe 'git/shop/issue/+' --qos notify --reason "Spacebar reports to fix and ship"Then, for each report filed on production (main on shop-app):
- Report. A member presses the Spacebar on the site and files what is wrong.
- Wake and read. The issue’s
openedevent wakes the agent. It acts only on issues labelledspacebar, one at a time, and only when the change stays in the app’s own page code. It reads the issue withspace-env git issue view <n>. - Change. With its tools on
shop-build, it edits onmainand compiles. - Ship.
ops/ship.sh shop-app <n>(below) commits, builds the release and its upgrade, and hands it to the app machine. - Install. The deployer installs it live, checks the site, and commits or rolls back. The reporter’s tab already shows the change.
- Close. The agent comments the version, commit and diff on the issue and closes it. In the Spacebar’s feedback list the report turns Fixed here.
ship.sh
On the build machine. It builds the upgrade from the version the target runs (the last one its deployer reported), so it never guesses:
#!/bin/sh
# ops/ship.sh TARGET [ISSUE]: build the next release of shop and hot-upgrade TARGET to it.
# Runs on a build machine, in /srv/src. VERSION=x.y.z sets the version (a feature's
# pre-releases); without it, the patch number of the latest release tag goes up.
set -eu
target=$1 issue=${2:-}
arch=/srv/artifacts
me=$(space-env whoami | awk '$1 == "machine:" {print $2}')
cd /srv/src
# What the target runs: a review machine starts as a copy of production.
from=$(cat "$arch/running-$target" 2>/dev/null || cat "$arch/running-shop-app")
# A hot upgrade reloads modules only: dependencies and the supervision tree go cold.
if ! git diff --quiet "v$from" -- mix.lock lib/shop/application.ex; then
echo "dependencies or the supervision tree changed since $from: deploy cold" >&2
exit 1
fi
# The next version follows the latest tag, not what runs: a release that failed to install
# keeps its tag, and the fix ships as the one after it (still upgrading from $from).
last=$(git tag -l 'v*' --sort=-v:refname | grep -v -- - | head -n 1 | sed 's/^v//')
to=${VERSION:-$(echo "$last" | awk -F. '{print $1 "." $2 "." $3 + 1}')}
sed -i "s/version: \"[^\"]*\"/version: \"$to\"/" mix.exs
git add -A lib priv mix.exs # new page modules too, not only changed ones
git commit -qm "shop $to${issue:+ (#$issue)}"
git tag "v$to"
git push -q origin HEAD "v$to"
# The upgrade is written from the release that runs: put it back where Castle's release
# steps (in mix.exs) look for it, then build.
mkdir -p _build/prod/rel/shop
tar -xzf "$arch/shop-$from.tar.gz" -C _build/prod/rel/shop
MIX_ENV=prod mix release --overwrite
cp "_build/prod/shop-$to.tar.gz" "$arch/"
# Hand it over: production by its topic, a review machine by a message to it. The context
# names this request; the deployer's answer carries it back.
ctx="ship-$target-$to"
space-env artifact put "$arch/shop-$to.tar.gz" --name "releases/shop-$to.tar.gz"
msg=$(printf '{"release": "releases/shop-%s.tar.gz", "version": "%s", "from": "%s", "reply_to": "%s", "context": "%s"}' \
"$to" "$to" "$from" "$me" "$ctx")
if [ "$target" = shop-app ]; then
space-env publish project/shop/release "$msg"
else
space-env send "$target" --qos notify --data "$msg"
fi
# Wait for the deployer's answer to this request (a late answer to an earlier one stays
# in the inbox), and check that it took this version.
reply=$(space-env receive --context "$ctx" --timeout 300)
ok=$(printf '%s' "$reply" | jq -r --arg v "$to" \
'[.. | objects | select(has("ok")) | .ok and .version == $v][0]')
if [ "$ok" != true ]; then
echo "$target did not take $to: $reply" >&2
exit 1
fi
echo "$to" > "$arch/running-$target"
echo "$target runs $to"The first release can’t be an upgrade: build it with MIX_ENV=prod mix release, install it
on the app machine as an ordinary release, tag it v3.0.0, and on the build machine keep its
tarball and record it as running (the next upgrade is written from that tarball):
cp _build/prod/shop-3.0.0.tar.gz /srv/artifacts/
echo 3.0.0 > /srv/artifacts/running-shop-appship.sh takes it from there.
ship.sh waits in receive for the answer, which keeps the build machine running for that
minute; that is what it is for.
The agent’s instructions, in its CLAUDE.md or AGENTS.md, say the same: which label to
act on, which code it may change, how to ship and what to do when ship.sh fails (read the
deployer’s reason, fix, ship again; never retry the same release blindly).
Routing reports
A report names the branch and the machine it was filed on, so it routes by rule:
| Filed on | Goes to |
|---|---|
main on shop-app | the bugfix loop: ship to production |
feature/NAME on app-NAME | that feature’s next pre-release (below) |
| anything else | nothing ships; the agent asks |
Reports from a review site never reach production.
Guard rails
Only signed-in members of your organization can file; only spacebar issues are acted on,
one at a time; changes stay in the page code; each app machine has its own secret key base
and cookie; a failed check rolls back. What the rails don’t cover is a bad change that still
passes the check: never point this loop at a machine that holds real customer data or
credentials.
Feature workflow (with development preview site)
A larger change gets a branch, its own machines and a review site before it touches
production: build-NAME, a copy of the build machine, and app-NAME, a hot copy of
production with its data as it is.
feature.sh
On the agent’s machine (only an agent’s machine creates machines):
#!/bin/sh
# ops/feature.sh NAME: machines for feature NAME, a build machine and a review site.
set -eu
name=$1
# The toolchain, the checkout and the release archive, as they are now.
space-env machines fork shop-build "build-$name"
# Production as it runs: the app, its data and its deployer. The fork gets none of
# shop-app's subscriptions, so it never installs production's releases.
space-env machines fork shop-app "app-$name" --hot
echo "next: in app-$name, ops/review.sh $name; in build-$name, git switch -c feature/$name"Then, with its tools on app-NAME, the agent puts the review site online:
#!/bin/sh
# ops/review.sh NAME: make this machine feature NAME's review site.
set -eu
name=$1
git -C /srv/src fetch -q origin
git -C /srv/src switch -c "feature/$name" # the Spacebar says acme/shop · feature/NAME
space-env web-portal attach --port 4000 # prints the review site's addressand on build-NAME it switches to the branch the same way and starts work.
A hot fork starts with the app already running and its data as in production. Two things to know:
- It runs with production’s environment. Anything derived from the host name, such as
Phoenix’s
check_origin, must allow the review site’s address too, or its LiveView socket is refused (403). - It needs production to run on the current guest kernel. When it can’t be made, the fork is an ordinary one and says why: the app then starts from its disk, with an empty state. Restart the production machine once after a platform release to keep hot forks possible.
Pre-releases
On build-NAME, ship to the review machine with a pre-release version:
VERSION=3.1.0-NAME.1 ops/ship.sh app-NAMEship.sh sends it straight to app-NAME with --qos notify, which resumes the machine if
it is suspended. SemVer sorts every 3.1.0-NAME.N before 3.1.0, so the real release later
upgrades from any of them.
Review rounds
- The agent opens a pull request from
feature/NAMEwith the review site’s address andFixes #N. - Reviewers try the feature on the review site and report with its Spacebar; those reports
carry
feature/NAMEandapp-NAME, so they become the next pre-release (3.1.0-NAME.2), not a production change. - Repeat until the pull request is approved.
Done
After the merge, the agent brings shop-build’s checkout up to the merged main and
builds the real 3.1.0 there (ship.sh doesn’t fetch, and its push needs the merge):
git -C /srv/src pull -q --ff-only origin main
VERSION=3.1.0 ops/ship.sh shop-appThen it removes the feature’s machines from its own machine:
#!/bin/sh
# ops/feature-done.sh NAME: remove feature NAME's machines (production is untouched).
set -eu
space-env machines delete "app-$1"
space-env machines delete "build-$1"Dropping a feature works the same way without the merge: close the pull request and its
issues, and run feature-done.sh.
What to watch for
- Check a downloaded release (size or checksum) before unpacking it.
- A hot upgrade can’t change dependencies or the supervision tree: ship those cold.
- The loop trusts its checks: write them so they test what users see, and so they can’t fail on their own.