How to Build Your Own Instant-Server Service Using Firecracker MicroVMs
Most agent sandboxes run in Firecracker microVMs. Here's how to build a small instant-server service yourself: host, jailer, networking, snapshots, a warm pool, and the API.
Every agent sandbox launch I read this year has the same line in its docs. InstaBox, the "cloud computers for AI agents" product from InsForge in YC's Spring 2026 batch, says each machine is "a Firecracker microVM". E2B's infra repo says "one Firecracker microVM per sandbox". Vercel Sandbox says each sandbox "runs in a secure Firecracker microVM". Superserve says its sandboxes are "powered by Firecracker MicroVMs".
I ran into Firecracker before, from the other side. When I wrote about Lambda SnapStart in July, the whole trick turned out to be a snapshot of a Firecracker microVM. This time I wanted the operator's view: the host, the jail, the network, the snapshot, and the small API that hands you a box, not the SDK.
This post builds a small version of that service end to end. One Linux host, Firecracker v1.18.0 under the jailer, one network namespace per box, a golden snapshot, a warm pool, a persistent /data disk per box, and a TypeScript control plane where POST /boxes claims a VM that's already restored instead of booting one.
One caveat before the commands. I wrote this on a Mac, and macOS has no KVM. I checked every command and JSON body against the Firecracker v1.18.0 docs and its OpenAPI spec, and the TypeScript passes tsc --strict. But I haven't run this stack on real KVM hardware. Treat it as a reviewed design, and test it on a metal host before you trust it.
Why a microVM and not a container
A container shares the host kernel. Every syscall the agent's code makes lands in the same kernel your control plane runs on, and one kernel bug is a way out. That's fine for code you wrote. It's not fine for code a model wrote five seconds ago, or code a stranger pasted into your free tier.
A Firecracker microVM gets its own guest kernel, and the wall between guest and host is KVM, which is hardware virtualization. The README says Firecracker "excludes unnecessary devices and guest-facing functionality to reduce the memory footprint and attack surface area of each microVM", which in practice leaves the guest with VirtIO net and block, vsock, a serial console, and a partial keyboard controller that only exists so the guest can ask for a reboot, per the design doc.
Then it stacks process-level walls on top. Firecracker installs seccomp filters per thread by default. The jailer puts each VMM process in its own chroot, mount namespace and cgroup, optionally its own network and PID namespace, and drops to an unprivileged uid before it execs Firecracker. The design doc's threat model treats every vCPU thread as "running malicious code as soon as they have been started". That's the stance you want for agent code.
It's also light enough to do per request. Firecracker's specification promises at most 5 MiB of VMM memory overhead for a 1 vCPU, 128 MiB guest, and at most 125 ms from the InstanceStart call to the guest's /sbin/init, measured with a minimal kernel and rootfs. AWS built it for services like Lambda and Fargate.
The pieces of a small instant-server service
This is everything the rest of the post builds.
The host. An EC2 instance with /dev/kvm, Firecracker and the jailer pinned to v1.18.0, cgroup v2, and one nftables ruleset that boxes can't get around.
The golden snapshot. One VM, booted once, warmed up, paused, snapshotted, and then killed. It's never resumed.
Slots. A slot is a network namespace, a jail, a copy-on-write rootfs, and a VM restored from the golden snapshot and left paused. The warm pool is a list of slots.
Boxes. A box is a slot someone claimed. It gets an identity through Firecracker's metadata service, its own /data disk, and then it's resumed.
The control plane.hrr_boxd.ts, a small HTTP API on the host that owns the pool, the box lifecycle, metering and quotas. A gateway in front of it (not shown) proxies SSH and HTTP to each box.
The whole service on one host. The control plane never boots anything on the request path; it hands out a VM the pool already restored.
The host has to expose /dev/kvm
Firecracker needs read and write access to /dev/kvm. The getting-started guide suggests a c5.metal with Ubuntu 24.04, and it still says "EC2 only supports KVM on .metal instance types".
That stopped being the whole story in February 2026, when AWS launched nested virtualization on virtual instances. The current EC2 docs list M7i, M7i-flex, M8i, M8id, M8i-flex, C7i, C7i-flex, C8i, C8id, C8i-flex, R7i, R7iz, R8i, R8id, R8i-flex, X8i, I7i and I7ie, with KVM and Hyper-V as the supported L1 hypervisors. You turn it on at launch with --cpu-options "NestedVirtualization=enabled", or on a stopped instance with modify-instance-cpu-options. AWS says there's no extra charge for it. Every family on that list is Intel. No Graviton yet.
I'd still run the real fleet on metal, for two reasons. The same AWS page tells you to evaluate bare metal for workloads that are "performance sensitive or have strict latency requirements", which a box service is, and Firecracker's own tested platforms table is all .metal: m6i.metal, m7i.metal-24xl, m8i.metal-48xl, m7a.metal-48xl, m8g.metal-24xl, m9g.metal-48xl and a few more. I couldn't find Firecracker docs that cover running inside nested virtualization, so I'd use nested instances for dev boxes and CI, and metal for production.
The first command below runs from your laptop; the rest run on the host as root.
# From your laptop: does this virtual instance type expose virtualization at all?
# An empty list means no nested virtualization.
aws ec2 describe-instance-types --instance-types m8i.2xlarge \
--query "InstanceTypes[].ProcessorInfo.SupportedFeatures"
# On the host: is KVM loaded, and can we use it?
lsmod | grep kvm
[ -r /dev/kvm ] && [ -w /dev/kvm ] && echo "OK" || echo "FAIL"
# cgroup v2 controllers the jailer will write to (cpu.max, memory.max)
echo "+cpu +memory" > /sys/fs/cgroup/cgroup.subtree_control
mkdir -p /sys/fs/cgroup/firecracker
echo "+cpu +memory" > /sys/fs/cgroup/firecracker/cgroup.subtree_control
# Pin the release and check the published checksum
FC=v1.18.0
ARCH="$(uname -m)"
BASE="https://github.com/firecracker-microvm/firecracker/releases/download/${FC}"
curl -fsSLO "${BASE}/firecracker-${FC}-${ARCH}.tgz"
curl -fsSLO "${BASE}/firecracker-${FC}-${ARCH}.tgz.sha256.txt"
sha256sum -c "firecracker-${FC}-${ARCH}.tgz.sha256.txt"
tar -xzf "firecracker-${FC}-${ARCH}.tgz"
install -m 0755 "release-${FC}-${ARCH}/firecracker-${FC}-${ARCH}" /usr/local/bin/firecracker
install -m 0755 "release-${FC}-${ARCH}/jailer-${FC}-${ARCH}" /usr/local/bin/jailer
The cgroup v2 part isn't optional in my book. The snapshot docs list "high snapshot restoration latency when cgroups V1 are in use" as a known limitation and strongly recommend v2. An instant-box service is mostly snapshot restores.
One box by hand, under the jailer
You need two artifacts: an uncompressed guest kernel and an ext4 rootfs. For a first run, the getting-started guide has a script that pulls both from Firecracker's CI bucket, patches an SSH key into the Ubuntu rootfs, and leaves you with $KERNEL, $ROOTFS and $KEY_NAME. For production, build your own with rootfs-and-kernel-setup.md.
Pick the guest kernel on purpose. The kernel policy supports 5.10, 6.1 and 6.18 guests, but the snapshot section below leans on VMGenID, and Linux only reseeds its RNG from VMGenID from 5.18 onward. 6.1 or 6.18, not 5.10.
This boots the golden VM. It's the only VM in the system that boots from a kernel. Everything after it restores from its snapshot.
# One-time: boot the golden VM. Slot 254 is reserved for it.
hrr-net-up.sh 254
ID=hrr-golden
JAIL="/srv/jailer/firecracker/$ID/root"
mkdir -p "$JAIL/run"
cp "$KERNEL" "$JAIL/vmlinux" # $KERNEL, $ROOTFS: from the getting-started script
cp --reflink=always "$ROOTFS" "$JAIL/rootfs.ext4"
truncate -s 1M "$JAIL/data.ext4" # placeholder, swapped for the real /data disk later
chown -R 20254:20254 "$JAIL"
jailer --id "$ID" --exec-file /usr/local/bin/firecracker \
--uid 20254 --gid 20254 --cgroup-version 2 \
--netns /var/run/netns/hrr-254 --new-pid-ns --daemonize
SOCK="$JAIL/run/firecracker.socket"
until [ -S "$SOCK" ]; do sleep 0.01; done
fc() { curl -sS --fail-with-body --unix-socket "$SOCK" -X "$1" "http://localhost$2" \
-H 'Content-Type: application/json' -d "$3"; }
fc PUT /machine-config '{"vcpu_count": 2, "mem_size_mib": 1024, "smt": false}'
fc PUT /boot-source '{"kernel_image_path": "/vmlinux",
"boot_args": "8250.nr_uarts=0 reboot=k panic=1"}'
fc PUT /drives/rootfs '{"drive_id": "rootfs", "path_on_host": "/rootfs.ext4",
"is_root_device": true, "is_read_only": false}'
fc PUT /drives/data '{"drive_id": "data", "path_on_host": "/data.ext4",
"is_root_device": false, "is_read_only": false}'
fc PUT /network-interfaces/eth0 '{"iface_id": "eth0", "guest_mac": "06:00:AC:10:00:02",
"host_dev_name": "tap0"}'
fc PUT /mmds/config '{"version": "V2", "network_interfaces": ["eth0"],
"ipv4_address": "169.254.170.2"}'
fc PUT /entropy '{}'
sleep 0.015 # getting-started.md: config is applied async, let it land before start
fc PUT /actions '{"action_type": "InstanceStart"}'
Every path in the API calls is relative to the jail root, /srv/jailer/firecracker/hrr-golden/root. The jailer copies the Firecracker binary into that chroot and Firecracker can't see anything outside it.
vcpu_count has to be 1 or an even number, per the API spec.
8250.nr_uarts=0 turns the serial console off. The production host guide recommends that, because the guest can otherwise write without limit to Firecracker's stdout.
The data drive is a 1 MiB placeholder that the guest never mounts. It's how each box gets its own disk later.
/mmds/config can only be set before boot. I moved MMDS off the default 169.254.169.254 so nobody confuses it with the EC2 metadata service I'm about to block.
PUT /entropy adds a virtio-rng device, one more entropy source for the guest after restore.
The guest MAC 06:00:AC:10:00:02 isn't random. The CI rootfs derives its IP from the MAC, so this one means 172.16.0.2. Every clone will have that same MAC and IP. The network has to be built around that.
Networking: one namespace per box
Firecracker gives each guest a TAP device and nothing more. The design doc is blunt about it: "Firecracker does not perform any network traffic filtering. All egress traffic from a guest is therefore considered untrusted, and should be filtered at the host-level."
Clones make this harder. Every VM restored from the golden snapshot expects a TAP called tap0 and believes its IP is 172.16.0.2. The fix in Firecracker's network-for-clones doc is a network namespace per clone, so every box can have its own tap0, plus a veth pair and NAT to make each one unique on the host. That's what this script does, and the golden VM uses it too, as slot 254.
#!/usr/bin/env bash
# hrr-net-up.sh <slot>: a namespace that looks exactly like the golden VM's network
set -euo pipefail
N="$1"
NS="hrr-$N"
ip netns add "$NS"
# Inside: the same tap0 and 172.16.0.1/30 the golden VM was snapshotted with
ip netns exec "$NS" ip tuntap add name tap0 mode tap
ip netns exec "$NS" ip addr add 172.16.0.1/30 dev tap0
ip netns exec "$NS" ip link set tap0 up
# A veth pair to the host. The host end gets a unique /30 per slot.
ip link add "hrrv$N" type veth peer name veth0 netns "$NS"
ip addr add "10.200.$N.1/30" dev "hrrv$N"
ip link set "hrrv$N" up
ip netns exec "$NS" ip addr add "10.200.$N.2/30" dev veth0
ip netns exec "$NS" ip link set veth0 up
ip netns exec "$NS" ip route add default via "10.200.$N.1"
ip netns exec "$NS" sysctl -qw net.ipv4.ip_forward=1
# Inbound SSH/HTTP to the guest, DNS to the host resolver, everything out as 10.200.N.2
ip netns exec "$NS" nft -f - <<NFT
table ip hrr {
chain pre {
type nat hook prerouting priority dstnat;
iifname "veth0" tcp dport { 22, 8080 } dnat to 172.16.0.2
iifname "tap0" udp dport 53 dnat to 10.200.$N.1
}
chain post {
type nat hook postrouting priority srcnat;
oifname "veth0" masquerade
}
}
NFT
From the host, box N is 10.200.N.2. The gateway connects there on port 22 or 8080 before the namespace forwards it to the guest. Outbound, the guest's traffic leaves the namespace as 10.200.N.2, and then the host decides what's allowed.
My taps live inside namespaces, so the host sees the hrrv* veths instead of tap*. The production guide shows a single rule that drops traffic from tap* to 169.254.169.254, and I block more than IMDS:
# /etc/nftables.d/hrr-host.nft
# Replace ens5 with your uplink: ip -j route list default | jq -r '.[0].dev'
table inet hrr_host {
chain input {
type filter hook input priority filter; policy accept;
iifname "hrrv*" ct state established,related accept
iifname "hrrv*" udp dport 53 accept # the host resolver, nothing else
iifname "hrrv*" counter drop
}
chain forward {
type filter hook forward priority filter; policy drop;
ct state established,related accept
iifname "hrrv*" ip daddr 169.254.0.0/16 counter drop # IMDS and the rest of link-local
iifname "hrrv*" oifname "hrrv*" counter drop # box to box
iifname "hrrv*" ip daddr { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10 } counter drop
iifname "hrrv*" tcp dport { 25, 465, 587 } counter drop # no spam relays on day one
iifname "hrrv*" oifname "ens5" counter accept
}
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
oifname "ens5" ip saddr 10.200.0.0/16 masquerade
}
}
In order: boxes can't reach the EC2 metadata service or anything else link-local, can't reach each other, can't reach your VPC or other private ranges, can't send mail, and can only talk to the host on DNS. Run a resolver on the host and point guests at 172.16.0.1, which the namespace forwards to it. Dropping all of 169.254.0.0/16 also cuts off the VPC resolver at 169.254.169.253, so the host resolver isn't optional.
The forward policy is drop, so this host shouldn't run anything else that forwards traffic, like Docker.
The one thing nftables can't do well is a domain allowlist. It sees IPs, and agents want to reach pypi.org, not an address. If you need "only these domains", send egress through an HTTP proxy that checks the CONNECT host or TLS SNI, and only let the proxy out. Superserve documents allow and deny lists by CIDR or domain, which is the feature you're rebuilding there.
Snapshot once, restore per request
Booting is the slow path. The 125 ms in the spec is with a minimal kernel and rootfs, and a real box has systemd, an SSH server, your agent, and whatever runtime the user expects to be warm, none of which you want to pay for on every POST.
You pay it once. Boot the golden VM, warm it up, and snapshot it. A Firecracker snapshot is a guest memory file plus a small microVM state file with the device and KVM state. Disks aren't part of it. They're yours to manage.
G="ip netns exec hrr-254 ssh -i $KEY_NAME root@172.16.0.2"
# Warm whatever your boxes need on first use. hrr-agent is your in-guest agent.
$G 'systemctl start hrr-agent && /opt/hrr/warm.sh'
# random-for-clones.md: don't hand every clone the same saved seed
$G 'rm -f /var/lib/systemd/random-seed && sync'
fc PATCH /vm '{"state": "Paused"}'
fc PUT /snapshot/create '{"snapshot_type": "Full",
"snapshot_path": "/snap.vmstate",
"mem_file_path": "/snap.mem"}'
# Never resume the golden VM. Kill it and publish its files.
kill -9 "$(cat "$JAIL/firecracker.pid")"
mkdir -p /var/lib/hrr/golden
for f in vmlinux rootfs.ext4 snap.vmstate snap.mem; do
ln "$JAIL/$f" "/var/lib/hrr/golden/$f"
done
chown root:root /var/lib/hrr/golden/*
chmod 0444 /var/lib/hrr/golden/*
The golden VM is never resumed. The snapshot docs walk through which patterns are safe. "Boot A, snapshot, terminate, load in B" is safe. Resuming the original and a clone from the same state isn't, because both continue with the same random state and tokens. Kill the golden VM.
The clones' rootfs is the golden VM's disk after the snapshot, not the image you started from. The guest's page cache in snap.mem describes that disk at that moment, so hand a clone a different disk and its filesystem state won't match its memory; Firecracker drains and fsyncs block devices during snapshot creation, so the file is consistent once the call returns.
Loading a snapshot is lazy. With the File backend, Firecracker mmaps the memory file MAP_PRIVATE. Pages load from it on first touch and writes go to private copy-on-write memory, which keeps restore fast and also means snap.mem must stay unchanged on disk for as long as any clone runs. All the clones on a host share its read pages through the page cache.
If kernel page faults are too slow for you, the Uffd backend hands every page fault to a process you write, over userfaultfd. That's where you'd prefetch the pages a box always touches, or pull memory from somewhere other than local disk. Firecracker gives you the protocol, not the handler. Start with File.
You'll also see diff snapshots, which only write pages dirtied since the last snapshot. In v1.18.0 the docs still mark them as developer preview, and most diff files have to be merged onto a base with snapshot-editor before you can resume them. I'd use full snapshots for both the golden image and idle boxes, and come back to diffs once they're stable.
What one POST /boxes does once the pool is warm: nothing on the request path boots a kernel.
Both paths meet at the fix-ups. Skip them and every clone shares the golden VM's keys and identity.
Try the three paths before reading on. The figure below races a cold boot against a snapshot restore and a claim from the warm pool. Start all three at once and watch where the time goes on each lane. The cold boot spends it on the kernel, init and your app. The restore spends a few milliseconds loading state, more if the memory file sits on network storage. The warm pool has already paid both before anyone asked. The timings are illustrative, in the range public write-ups report, not a benchmark. Switch to the burst view to see what pool size does to p99, and skip the fix-ups to see what goes wrong.
A restore is quick, but a slot also needs a namespace, a jail and a rootfs copy, and the jailer gets slower with load. Its docs measured jail creation at about 2x slower with 10 jails starting in parallel on a host with no mount points, and about 10x with 500 mount points. None of that happens on the request path: a slot is built ahead of time, restored, and left paused.
#!/usr/bin/env bash
# hrr-slot-up.sh <slot>: one restored, paused microVM, waiting to be claimed
set -euo pipefail
N="$1"
ID="hrr-slot-$N"
GOLD=/var/lib/hrr/golden
JAIL="/srv/jailer/firecracker/$ID/root"
U=$((20000 + N))
hrr-net-up.sh "$N"
# Shared files are hard links. The rootfs is a reflink: instant, and CoW per box.
mkdir -p "$JAIL/run"
ln "$GOLD/vmlinux" "$GOLD/snap.vmstate" "$GOLD/snap.mem" "$JAIL/"
cp --reflink=always "$GOLD/rootfs.ext4" "$JAIL/rootfs.ext4"
truncate -s 1M "$JAIL/data.ext4"
chown "$U:$U" "$JAIL" "$JAIL/run" "$JAIL/rootfs.ext4" "$JAIL/data.ext4"
chmod 0600 "$JAIL/rootfs.ext4"
jailer --id "$ID" --exec-file /usr/local/bin/firecracker \
--uid "$U" --gid "$U" \
--cgroup-version 2 --cgroup "cpu.max=200000 100000" --cgroup "memory.max=1280M" \
--netns "/var/run/netns/hrr-$N" --new-pid-ns --daemonize
SOCK="$JAIL/run/firecracker.socket"
for _ in $(seq 200); do [ -S "$SOCK" ] && break; sleep 0.01; done
curl -sS --fail-with-body --unix-socket "$SOCK" -X PUT http://localhost/snapshot/load \
-H 'Content-Type: application/json' \
-d '{"snapshot_path": "/snap.vmstate",
"mem_backend": {"backend_path": "/snap.mem", "backend_type": "File"},
"clock_realtime": true,
"resume_vm": false}'
The rootfs uses cp --reflink=always. That only works on a filesystem with reflinks, like XFS or Btrfs, where it's a metadata-only copy, so every box starts with a private, writable rootfs that shares blocks with the golden one until it writes. On ext4 the command fails rather than quietly copying gigabytes, which is the behaviour I want. The hard links mean /var/lib/hrr and /srv/jailer have to be on the same filesystem.
Each slot runs under its own uid and gid, which the production guide recommends, so a broken jail can't read a neighbour's files. cpu.max=200000 100000 caps the box at two CPUs' worth of time per 100 ms period. memory.max leaves some room above the guest's 1024 MiB for the VMM itself.
How big should the pool be? It needs to cover the boxes requested while a slot is being rebuilt, so if you hand out 2 boxes a second at peak and a slot takes 3 seconds to build, a pool of 6 runs dry. Measure your slot build time on your hardware and size from that. When the pool is empty, the API returns 503 and the client retries, which is better than quietly falling back to a cold boot.
Every clone wakes up with the same secrets
This is the part of the instant-box idea that's easy to get wrong. A restored VM resumes exactly where the golden VM stopped. Anything it had already generated, every clone has too. The snapshot docs say it directly: without a strong way to keep unique things unique, "we consider resuming execution from the same state more than once insecure."
The kernel side is mostly handled. Firecracker always enables a VMGenID device and writes a fresh 16-byte ID on every restore. Linux 5.18 and later uses that to reseed its CSPRNG. There's still a short window between the vCPUs resuming and the reseed, which random-for-clones.md calls out, and it does nothing for state that userspace already pulled out of the kernel. Lambda has the same problem, and the SnapStart uniqueness guide reads like a checklist for this section.
State
Same in every clone?
What I'd do
Kernel CSPRNG
Reseeded via VMGenID on Linux 5.18+, after a short window
6.1+ guest kernel, the entropy device, and no secrets generated in that window
/var/lib/systemd/random-seed
Yes
Delete before the snapshot (done above)
/proc/sys/kernel/random/boot_id
Yes
Bind-mount a fresh file over it if anything reads it
SSH host keys, /etc/machine-id
Yes
Regenerate on claim, before the gateway sends traffic
Userspace RNGs, cached tokens, UUIDs
Yes
Don't create them before the snapshot; regenerate on claim
MAC and IP
Yes
Namespace per box plus NAT (done above)
Wall clock
Resumes from snapshot time
clock_realtime on load, then step the clock on claim
vsock connections
Closed by the snapshot
Agent reconnects; guest listen sockets survive
MMDS data
Not in the snapshot
PUT /mmds with the box identity on claim
Those last rows are how a clone finds out it's a new box. The control plane writes {box: {id, owner, claimedAt}} into MMDS, and the agent in the guest polls it at 169.254.170.2 with an MMDS V2 token. When the ID changes from empty to something, it regenerates keys and machine ID, steps the clock, and mounts /data.
About the clock: clock_realtime: true only exists on x86_64, needs host Linux 5.16 or later, and advances kvm-clock by the time since the snapshot was taken, at load. The docs don't say what happens to the guest clock while a loaded slot sits paused in the pool, so I wouldn't rely on it. Firecracker's FAQ recommends NTP in the guest, and at scale a KVM PTP clock as the NTP source. I'd have the agent step the clock on claim as well, before anything checks a TLS certificate.
/data lives on its own disk
InstaBox's homepage describes "a 20 GiB persistent disk at /data" next to a separate root disk, a split I like, and the placeholder drive makes it possible on top of a shared snapshot.
#!/usr/bin/env bash
# hrr-data-attach.sh <box-id> <slot>: create the box's /data disk once, link it into the jail
set -euo pipefail
BOX="$1"
N="$2"
DISK="/var/lib/hrr/data/$BOX.ext4"
if [ ! -f "$DISK" ]; then
truncate -s 20G "$DISK"
mkfs.ext4 -q -L hrr-data "$DISK"
fi
chown "$((20000 + N)):$((20000 + N))" "$DISK"
ln -f "$DISK" "/srv/jailer/firecracker/hrr-slot-$N/root/box.ext4"
On claim, the control plane links the box's disk into the jail and calls PATCH /drives/data with the new path. The block update docs describe exactly this placeholder pattern, with one rule: the guest must not have the device mounted or be reading it while you swap. The golden VM never touched it, so that holds. The agent then mounts LABEL=hrr-data on /data, and the label matters here, because device names like /dev/vdb depend on the order the drives were added.
The rootfs is disposable. Resetting a box means throwing away its reflinked rootfs and taking a fresh slot. /data outlives that, and it outlives DELETE /boxes/:id too, until you add a volume API to remove it.
Pausing a box stops its vCPUs but keeps all its RAM. For boxes idle long enough to matter, hibernate them to disk:
# Idle for a long time: write the box to disk, then free its RAM
fc PATCH /vm '{"state": "Paused"}'
fc PUT /snapshot/create '{"snapshot_type": "Full",
"snapshot_path": "/box.vmstate",
"mem_file_path": "/box.mem"}'
# move box.vmstate, box.mem, rootfs.ext4 and box.ext4 somewhere safe, then hrr-slot-down.sh
# Waking it later = a fresh jail with the same relative paths + PUT /snapshot/load.
# Each hibernation snapshot is loaded once, which is the safe pattern in snapshot-support.md.
The control plane: POST /boxes without a boot
This is the whole API for one host. Claiming a box is a hard link and three Firecracker calls: write the identity to MMDS, resume, and swap the data disk. That leaves room for the target of under a second. It's a target, though. I haven't measured it.
The control plane also owns the lifecycle (pause, resume, destroy, idle timeout), per-second metering, and a per-owner quota.
// hrr_boxd.ts: the control plane for one host. Node 22+, runs as root next to the jails.
import http from "node:http";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
const run = promisify(execFile);
const HRR_POOL_TARGET = 8;
const HRR_IDLE_MS = 15 * 60_000;
const HRR_MAX_BOXES_PER_OWNER = 5;
const HRR_KEYS = new Map<string, string>(Object.entries(JSON.parse(process.env.HRR_API_KEYS ?? "{}")));
type HrrSlot = { slot: number; sock: string };
type HrrBox = HrrSlot & {
id: string;
owner: string;
state: "running" | "paused";
lastActive: number; // the SSH/HTTP gateway (not shown) bumps this on traffic
runningMs: number;
since: number;
cpuAtClaim: number;
};
class HrrHttpError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
const pool: HrrSlot[] = [];
const boxes = new Map<string, HrrBox>();
const freeSlots: number[] = [];
let nextSlot = 0;
let filling = false;
// One Firecracker API call over the jail's unix socket
function hrr_fc(sock: string, method: "PUT" | "PATCH", path: string, body: unknown) {
const data = JSON.stringify(body);
return new Promise<void>((resolve, reject) => {
const req = http.request(
{
socketPath: sock,
method,
path,
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) },
},
(res) => {
let out = "";
res.on("data", (chunk) => (out += chunk));
res.on("end", () =>
(res.statusCode ?? 500) < 300
? resolve()
: reject(new Error(`${method} ${path} ${res.statusCode}: ${out}`)),
);
},
);
req.on("error", reject);
req.end(data);
});
}
async function hrr_fill_pool() {
if (filling) return;
filling = true;
try {
while (pool.length < HRR_POOL_TARGET) {
const slot = freeSlots.pop() ?? nextSlot++;
if (slot > 253) break; // 254 is the golden VM; the /30 scheme runs out after that
await run("/usr/local/sbin/hrr-slot-up.sh", [String(slot)]);
pool.push({ slot, sock: `/srv/jailer/firecracker/hrr-slot-${slot}/root/run/firecracker.socket` });
}
} finally {
filling = false;
}
}
function hrr_refill() {
hrr_fill_pool().catch((err) => console.error("pool refill failed", err));
}
async function hrr_cpu_seconds(slot: number) {
// jailer + cgroup v2: <cgroup root>/<parent-cgroup, default "firecracker">/<id>
const stat = await readFile(`/sys/fs/cgroup/firecracker/hrr-slot-${slot}/cpu.stat`, "utf8");
return Number(/^usage_usec (\d+)$/m.exec(stat)?.[1] ?? 0) / 1e6;
}
function hrr_set_state(box: HrrBox, next: HrrBox["state"]) {
const now = Date.now();
if (box.state === "running") box.runningMs += now - box.since;
box.state = next;
box.since = now;
}
function hrr_billable_seconds(box: HrrBox) {
const live = box.state === "running" ? Date.now() - box.since : 0;
return Math.ceil((box.runningMs + live) / 1000);
}
async function hrr_create_box(owner: string) {
const mine = [...boxes.values()].filter((b) => b.owner === owner).length;
if (mine >= HRR_MAX_BOXES_PER_OWNER) throw new HrrHttpError(429, "box quota reached");
const slot = pool.shift();
if (!slot) throw new HrrHttpError(503, "warm pool empty, retry shortly");
hrr_refill();
const id = `box-${randomUUID().slice(0, 8)}`;
try {
await run("/usr/local/sbin/hrr-data-attach.sh", [id, String(slot.slot)]);
// The MMDS data store isn't in the snapshot, so this is where a clone learns who it is
await hrr_fc(slot.sock, "PUT", "/mmds", { box: { id, owner, claimedAt: new Date().toISOString() } });
await hrr_fc(slot.sock, "PATCH", "/vm", { state: "Resumed" });
// Swap the placeholder for the real disk; the agent mounts LABEL=hrr-data when it appears
await hrr_fc(slot.sock, "PATCH", "/drives/data", { drive_id: "data", path_on_host: "/box.ext4" });
} catch (err) {
await run("/usr/local/sbin/hrr-slot-down.sh", [String(slot.slot)]).catch(() => {});
freeSlots.push(slot.slot);
throw err;
}
const now = Date.now();
const box: HrrBox = {
...slot, id, owner, state: "running", lastActive: now, runningMs: 0, since: now,
cpuAtClaim: await hrr_cpu_seconds(slot.slot),
};
boxes.set(id, box);
return box;
}
async function hrr_pause(box: HrrBox) {
await hrr_fc(box.sock, "PATCH", "/vm", { state: "Paused" });
hrr_set_state(box, "paused");
}
async function hrr_resume(box: HrrBox) {
await hrr_fc(box.sock, "PATCH", "/vm", { state: "Resumed" });
hrr_set_state(box, "running");
box.lastActive = Date.now();
}
async function hrr_destroy(box: HrrBox) {
const cpu = (await hrr_cpu_seconds(box.slot)) - box.cpuAtClaim;
hrr_set_state(box, "paused"); // closes the open running interval
console.log(JSON.stringify({ usage: box.id, owner: box.owner, seconds: hrr_billable_seconds(box), cpu }));
await run("/usr/local/sbin/hrr-slot-down.sh", [String(box.slot)]);
boxes.delete(box.id);
freeSlots.push(box.slot);
}
function hrr_auth(req: http.IncomingMessage) {
const key = req.headers.authorization?.replace(/^Bearer /, "");
const owner = key ? HRR_KEYS.get(key) : undefined;
if (!owner) throw new HrrHttpError(401, "bad api key");
return owner;
}
// Idle reaper. Pausing stops the CPU meter; it doesn't give the RAM back.
setInterval(() => {
for (const box of boxes.values()) {
if (box.state === "running" && Date.now() - box.lastActive > HRR_IDLE_MS) {
hrr_pause(box).catch((err) => console.error(box.id, err));
}
}
}, 1000);
http
.createServer(async (req, res) => {
const reply = (status: number, body: unknown) =>
res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(body));
try {
const owner = hrr_auth(req);
if (req.method === "POST" && req.url === "/boxes") {
const box = await hrr_create_box(owner);
return reply(201, {
id: box.id,
ssh: `ssh ${box.id}@ssh.boxes.example.dev`,
http: `https://${box.id}.boxes.example.dev`,
});
}
const [, root, id, action] = (req.url ?? "").split("/"); // /boxes/:id[/:action]
const box = root === "boxes" && id ? boxes.get(id) : undefined;
if (!box || box.owner !== owner) return reply(404, { error: "no such box" });
if (req.method === "POST" && action === "pause") await hrr_pause(box);
else if (req.method === "POST" && action === "resume") await hrr_resume(box);
else if (req.method === "DELETE" && !action) await hrr_destroy(box);
else if (req.method !== "GET" || action) return reply(405, { error: "unsupported" });
return reply(200, { id: box.id, state: box.state, billableSeconds: hrr_billable_seconds(box) });
} catch (err) {
reply(err instanceof HrrHttpError ? err.status : 500, { error: (err as Error).message });
}
})
.listen(8080, "127.0.0.1", hrr_refill);
Metering has two numbers.billableSeconds is wall time while running, rounded up to the second. cpu comes from the slot's cgroup v2 cpu.statusage_usec, minus whatever was spent restoring before the claim. Bill on either. Vercel bills Sandbox CPU on active CPU time and memory on what's provisioned, which is the second model.
The idle timeout pauses, it doesn't destroy. InstaBox's idle docs pause after 30 idle minutes and keep memory and processes. Mine pauses at 15 and leaves hibernation to a second, slower timer.
A failed claim burns the slot. If any Firecracker call fails halfway, that VM is in an unknown state. Tear it down and let the pool refill.
Pool refills never crash the process.hrr_refill catches errors from the slot script. An unhandled rejection there would take the whole API down with it.
State lives in memory. Restart the process and you lose track of running boxes. A real version keeps boxes in a database and reconciles against /srv/jailer on startup.
What I'd check first on real hardware
Everything above follows the v1.18.0 docs, but these are the parts I'd test first, because the docs don't spell them out:
That the jailer accepts a value with a space in --cgroup "cpu.max=200000 100000". If it doesn't, create the cgroup yourself and use --parent-cgroup.
That Firecracker creates its socket in /run inside the jail with the directory pre-created and owned by the slot's uid, as the script assumes.
That PATCH /drives right after resume, before the agent touches the device, behaves like the documented post-boot case.
The real numbers on your instance type: slot build time, claim latency, and how many paused 1 GiB clones fit before page cache pressure starts hurting restores.
Going further, depending on your job
If you're a DevOps engineer like me
Harden the host before you tune it. The production guide recommends disabling SMT and Kernel Samepage Merging for multi-tenant hosts, turning swap off, loading microcode early, and running one tenant per Firecracker process. Do those first, then measure.
Keep host logging quiet. The same guide describes a setup where turning on host console logging slowed snapshot restore from 3 ms to 8.5 ms on aarch64, because creating TAP devices logged to a slow console. It recommends quiet loglevel=1 on the host kernel command line.
Watch the boxes, not just the host. Firecracker v1.17 added emit_id to metrics, so each line carries the microVM ID. Add cgroup cpu.stat and memory.current per slot, the nft counters on the drop rules, and alert on the lost-logs and lost-metrics counters.
Run a watchdog. The production guide recommends an outside process that finds unresponsive Firecracker processes and kills them with SIGKILL, because the custom signal handlers can deadlock in rare cases.
Treat the golden snapshot as a build artifact. Snapshots must be resumed on identical software and hardware. Key it by Firecracker version, host kernel and instance family, rebuild it on every upgrade, and roll hosts instead of upgrading them in place.
If you're a cloud engineer
Keep each fleet on one instance family. A snapshot from one CPU generation won't restore on another. That makes "whatever metal is cheapest today" a bad scaling policy, and it's a reason to pick one family per region and stay on it.
Graviton is an option on metal. v1.17 added support for Graviton5 m9g.metal-48xl. It isn't an option for nested virtualization, where AWS's list is Intel-only.
Decide where /data survives. On local NVMe, a box's data dies with the host. If that's not OK, copy /data to S3 on hibernate and pull it back on wake, or pin each box to a host and accept the risk. Make that choice before your first user stores something they care about.
Plan for a shared egress IP. With NAT, every box on a host leaves through the host's address. One abusive box can get that IP blocked for every box on the host. If you need clean IPs per customer, that's a separate NAT or Elastic IP design.
If you're a backend or full-stack engineer
Make POST /boxes idempotent. Accept an Idempotency-Key header and return the same box on a retry. Agents retry a lot, and a duplicated box is a quota leak.
Return 503 with Retry-After when the pool is empty. Don't hold the request open for a cold boot. The client can wait better than your API can.
Put the agent API on vsock. Exec, file upload and port forwarding from the control plane over vsock don't need the guest network at all. Remember that the snapshot closes vsock connections, so reconnect after every restore.
Keep a usage ledger. Write every state change with a timestamp to a table, and compute bills from that, not from a counter in memory like my example.
If you're building this as a business
Cost per box-hour is a division. Take the host's hourly price from the EC2 pricing page and divide by how many boxes you can actually fit. RAM is usually the limit, so that number depends on overcommit: the shared snap.mem pages, the balloon device with free page reporting, and how aggressively you hibernate. CPU oversubscription is on by default in Firecracker, so CPU density is a policy choice, not a hard limit.
Paused isn't free. A paused box burns no CPU but holds all its RAM. Price idle time accordingly, or hibernate it.
Free tiers attract crypto miners. Cap CPU with cpu.max, alert on boxes that sit at their cap for an hour, put free-tier egress behind the allowlist proxy, and keep the fixed idle pause. InstaBox fixes the free plan's idle timeout at 30 minutes, while paid plans can change it.
Noisy neighbours are mostly disk and network. Firecracker has token-bucket rate limiters on every block and network device. The production guide warns that one box writing heavily can fill the host page cache and slow everyone else's I/O. Set limits per plan from day one, because adding them later feels like a downgrade to existing users.
Hope you enjoyed this one. If you've run Firecracker in production and one of my assumptions above breaks on real hardware, I'd like to hear which one.
On this post
Comments
A reply stays under the note it answers.
No comments yet.
If you have a note on How to Build Your Own Instant-Server Service Using Firecracker MicroVMs, sign in and leave it.