Personalize this lesson
Adapt explanations and teaching visuals to your background and preferred voice.
An agent runs a script that installs a package, creates a chart, and leaves a background process running. The next tenant needs a fresh workspace. Which parts can the service share, and which parts must disappear before that workspace is reused?
In Local Agent Sandboxing, Landlock and Seatbelt restricted processes on one workstation. A multi-tenant service also has to contain an untrusted guest, manage shared host resources, and recover after its controller crashes. We'll follow two sandbox instances, A and B, from one clean template through separate writes and eventual cleanup.
Give each session an owner and a readiness boundary
Treat generated code as untrusted. It can consume memory, spawn processes, inspect its environment, and make every network request its permissions allow. The platform's trusted host agent controls the virtual machine, resource limits, network paths, and artifact export.
Use an authenticated tenant, sandbox ID, and generation number to identify each instance. A retry can refer to an existing instance only after the controller reconciles its status. Reusing an ID while an old process still owns its resources creates a cleanup race.
This design uses lightweight virtual machines called Firecracker microVMs, each with its own guest kernel. A virtual machine monitor (VMM) is the host process that configures the guest and emulates its devices. Linux Kernel-based Virtual Machine (KVM) supplies hardware-assisted execution. The VMM, KVM, host kernel, and management services remain part of the trusted platform.[1][2]
External API connections use Transport Layer Security (TLS). The trusted broker constructs those connections after checking the sandbox's authority.

Sharing the immutable template reduces repeated initialization. Each instance still owns its writable memory, scratch storage, command channel, and capabilities.
For the interactive route, set an initial design target of at most 15 ms at the 99th percentile (p99), measured from gateway acceptance to the guest supervisor beginning the first user instruction. Include placement, queueing after acceptance, restore work, and required readiness checks. Record rejection rate and timeout rate alongside that percentile. Measure cold launch separately for each image profile.
That target needs a workload test with pinned host and guest kernels, Firecracker version, image, snapshot residency, concurrent starts, and user-code entry instrumentation. Firecracker's snapshot documentation makes restore performance dependent on memory, vCPU, and device configuration.[3] A successful snapshot API response and the first executed user statement are different timing endpoints.
The service should support:
- Separate session state for iterative agent turns, with an explicit expiration and disposal policy.
- Bounded stdin, stdout, stderr, uploaded files, and exported artifacts.
- Package installation from approved artifacts or network routes.
- Resource profiles such as 1–4 virtual CPUs (vCPUs), 512 MiB–8 GiB of configured guest RAM, and a 5 GiB scratch limit.
- Denial of guest access to host management interfaces, other tenants, and infrastructure metadata.
Those resource profiles are example product limits. MiB and GiB mean and bytes. The host also needs memory for VMM overhead, shared pages, page tables, buffers, and the operating system.
Put the guest kernel behind KVM
Ordinary containers isolate processes through namespaces and resource controls while sharing a host kernel. A successful host-kernel privilege escalation can compromise that shared boundary. A microVM gives each tenant a guest kernel, so controlling that guest kernel still leaves the VMM and KVM boundary to cross.[1]
KVM exposes file descriptors and ioctl operations through /dev/kvm. A host VMM typically:
- Opens
/dev/kvmand usesKVM_CREATE_VMto obtain a VM descriptor. - Registers host userspace memory regions as guest physical memory.
- Uses
KVM_CREATE_VCPUto obtain vCPU descriptors. - Runs each vCPU through
KVM_RUNand handles exits that require userspace device emulation.[4]
Hardware virtualization handles guest execution and address translation. Some exits are handled inside KVM. Others return to the VMM with a userspace exit reason.
The following C fragment shows only that control flow. VM initialization, memory mappings, device handlers, and shutdown coordination are omitted. Check the return value before consulting exit_reason, because an interrupted or failed call has a different outcome.[4]
while (!stop_requested) {
int rc = ioctl(vcpu_fd, KVM_RUN, 0);
if (rc < 0) {
if (errno == EINTR) {
continue; /* Recheck stop_requested at the loop boundary. */
}
report_run_error(errno);
break;
}
switch (run_struct->exit_reason) {
case KVM_EXIT_MMIO:
handle_mmio(run_struct);
break;
case KVM_EXIT_IO:
handle_io_port(run_struct);
break;
case KVM_EXIT_HLT:
handle_guest_halt(run_struct);
break;
default:
stop_for_unhandled_exit(run_struct->exit_reason);
stop_requested = true;
}
}
A halt needs the VMM's guest-lifecycle policy. It can mean waiting for an interrupt rather than the end of a session.
Keep the VMM's host authority small
Firecracker has a deliberately limited device surface for lightweight virtual machines. Its Rust implementation helps prevent memory-safety errors, while device emulation, unsafe code, KVM, and host integration still need security review and updates.[2]
Device support changes by version. The Firecracker source checked for this chapter supports VirtIO virtual devices over memory-mapped I/O (MMIO) and optional Peripheral Component Interconnect (PCI) VirtIO transport. That transport support doesn't imply arbitrary PCI-device emulation or device passthrough.[5] Use the matching host, guest, and device configuration rather than a fixed count of emulated devices.
The Jailer prepares a restricted host environment for the Firecracker process. It can create a restricted filesystem view, drop to configured user and group IDs, configure resource-control groups (cgroups), and create a process-ID (PID) namespace. Its --netns option joins a network namespace that the integrator has already created.[6]
Keep Firecracker's default seccomp system-call filters, protect its API socket, and bound serial and process output. The upstream host guide specifically calls out unbounded guest-driven output as a host resource risk.[2]
| Boundary | State it separates | Remaining shared dependency |
|---|---|---|
| Container namespaces | Host processes and selected resource views | Host kernel and permitted device interfaces |
| Guest VM | Guest kernel and guest address space | VMM, KVM, host kernel, and hardware |
| Jailed VMM process | Host filesystem, credentials, and process access | Required host interfaces and their implementations |
| Network policy | Permitted destinations and services | Enforcement path, address handling, and broker authority |
These controls protect different interfaces. Keep their configuration and failure tests separate.
Restore a clean template, then establish readiness
A useful base snapshot contains the initialized guest kernel, language runtime, and a supervisor waiting for work. Create it before tenant data, customer credentials, or user jobs enter the guest.
A Firecracker snapshot includes guest memory and versioned microVM state. Disk backing files are managed separately by the integrator and must remain consistent with the saved state.[3] Authenticate the template's provenance and integrity before loading it, and keep its backing memory file immutable for the restored VM's lifetime.

The guest can be running while the service still withholds user work. Readiness belongs to the chosen template and restore protocol.
Follow one copy-on-write page
With the File memory backend, Firecracker maps the snapshot memory file privately. Host page faults bring required file contents into RAM on demand. Writes create private copies rather than modifying the backing template.[3]
Suppose one 4 KiB page contains the value 20. A and B initially read that clean page. When A writes 99, A gets a private page containing 99. B and the immutable base still contain 20. The physical page-size choice in this example is explicit.

Reading a previously absent page can incur I/O and increase resident memory without creating a private modified copy. Writes, including runtime bookkeeping or collector metadata updates, can increase private memory. Mapping a snapshot avoids copying every unmodified byte up front, while page faults and working-set growth still affect latency and capacity.
MAP_NORESERVE changes reservation behavior on systems that use it. It doesn't create physical RAM or make overcommit safe. Plan admission against actual resident-memory pressure and the guest's allowed growth.
Choose who handles missing pages
Firecracker also offers the Uffd backend, which delegates missing-page handling through Linux userfaultfd to a userspace process. The integrator supplies that handler and its permissions, storage, validation, failure behavior, and latency budget.[7]
A custom handler could read snapshot chunks from a local cache or a remote store. Remote NVMe or object-storage fetching is an integration design. Firecracker's interface doesn't supply a complete distributed cache. A stalled handler can stall guest progress, so test cold pages and failure recovery as well as hot-cache restores.
Repair the state that must be fresh
Cloning a template also clones information that applications may assume is unique or current. Inspect the following state before admitting tenant work.
Wall clocks and application deadlines
The documented snapshot path can resume the guest wall clock from snapshot time. Synchronize it through the guest protocol, or use a supported restore-time clock option under its documented host and clock-source conditions.[3]
An old wall clock can affect certificate validity and token expiry. Monotonic durations, saved timers, and application deadlines need their own restore semantics. Test them on the actual guest rather than assuming every timer expires or every TLS operation fails.
Supported VMClock implementations can expose a changed generation counter to userspace after restore. That is a signal for compatible applications to refresh their state. It requires matching guest support and application integration.[3]
Kernel randomness and copied application state
Firecracker updates the virtual machine generation identifier (VMGenID) when restoring a snapshot. A supporting guest kernel uses the notification to reseed its random generator. There is a window between resuming vCPUs and handling that notification.[8]
The kernel's random generator and a copied userspace pseudorandom generator are separate state. Reinitializing the kernel doesn't replace previously generated tokens, cached random values, application identifiers, or every userspace seed. The snapshot can also retain the same /proc/sys/kernel/random/boot_id.[8]
Use a restore protocol validated for the actual guest driver and kernel configuration. Keep customer keys and one-use credentials out of the template. Admit user work only after the required kernel and application-state checks succeed. A generic “32 fresh bytes sent” counter doesn't establish that those checks passed.
Host networking and guest identity
The host TAP device name, its network namespace, and the guest's IP/MAC configuration are different objects. Jailer joins a supplied namespace. A clone strategy can reuse the same TAP name and private guest address inside distinct namespaces, with host routing or NAT separating their external paths.[6][9]
For example, 192.168.241.2 is a private address. Repeating it in isolated namespaces doesn't make it unique globally. The host must still provision the intended routes and filtering. The upstream clone-network example is a starting point that needs its own security and performance validation.[9]
Open connections and supervisor state
Snapshot restore can lose network connections. Firecracker resets existing vsock connections while preserving guest listen sockets for new connections.[3] Reconnect the host control channel for the new sandbox generation.
Guest file descriptors refer to guest resources and device protocols. They aren't ordinary host file descriptors copied into the guest. Keep the template quiescent, reconcile external state explicitly, and avoid carrying live user processes or external sessions into a shared template.

Give each guest a disposable writable filesystem
A package installation or generated output.csv should change only that sandbox's writable layer. In this design, the guest mounts an OverlayFS root: a merged view of a read-only base and per-instance scratch.
The lower layer can come from a read-only SquashFS image attached through a virtual block device. In this design, the guest creates an upper directory and allocates a fresh, empty work directory for each instance. OverlayFS requires workdir to be on the same filesystem as upperdir. The work directory supports OverlayFS operations and is kept outside the merged user view.[10]
Read a base configuration file and the merged view can use the lower file. Modify it and OverlayFS copies it into the upper layer. Create output.csv and it exists in the upper layer. Delete a lower file and a whiteout records its removal from the merged view while leaving the lower file intact.[10]
The host owns the scratch backing file or volume. The guest owns its mounted OverlayFS view. After the instance retires, the host can dispose of the instance's backing resources. A host process cannot directly unmount an unrelated guest's / as though it were a host mount.

For reuse, stop admission, retire execution, close references, revoke capabilities, and dispose of the old scratch backing. Construct the next instance from the clean template and a fresh upper/work pair. Cleanup latency depends on the storage path and outstanding work. Filesystem disposal also needs separate retention rules for exported artifacts, logs, and backups.
Use vsock as a bounded command channel
Virtio-vsock provides host-guest communication through a virtual socket device. Firecracker mediates host AF_UNIX sockets and guest AF_VSOCK sockets.[11] This control path uses Unix/vsock endpoints rather than host TCP ports.
That removes TCP port allocation from this particular channel. It still consumes descriptors, buffers, and VMM work. TCP capacity depends on its configured ephemeral range and connection tuples. Compare both paths with measurements instead of assigning either one a fixed transit time.
A guest supervisor can listen on vsock port 5000. For a host-initiated connection, the host connects to the configured Unix socket, sends CONNECT 5000\n, and waits for an OK PORT\n acknowledgement. Only then does the same stream carry application messages.[11]

Stream reads can return part of a message or close before a delimiter arrives. The following host-side integration fragment reads one bounded acknowledgement without consuming application payload bytes. It requires a running, correctly configured guest and is left unmarked as an executable lesson cell.[12]
import re
import socket
import time
def read_ack(sock, timeout=2.0):
deadline = time.monotonic() + timeout
line = bytearray()
for _ in range(64):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("vsock acknowledgement deadline exceeded")
sock.settimeout(remaining)
chunk = sock.recv(1)
if not chunk:
raise ConnectionError("vsock closed before acknowledgement")
line.extend(chunk)
if chunk == b"\n":
match = re.fullmatch(rb"OK ([0-9]+)\n", bytes(line))
if match is None:
raise ConnectionError("invalid vsock acknowledgement")
port = int(match.group(1))
if not 2**30 <= port < 2**31:
raise ConnectionError("unexpected host-side vsock port")
return port
raise ConnectionError("vsock acknowledgement exceeds 64 bytes")
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(2.0) # Example connect timeout.
sock.connect("/srv/jailer/firecracker/vm-a/root/vsock.sock")
sock.sendall(b"CONNECT 5000\n")
assigned_port = read_ack(sock, timeout=2.0)
sock.settimeout(2.0) # A separate timeout for the next operation.
sock.sendall(b'{"action":"execute","script":"print(42)"}\n')The port check above follows the pinned Firecracker implementation's reserved host-side range. The complete service also needs generation-bound authorization, message framing, backpressure, cancellation, and output limits. Check the matching host and guest prerequisites for the deployed release.
Constrain outbound traffic and broker private API access
The command channel and Internet access serve different purposes. Give the guest only the network routes it needs, and enforce that policy outside the untrusted guest.
Put forbidden destinations behind an enforced deny path
Cloud instance metadata can expose instance information and role credentials. AWS documents IPv4 IMDS at 169.254.169.254 and an optional IPv6 endpoint, fd00:ec2::254, on supported Nitro instances and subnets.[13] The credentials belong to the EC2 instance's assigned role. Whether that instance is a bare-metal worker or a VM is a deployment choice.
Cover every relevant address family and path. Denying one address in one forwarding chain leaves other routes, local services, redirects, or proxy paths to inspect. The policy for this design is:
| Guest request | Enforced handling |
|---|---|
| Host management, metadata, another tenant, or unapproved private destination | Deny before it leaves the sandbox's permitted network boundary |
| Approved package artifact | Fetch through the authorized artifact service |
| Approved private API operation | Send to the authenticated API broker |
| Arbitrary destination or unresolved policy | Deny and return a bounded error |
Validate all resolved addresses, including IPv6 and mapped forms. Connect to the validated destination, preserve TLS hostname verification, and reject or revalidate redirects. Resolve and validate again for a new connection. Domain allowlisting and an earlier DNS lookup alone don't prevent rebinding.[14]
Give the broker an explicit protocol
Suppose A may read one repository through a GitHub integration. The orchestrator issues a short-lived capability bound to A's instance generation, tenant, repository, and permitted read operation. The guest presents that capability to an authenticated broker endpoint.
The broker validates the caller and operation, constructs the permitted upstream request, retrieves the real credential, and opens TLS to the approved API origin. The real credential stays inside the trusted broker. An ordinary encrypted HTTPS tunnel doesn't expose its Authorization header for a transparent proxy to rewrite.

A phantom reference or broker capability still grants authority. Guest code can try to abuse every operation it permits. Limit methods, resource paths, redirects, response size, lifetime, and rate. Revoke the capability when its instance retires. A host or broker compromise crosses the trusted boundary described earlier.
Size resident memory and runnable work separately
Use one hypothetical host for the worksheet: 128 physical CPU cores and 256 GiB RAM. These are chosen inputs, rather than specifications for a named server.
Reserve 32 GiB for host services, shared resident template data, and an initial allowance for other overhead. This leaves:
If every guest reserves a full 2 GiB within that remaining budget, the quotient is . If each guest instead contributes an assumed 50 MiB of private resident pages, the private-page-only quotient is .
The roughly 41-fold difference exposes the assumption that matters: how much each guest actually makes private. The second quotient excludes per-instance overhead and additional safety headroom. It cannot establish a host limit for 4,587 active 2 GiB guests. If those guests write their allowed memory, the physical demand changes dramatically.

Shared page-cache accounting, VMM memory, page tables, buffers, scratch growth, simultaneous faults, and a cold template can further reduce density. Measure those terms under concurrent starts and representative code, then admit against bounded memory pressure. Test correlated peaks and recovery capacity.
CPU overcommit needs a separate worksheet. At 128 cores and 30 configured one-vCPU sessions per core, the host would expose 3,840 vCPUs. An assumed 3% average duty cycle corresponds to 115.2 core-equivalents of mean demand. Synchronized work can still make all 3,840 vCPUs runnable and create queueing. Mean demand doesn't determine p99 startup or completion latency.

Place the VMM process and its tasks in the intended host cgroup. For fair-class CPU scheduling, cpu.max = 100000 100000 allows that group an aggregate 100,000 microseconds of CPU time per 100,000-microsecond period. It doesn't assign that allowance independently to every vCPU thread.[15]
Set memory.max with the guest footprint and VMM overhead in mind, monitor memory events, and define out-of-memory (OOM) handling. Host pids.max limits host tasks. Guest process limits constrain the untrusted processes inside that guest. Keep both controls, plus output, disk, and network limits, in the resource profile.[15]
Model page ownership and retirement locally
Before implementing the host agent, check the lifecycle with a small deterministic model. It represents three clean 4 KiB pages and separate private writes. Its readiness flags are supplied controller observations, and its retirement call represents a trusted confirmation that execution has stopped.
The program performs dictionary and integer operations in one Python process. It checks the model's transitions, while real readiness probes and resource retirement require a VMM integration test.
Predict two results: after A writes 99 into page 1, what does B read? After A requests cancellation, can cleanup already discard A's scratch?
from dataclasses import dataclass, field
PAGE_BYTES = 4096
REQUIRED = frozenset({"clock", "kernel_rng", "app_state", "network", "control"})
@dataclass
class Clone:
sandbox_id: str
generation: int
base: tuple[int, ...]
state: str = "RESTORED"
private: dict[int, int] = field(default_factory=dict)
scratch: dict[str, bytes] = field(default_factory=dict)
def admit(self, verified: set[str]):
if self.state != "RESTORED" or not REQUIRED <= verified:
raise RuntimeError("restore checks incomplete")
self.state = "READY"
def start(self):
if self.state != "READY":
raise RuntimeError("instance is not ready")
self.state = "RUNNING"
def read(self, page: int):
if self.state != "RUNNING":
raise RuntimeError("instance is not running")
if type(page) is not int or not 0 <= page < len(self.base):
raise RuntimeError("page is outside the modeled mapping")
return self.private.get(page, self.base[page])
def write(self, page: int, value: int):
self.read(page) # Require a running instance and an existing page.
self.private[page] = value
def request_cancel(self):
if self.state != "RUNNING":
raise RuntimeError("instance is not running")
self.state = "CANCEL_REQUESTED"
def confirm_retired(self, sandbox_id: str, generation: int):
if (sandbox_id, generation) != (self.sandbox_id, self.generation):
raise RuntimeError("retirement identity mismatch")
if self.state != "CANCEL_REQUESTED":
raise RuntimeError("retirement is out of order")
self.state = "RETIRED"
def dispose(self):
if self.state != "RETIRED":
raise RuntimeError("execution retirement required")
self.private.clear()
self.scratch.clear()
self.state = "DISPOSED"
def rejected(call, expected):
try:
call()
except RuntimeError as error:
assert str(error) == expected
else:
raise AssertionError("invalid transition succeeded")
base = (10, 20, 30)
a, b = Clone("A", 1, base), Clone("B", 1, base)
rejected(lambda: a.admit({"clock"}), "restore checks incomplete")
assert a.state == "RESTORED"
for clone in (a, b):
clone.admit(set(REQUIRED))
clone.start()
assert a.base is b.base
rejected(lambda: a.write(-1, 99), "page is outside the modeled mapping")
a.write(1, 99)
a.scratch["output.csv"] = b"id,value\n1,99\n"
assert (a.read(1), b.read(1), base[1]) == (99, 20, 20)
page_accounting_bytes = (len(base) + len(a.private) + len(b.private)) * PAGE_BYTES
print("page 1: A =", a.read(1), "B =", b.read(1), "base =", base[1])
print("modeled page-accounting KiB:", page_accounting_bytes // 1024)
a.request_cancel()
rejected(a.dispose, "execution retirement required")
assert a.private and a.scratch
rejected(lambda: a.confirm_retired("A", 2), "retirement identity mismatch")
a.confirm_retired("A", 1)
a.dispose()
assert not a.private and not a.scratch and not b.scratch
assert b.read(1) == 20
print("A after confirmed retirement:", a.state)
print("B retains clean base and empty scratch:", not b.scratch)
usable_mib = (256 - 32) * 1024
print("full 2GiB budget quotient:", usable_mib // 2048)
print("50MiB private-page-only quotient:", usable_mib // 50)
print("mean core-equivalents at 3%:", f"{128 * 30 * 0.03:.1f}")page 1: A = 99 B = 20 base = 20
modeled page-accounting KiB: 16
A after confirmed retirement: DISPOSED
B retains clean base and empty scratch: True
full 2GiB budget quotient: 112
50MiB private-page-only quotient: 4587
mean core-equivalents at 3%: 115.2A's write changes its private mapping. B keeps the clean value. The 16 KiB page-accounting total counts one shared three-page base plus A's one private page. This arithmetic assigns a page to each base entry and private entry; operating-system and VMM overhead remain outside the model.
The second result is a cleanup invariant: requesting cancellation leaves A's resources owned until the controller confirms retirement for A's exact generation. The model catches an out-of-order disposal and a stale generation. It doesn't establish that an actual device, process, mount, or remote request has stopped.

Reconcile failures before returning capacity
A controller can lose its reply while a VMM keeps running. Keep that instance uncertain, recover its authoritative state, and stop or adopt it under the same generation. A new controller should reconcile durable ownership with host processes, cgroups, sockets, volumes, and network objects.
| Failure | Evidence to inspect | Response owned by the platform |
|---|---|---|
| Runaway guest processes | Guest process limits, vCPU usage, output growth | Enforce guest limits and host CPU/output budgets |
| Private-memory growth | Host cgroup memory events, resident pages, guest OOM state | Reject new work, stop the affected instance under policy, and preserve host reserve |
| Lost controller heartbeat | Generation-bound process and resource inventory | Reconcile ownership before adoption or termination |
| Stalled page handler or storage | Fault progress, backend errors, instance deadline | Stop admission and retire the affected instance before reclaiming |
| Credential abuse | Broker caller, capability, operation, resource, and upstream result | Deny unauthorized operations and revoke the affected capability |
| Cleanup incomplete | Live process/FD references, mounts, network state, scratch ownership | Quarantine the instance resources until disposal is verified |
For an owned non-root process cgroup in a valid domain configuration, Linux cgroup.kill can terminate the cgroup tree. In a threaded cgroup, writing cgroup.kill fails with EOPNOTSUPP because the operation targets whole processes. Verify process exit and the remaining resource references before returning capacity.[15] A PID number or a timed heartbeat alone doesn't identify every resource safely, especially after PID reuse.
Before allowing a new tenant, check that the old generation has stopped, scratch and writable memory are no longer reachable, capabilities are revoked, and exported artifacts follow their retention policy. Then test that the new instance sees only the clean base. Fault-inject controller crashes, delayed cleanup, repeated events, and cold-page failures in the actual runtime.
The complete deployment evaluation also needs patched host/guest configurations, guest-escape testing appropriate to the threat model, cross-tenant network probes, resource-pressure tests, and measurements of the full readiness endpoint. The local model establishes the stated arithmetic and transitions.
Follow-up questions
How would a sandbox read a 50 GiB model without copying it into its scratch layer?
Use an authorized read-only virtual block device backed by a managed image. Bind the image revision and access policy to the instance. Account for its I/O and resident page-cache working set, even when the underlying file is shared. A filesystem-sharing feature requires explicit support in the chosen VMM and guest configuration.
Why can a garbage collector increase private memory after restore?
Writes to marks, reference counts, or other heap metadata can break copy-on-write sharing. Reads can bring clean pages into RAM without making private modified copies. Measure the runtime's actual write pattern and resulting resident memory.