Black Friday: the complete AWS Security Bundle, 12 volumes, $99 $49.50 BLACKFRIDAY50 Grab it →
SecurityZines.com Join

How Firecracker microVMs Work

From "what is a VM" to KVM exits, virtio rings, the jailer and snapshot clones. The tech that runs every AWS Lambda call, drawn by hand.

Every time an AWS Lambda function runs, it runs inside a tiny virtual machine that was started in a fraction of a second. Thousands of those VMs share one physical server, and many of them belong to strangers who do not trust each other. The software that makes this possible is called Firecracker.

This post explains how it works. It starts with zero background and ends deep in the internals. Read the parts you need and skip the rest. Every diagram draws itself when you scroll to it. Click a diagram to play it again.

Part 1 : plain words

1. The problem: running strangers' code

In plain wordsImagine you rent out space on one big computer. Alice, Bob and a stranger called Eve all upload code, and you run it on the same machine. You need walls between them. If Eve's code can peek into Alice's data, you are out of business.

There are two classic ways to build those walls.

Containers (Docker, Kubernetes pods) are like rooms in one flat. Each app gets its own room, but every room shares the same building: one Linux kernel. Containers start fast and cost almost nothing. The catch is that the kernel is a huge shared surface. One kernel bug and Eve can walk out of her room into Alice's.

Virtual machines are like separate houses. Each VM runs its own kernel on top of virtual hardware. To escape, Eve has to break the virtualization layer itself, which is much harder. The catch is that a classic VM (for example with QEMU) pretends to be a whole PC: BIOS, USB controllers, PCI buses, sound cards and hundreds of other devices. All of that takes time to start, eats memory, and every emulated device is more code that can have bugs.

microVMs are the third option: tiny prefab cabins. You keep the strong VM wall, but you throw away almost all the fake hardware. What is left boots in about the time a container does.

Containers share one kernel. VMs each get a kernel plus a pile of fake hardware. microVMs keep the kernel wall and drop the pile. Open full size

Takeaway: a microVM gives you VM-grade isolation at close to container speed.

2. Why AWS built Firecracker

AWS Lambda launched in 2014. Customers upload a function, AWS runs it when an event arrives, and you pay by the millisecond. That means AWS runs code from millions of customers, and it needs to start a fresh sandbox for them all the time.

In the early days Lambda used containers inside a separate EC2 VM for each customer account. That kept customers apart, but it wasted a lot of capacity: each account needed its own VM, even if it only ran one tiny function now and then. Packing many customers onto one host safely needed something new.

Nothing on the shelf fit. QEMU was too big and too slow to start. Containers alone were not a strong enough wall. So AWS wrote its own VM monitor in Rust, starting from Google's crosvm (the VM monitor in ChromeOS), and open-sourced it in November 2018 under the Apache 2.0 licence. In 2020 they published the design in a paper at NSDI, "Firecracker: Lightweight Virtualization for Serverless Applications".

Many tenants, one host. The four numbers that made Firecracker worth building. Open full size

The design targets are the numbers people still quote:

  • about 125 ms from "start" to the guest running user code
  • less than 5 MiB of extra memory per microVM, on top of the guest's own RAM
  • up to 150 new microVMs per second on one host
  • about 50,000 lines of Rust when the paper came out, against well over a million lines for QEMU

Fargate (AWS's serverless containers) moved onto Firecracker too. Today it also runs Fly.io Machines and a lot of sandboxes for AI agents. More on that at the end.

Part 2 : how it works

3. Virtualization in five minutes

In plain wordsThink of the CPU as a football referee. The guest system plays normally and the referee lets the game flow at full speed. When the guest tries something risky, like touching hardware, the referee blows the whistle, the host decides what happens, and then play continues.

Modern CPUs have hardware support for virtualization: Intel VT-x, AMD-V, and the virtualization extensions on ARM. With VT-x the CPU has two worlds. The host runs in VMX root mode. The guest runs in VMX non-root mode. Most guest instructions (add, move, jump, even most kernel work) run directly on the real CPU at full speed. No emulation, no translation.

Some things are not allowed to run directly. If the guest touches a device address, executes certain privileged instructions or gets an interrupt it should not see, the CPU stops the guest and jumps back to the host. That is a VM exit. The host handles the event and then resumes the guest with a VM entry (VMRESUME). The CPU keeps each virtual CPU's state in a structure called the VMCS, and translates guest "physical" memory to real memory with EPT (extended page tables).

The guest runs at full speed until it does something that needs the host. Then: exit, handle, enter. Open full size

Takeaway: the speed of a VM depends on how often it exits. Fewer exits, faster VM.

4. KVM does the CPU, Firecracker does the rest

On Linux, the kernel part of virtualization is KVM (kernel-based virtual machine, the kvm.ko module). KVM knows how to drive VT-x or AMD-V. It keeps the vCPU state, maps guest memory, and emulates the interrupt controller and timers inside the kernel, because those are hit so often that a trip to user space would be too slow.

KVM does not build a whole machine. It does not load a kernel, it does not provide a disk or a network card, and it has no API for humans. That is the job of a user-space program called the VMM (virtual machine monitor). QEMU is the famous one. Firecracker is a much smaller one.

The two talk through one file, /dev/kvm, using ioctl() calls. That handful of calls is enough to create a VM, give it memory and start a vCPU:

KVM owns the CPU and memory tricks. Firecracker owns the API, the devices, booting and snapshots. Open full size
fd   = open("/dev/kvm", O_RDWR)
vm   = ioctl(fd,   KVM_CREATE_VM, 0)
       ioctl(vm,   KVM_SET_USER_MEMORY_REGION, &region)   // guest RAM
vcpu = ioctl(vm,   KVM_CREATE_VCPU, 0)
       ioctl(vcpu, KVM_SET_REGS, &regs)                  // where to start
       ioctl(vcpu, KVM_RUN, 0)                            // run until an exit

Firecracker is written in Rust, a memory-safe language. That matters a lot here: the VMM parses data that comes straight from the guest, which is the attacker in our threat model. Many real QEMU escapes were memory bugs in device emulation code written in C.

5. One VM is one process

In plain wordsEach microVM is just a normal Linux program. You can see it in ps, limit it with cgroups, and kill it with kill. When the program stops, the VM is gone.

One firecracker process runs exactly one microVM. Inside it there are three kinds of threads:

  • API thread (fc_api): serves a small REST API on a Unix socket. This is how you configure and control the VM.
  • VMM thread (the main thread): runs an epoll event loop that drives the emulated devices, the rate limiters and the metrics.
  • vCPU threads (fc_vcpu 0, fc_vcpu 1 ...): one per virtual CPU. Each one sits in a loop calling KVM_RUN.

Guest RAM is a plain anonymous mmap region inside the Firecracker process. Firecracker hands that region to KVM with KVM_SET_USER_MEMORY_REGION, and from then on the guest sees it as its own "physical" memory. The host kernel can still swap it, account it to a cgroup, or back it with huge pages, like any other process memory.

Threads and memory of a single microVM. Guest RAM is just one big mmap. Open full size

Takeaway: all the normal Linux tools for processes (cgroups, namespaces, seccomp, kill) work on a microVM. Firecracker leans on that hard for security.

6. From API call to running kernel

You start Firecracker with a socket path and then describe the VM with a few HTTP calls. Each call is checked before boot, so a bad config fails early with a clear error instead of a half-started VM. A successful call returns 204 No Content.

Five calls, then boot. No BIOS, no bootloader. Open full size
curl --unix-socket /tmp/firecracker.socket -X PUT http://localhost/machine-config \
  -d '{ "vcpu_count": 2, "mem_size_mib": 1024 }'

curl --unix-socket /tmp/firecracker.socket -X PUT http://localhost/boot-source \
  -d '{ "kernel_image_path": "./vmlinux",
        "boot_args": "console=ttyS0 reboot=k panic=1 pci=off" }'

curl --unix-socket /tmp/firecracker.socket -X PUT http://localhost/drives/rootfs \
  -d '{ "drive_id": "rootfs", "path_on_host": "./rootfs.ext4",
        "is_root_device": true, "is_read_only": false }'

curl --unix-socket /tmp/firecracker.socket -X PUT http://localhost/actions \
  -d '{ "action_type": "InstanceStart" }'

You can also skip the API and pass everything in one JSON file with --config-file.

Why it boots so fast

A normal PC boot runs firmware (BIOS or UEFI), which finds a bootloader (grub), which finds and decompresses the kernel, which finally starts. Firecracker skips all of it. It reads the uncompressed vmlinux kernel image straight into guest memory, writes the boot parameters and the kernel command line where Linux expects them, sets the vCPU registers to the kernel's 64-bit entry point, and calls KVM_RUN. The first instruction the guest executes is kernel code.

Look at the boot args. pci=off tells Linux not to scan for a PCI bus, because there isn't one. reboot=k makes the guest reboot through the keyboard controller, which Firecracker turns into a clean exit. console=ttyS0 sends the kernel log to the serial port. Firecracker also adds virtio_mmio.device=... entries to the command line, which is how the guest learns where its disk and network devices live without scanning anything.

Part 3 : deep dive

7. The vCPU loop and VM exits

Each vCPU thread is a simple loop. It calls ioctl(vcpu, KVM_RUN), and that call blocks while the guest runs. When the guest does something KVM cannot handle in the kernel, the call returns with an exit reason in a shared structure (kvm_run). Firecracker handles it and loops.

The heartbeat of every vCPU thread. Open full size

In Firecracker the interesting exit reasons are few:

  • KVM_EXIT_MMIO: the guest read or wrote a memory address that belongs to a device. Firecracker finds the device on its MMIO bus and lets it handle the access. This is how the guest talks to virtio devices.
  • KVM_EXIT_IO (x86 only): the guest used an I/O port. Firecracker has only two port devices: the serial console and a stub i8042 keyboard controller whose only job is the reset line.
  • Everything else, like timer interrupts, most of the interrupt controller and page table work, stays inside KVM and never reaches Firecracker.

Every exit costs a few microseconds (a full switch from guest to host kernel to user space and back). So the design goal is simple: keep exits rare, and make the common ones skip user space. The next two sections show how virtio does that.

8. Virtio: devices without fake hardware

In plain wordsInstead of pretending to be a real disk controller, Firecracker and the guest agree on a shared to-do list in memory. The guest writes "please write these bytes", taps Firecracker on the shoulder, and Firecracker writes back "done".

Emulating a real network card means the guest pokes dozens of hardware registers per packet, and each poke is a VM exit. Virtio is a standard for "paravirtual" devices: the guest knows it is in a VM and uses a simple, efficient protocol instead. Linux has virtio drivers built in.

The core of virtio is the virtqueue, made of three parts that all live in guest RAM:

  1. Descriptor table: entries of address, length, flags. Each one points at a buffer in guest memory. Descriptors can be chained with the NEXT flag, and WRITE marks a buffer the device writes into.
  2. Available ring: the driver puts the index of a descriptor chain here to say "this job is ready".
  3. Used ring: the device puts the index back, plus how many bytes it wrote, to say "this job is done".
Virtio in one picture. The data never gets copied into a message, both sides read the same memory. Open full size

Firecracker uses the virtio-mmio transport: each device is a small block of registers at a fixed address. The guest writes the queue number to the QueueNotify register to "kick" the device. Because Firecracker maps all of guest RAM into its own process, it reads descriptors and buffers in place.

The whole device list is short on purpose:

  • virtio-net: network, backed by a TAP device on the host
  • virtio-block: disks, backed by plain files on the host
  • virtio-vsock: a host-to-guest socket, backed by a Unix socket
  • virtio-balloon: lets the host ask the guest to hand memory back
  • virtio-rng: entropy for the guest
  • serial console and an i8042 stub for reset

No USB, no GPU, no sound, no BIOS. Fewer devices means less code an attacker can reach from inside the guest.

9. One disk write, end to end

Let's follow a single write from the guest's filesystem to a file on the host.

Seven steps from a guest write to bytes in a host file. Open full size
  1. The guest's block driver builds a request in the virtqueue: a header descriptor (type write, sector number), one or more data descriptors, and a status byte for the answer.
  2. It writes to QueueNotify. Normally that would be an MMIO exit all the way to user space.
  3. But Firecracker registered an ioeventfd for that address. KVM sees the write, signals the eventfd inside the kernel, and resumes the guest right away. The vCPU never waits for the disk.
  4. The VMM thread wakes up in its epoll loop. Before it does any work it asks the device's rate limiter for tokens (more on that below).
  5. It reads the descriptors from guest memory and does a pwrite() into the backing file, for example rootfs.ext4. Firecracker can use plain synchronous I/O or io_uring for this.
  6. It writes the status byte and puts the request index on the used ring.
  7. It signals an irqfd, and KVM injects the interrupt into the guest. The guest driver sees the used ring and completes the write.
Rate limiters. Every block and network device can have a token bucket for bandwidth (bytes) and for operations, each with a size, a refill_time in milliseconds and an optional one_time_burst. When the bucket is empty, the VMM thread simply stops taking requests from that queue until it refills. One noisy VM cannot starve the disk or network for its neighbours.
"rate_limiter": {
  "bandwidth": { "size": 52428800, "refill_time": 1000 },
  "ops":       { "size": 1000,     "refill_time": 1000 }
}

10. Networking, metadata and vsock

Firecracker does not do routing, bridging or DHCP. It gives the guest a virtio-net card and connects it to a TAP device on the host. Every frame the guest sends comes out of tap0 on the host. From there it is plain Linux networking: you add an IP, turn on forwarding and NAT the traffic out.

# on the host
sudo ip tuntap add dev tap0 mode tap
sudo ip addr add 172.16.0.1/30 dev tap0
sudo ip link set dev tap0 up
sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# tell Firecracker to use it
curl --unix-socket /tmp/firecracker.socket -X PUT http://localhost/network-interfaces/eth0 \
  -d '{ "iface_id": "eth0", "guest_mac": "06:00:AC:10:00:02", "host_dev_name": "tap0" }'
Three ways in and out of a microVM. Open full size

MMDS: a metadata service inside Firecracker

EC2 instances read their config from 169.254.169.254. Firecracker has the same idea built in, the microVM Metadata Service (MMDS). You load a JSON document with PUT /mmds, and when the guest sends HTTP to the MMDS address, Firecracker intercepts the packet and answers it itself. The request never leaves the host. Version 2 works like EC2's IMDSv2: the guest first does PUT /latest/api/token with an X-metadata-token-ttl-seconds header, then sends the token in X-metadata-token on every read. That blocks the classic SSRF trick of making some app inside the guest fetch metadata with a plain GET.

vsock: talk to the guest without a network

Sometimes you just want an agent in the guest to talk to the host, for example to send logs or receive commands, without giving the VM a network at all. virtio-vsock does that. On the host side it is a Unix socket. To reach port 52 in the guest, you connect to that Unix socket and send CONNECT 52\n. Firecracker answers OK <port>\n and from then on the stream goes straight to the guest process listening on AF_VSOCK port 52. Connections from the guest to the host land on a Unix socket named <uds_path>_<port>.

11. Security: the four walls

In plain wordsAssume the attacker already has root inside the VM. That is not a bug in this model, it is the starting point. The question is how many walls they must break to reach the host or another customer. With Firecracker the answer is four.
Root in the guest is only root in a box inside a box inside a box. Open full size

Wall 1: KVM and hardware virtualization. The guest runs in VMX non-root mode with its own page tables, mapped through EPT. It cannot see host memory at all. The only way out is through the narrow set of exits Firecracker handles, and that device code is small and written in Rust.

Wall 2: seccomp. Suppose the attacker still finds a bug in device emulation and runs code inside the Firecracker process. Firecracker installs a seccomp-BPF filter on every thread before the guest starts. Each thread type (api, vmm, vcpu) has its own allow-list of syscalls and even of syscall arguments, and anything else kills the whole process with SIGSYS. The filters are compiled into the binary at build time. You can supply your own with --seccomp-filter, and you should never use --no-seccomp in production.

Wall 3: the jailer. Firecracker ships with a second binary, jailer, that sets up the process before Firecracker even starts:

  1. creates new mount, PID and network namespaces (you can also pass an existing one with --netns)
  2. puts the process in cgroups so you can cap CPU, memory and I/O
  3. builds a tiny chroot at /srv/jailer/firecracker/<id>/root, with only the device nodes it needs (/dev/kvm, /dev/net/tun) and the files you link in
  4. drops to an unprivileged uid and gid, then execs Firecracker
sudo jailer --id vm1 \
  --exec-file /usr/bin/firecracker \
  --uid 123 --gid 100 \
  --cgroup-version 2 \
  -- --api-sock /run/firecracker.socket

Wall 4: the host. The host itself should be hardened against side channels. The Firecracker production guide asks you to disable SMT (hyperthreading) so two tenants never share a physical core, keep KPTI and the other Spectre and Meltdown mitigations on, and keep the kernel and microcode patched.

Takeaway: an attacker needs a guest-to-VMM bug, then a way around seccomp, then a way out of the jail, then a host bug. Each wall is cheap for you and expensive for them.

12. Snapshots and clones

Firecracker can freeze a running VM to disk and bring it back later, on the same host or another one. This is how you get a "warm" VM in a few milliseconds instead of booting from scratch every time.

Pause, save two files, load as many copies as you like. Open full size
# pause and save
curl --unix-socket $SOCK -X PATCH http://localhost/vm -d '{ "state": "Paused" }'
curl --unix-socket $SOCK -X PUT http://localhost/snapshot/create \
  -d '{ "snapshot_type": "Full", "snapshot_path": "./vmstate", "mem_file_path": "./mem" }'

# in a fresh firecracker process: load and go
curl --unix-socket $SOCK2 -X PUT http://localhost/snapshot/load \
  -d '{ "snapshot_path": "./vmstate",
        "mem_backend": { "backend_type": "File", "backend_path": "./mem" },
        "resume_vm": true }'

A snapshot is two files. The vmstate file holds the small stuff: vCPU registers, device state, the interrupt controller. The memory file holds guest RAM. On load, Firecracker maps the memory file with MAP_PRIVATE, so pages are read from disk only when the guest touches them, and writes go to private copies. Ten clones of one snapshot share the same clean pages in the host page cache. For very large memory you can use the Uffd backend and serve pages yourself with Linux userfaultfd. There are also diff snapshots that save only the pages that changed.

The clone gotcha. Every clone wakes up with the exact same memory. That includes the guest's random number generator state, any keys or tokens the app already generated, TCP sequence numbers and the MAC address. Two clones can produce the same "random" values. Recent Firecracker versions add a VMGenID device so the guest kernel knows it was restored and can reseed itself, but your own app still needs to refresh anything it derived from randomness. Also give each clone its own MAC and IP.

Snapshots also need care across hosts. A guest that saw a CPU feature (say AVX-512) on one host will crash if it is restored on a host without it. Firecracker's CPU templates (for example "cpu_template": "T2" in /machine-config) hide CPU features so a snapshot can move between different machine types.

13. Who runs it, and when to pick it

Some of the places your code may already be running in a microVM. Open full size
  • AWS Lambda and Fargate, the reason it exists.
  • Fly.io: Fly Machines are Firecracker microVMs.
  • AI agent sandboxes such as E2B run each agent's code in its own microVM. If an LLM writes and runs code for you, it is quite likely inside one.
  • Kata Containers can use Firecracker as its VMM, and firecracker-containerd lets containerd run containers inside microVMs. Same container workflow, VM-grade wall.

Pick Firecracker when you run untrusted or multi-tenant code, you want many small short-lived workloads per host, and fast start matters. Pick something else when you need a GPU, a Windows guest, a desktop or a lot of special hardware. Firecracker is built for headless Linux compute only. It needs a Linux host with KVM, so on a cloud VM you need bare metal or nested virtualization, and it supports x86_64 and aarch64 hosts.

14. Try it yourself

You need a Linux machine with KVM. Check that you can open /dev/kvm first.

# 1. can I use KVM?
[ -r /dev/kvm ] && [ -w /dev/kvm ] && echo "KVM OK" || echo "fix /dev/kvm access"

# 2. get the latest release
ARCH="$(uname -m)"
release_url="https://github.com/firecracker-microvm/firecracker/releases"
latest=$(basename $(curl -fsSLI -o /dev/null -w %{url_effective} ${release_url}/latest))
curl -L ${release_url}/download/${latest}/firecracker-${latest}-${ARCH}.tgz | tar -xz
mv release-${latest}-${ARCH}/firecracker-${latest}-${ARCH} firecracker

# 3. start it (one terminal)
rm -f /tmp/firecracker.socket
./firecracker --api-sock /tmp/firecracker.socket

You also need a guest kernel (vmlinux) and a root filesystem (rootfs.ext4). The getting started guide links ready-made ones. Then, in a second terminal, send the four curl calls from section 6. The guest's serial console shows up in the first terminal, and in about a second you have a login prompt inside a VM.

Things to try next: add the network interface from section 10 and ping out, take a snapshot and load it in a second Firecracker process, then run the whole thing again under jailer.

15. Cheat sheet

  • What: a Rust VMM on top of KVM. One process per microVM. Open source since 2018, Apache 2.0.
  • Numbers: about 125 ms to user space, under 5 MiB overhead, up to 150 VMs per second per host.
  • Threads: api (REST on a Unix socket), vmm (devices, epoll), one vcpu thread per vCPU (KVM_RUN loop).
  • Boot: no BIOS, no bootloader. Loads vmlinux and jumps to the entry point. Boot args console=ttyS0 reboot=k panic=1 pci=off.
  • Devices: virtio-net (TAP), virtio-block (file), vsock (Unix socket), balloon, rng, serial, i8042. Over virtio-mmio.
  • Fast I/O: ioeventfd for kicks, irqfd for interrupts, token-bucket rate limiters per device.
  • Walls: KVM, seccomp per thread, jailer (namespaces, cgroups, chroot, unprivileged uid), hardened host with SMT off.
  • Snapshots: vmstate + memory file, MAP_PRIVATE lazy load. Re-seed and re-address every clone. Use CPU templates to move between hosts.

Want all of this on paper? The 3-page Firecracker mini book is free, with a print-ready PDF.

Get the next one by email

New posters land in the Security Zines newsletter on Substack. Free, no spam.