DEV Community

Cover image for Resuming a 64 GiB Firecracker sandbox in under a second
Thomas Metz
Thomas Metz

Posted on

Resuming a 64 GiB Firecracker sandbox in under a second

Most AI agent sandboxes are small. 2 vCPU and a few GiB of RAM are enough to run some Python, call a tool and return a result. But some agent work needs a lot more memory: a data frame with tens of millions of rows, DuckDB over a large Parquet file, a monorepo build, a full test suite, an in-memory search index.

I run getrollouts.dev, a hosted sandbox service built on the open-source E2B runtime (Firecracker microVMs). This week I added sandboxes with 32 and 64 GiB RAM. Starting them was easy. Pausing and resuming them was not, and the reason turned out to be interesting enough to write down. If you self-host the E2B runtime, the fix may save you a day.

The symptom

Pause and resume is one of the best features of E2B-style sandboxes: you freeze the whole VM, memory and running processes included, stop paying for compute, and continue later exactly where you left off.

With small sandboxes this is fast. With a 32 GiB sandbox that had 24 GiB of data in memory, my test looked like this:

from e2b_code_interpreter import Sandbox

sbx = Sandbox.create("code-interpreter-32g")
sbx.run_code("import numpy as np\na = np.ones(24 * 2**27)")   # 24 GiB in memory

sbx.pause()                       # returned after 0.2 s
sbx = Sandbox.connect(sbx.sandbox_id)   # took 53 to 58 s
Enter fullscreen mode Exit fullscreen mode

The pause returned immediately, but resuming right after it took almost a minute. The 64 GiB version did not resume at all. It failed after exactly 60 seconds.

What it was not

My first guess was disk speed. The snapshot of a 24 GiB sandbox is about 26 GB, and if it lands on a slow disk, resuming waits for it. So I moved the snapshot storage to local drives that write more than 2 GB/s.

The resume time did not change. Still 53 seconds.

The network was not it either: during the resume nothing was read over the network. And giving the kernel more free memory for the page cache changed nothing.

What it was

Two things, both visible once I looked at the orchestrator instead of the disks:

  1. The resume waits for the pause to finish writing. The pause call returns quickly because the runtime copies the VM memory into its snapshot cache in the background. A resume that arrives while this copy is still running waits until it is done.
  2. The copy is limited by one CPU core, not by the disk. One orchestrator thread sat at 100 % on a single core, and the kernel writeback thread for the target disk at about 95 %. Together they pushed about 1 GB/s, half of what the drives can take. On top of that the snapshot is written twice: once into the local cache, then again into template storage.

So a 24 GiB sandbox had to wait for roughly 26 GB to be copied by a single thread before it could come back. A 64 GiB sandbox needed about 100 seconds, and the runtime gives the guest agent 60 seconds (ENVD_TIMEOUT) to answer after a resume. That was the failure at exactly 60 s.

You can see both effects with nothing more than top -H and the orchestrator log during a resume: the load snapshot call itself takes milliseconds, the time is spent before it starts.

The fix: two flags that already exist

The E2B runtime is open source, so I read the snapshot code. It already has a solution, behind feature flags that are off by default:

  • memfd-dedup-inflight-serve: a resume that overlaps an in-flight snapshot copy serves memory pages straight from the still-mapped memory of the paused VM, instead of waiting for the copy.
  • memfile-diff-dedup: needed for the first one. It also lets the snapshot be written with direct I/O, past the page cache.

A third one, memfd-background-copy, is already on by default. That is why the pause call returns quickly.

With these two flags on, the same test looks very different:

Resume of a paused sandbox before after
32 GiB, 24 GiB in use, right after the pause 53 to 58 s 0.3 to 6 s
64 GiB, 48 GiB in use, right after the pause failed after 60 s 0.4 to 6.4 s
either size, minutes after the pause under 1 s under 1 s

Data was intact in every run (a checksum over the whole array after the resume).

One honest caveat: memory is loaded on demand after a resume. If your code touches all 48 GiB right away, that first full pass takes about a minute. Code that only needs part of its memory continues immediately.

Setting the flags without LaunchDarkly

The runtime reads these flags from LaunchDarkly. If you self-host without a LaunchDarkly account, every flag simply has its built-in default, and there is no config file to change them.

But the client respects LAUNCH_DARKLY_BASE_URL, and any flag it does not find falls back to the built-in default. So a tiny local server that speaks the LaunchDarkly streaming protocol and serves only the flags you want is enough. This is the core of mine:

import json, time
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler

FLAGS = {
    "memfd-dedup-inflight-serve": True,
    "memfile-diff-dedup": {"enabled": True, "bestEffort": True, "directIO": True},
}

def flag(key, val):
    return {"key": key, "version": 1, "on": True, "variations": [val, {} if isinstance(val, dict) else not val],
            "fallthrough": {"variation": 0}, "offVariation": 0, "targets": [], "rules": [],
            "prerequisites": [], "salt": key, "deleted": False}

DATA = {"flags": {k: flag(k, v) for k, v in FLAGS.items()}, "segments": {}}

class H(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path.startswith("/all"):            # streaming endpoint
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.end_headers()
            self.wfile.write(b"event: put\ndata: " + json.dumps({"path": "/", "data": DATA}).encode() + b"\n\n")
            self.wfile.flush()
            while True:                              # keep the stream open
                time.sleep(30); self.wfile.write(b":\n\n"); self.wfile.flush()
        self.send_response(404); self.end_headers()
    def do_POST(self):                               # analytics events: accept and drop
        self.rfile.read(int(self.headers.get("Content-Length") or 0))
        self.send_response(202); self.end_headers()

ThreadingHTTPServer(("127.0.0.1", 8099), H).serve_forever()
Enter fullscreen mode Exit fullscreen mode

Then start the orchestrator with:

LAUNCH_DARKLY_API_KEY=local
LAUNCH_DARKLY_BASE_URL=http://127.0.0.1:8099
Enter fullscreen mode Exit fullscreen mode

The log should show LaunchDarkly streaming is active. You will also see warnings about unknown feature keys for every flag you did not define. They are harmless: those flags keep their defaults.

Two notes if you try this. These flags are off by default for a reason, so test on one machine first and keep a way back (removing the two environment variables and restarting the orchestrator). And check that small sandboxes still behave: in my tests a small sandbox still paused in 0.2 s and resumed in 0.3 s.

Large sandboxes on getrollouts.dev

This is now live. Every paid account can start code-interpreter-32g (8 vCPU, 32 GiB) and code-interpreter-64g (8 vCPU, 64 GiB), or build its own template up to that size, at the same per-second rates as small sandboxes ($0.040 per vCPU-hour plus $0.013 per GiB-hour): $0.74 per hour for 32 GiB and $1.15 per hour for 64 GiB, prepaid, no monthly fee. Paused sandboxes cost nothing. Large self-serve sizes are still rare among hosted sandbox services, where more memory often means a sales call.

# export E2B_API_KEY=...  E2B_DOMAIN=getrollouts.dev
from e2b_code_interpreter import Sandbox

sbx = Sandbox.create("code-interpreter-64g", timeout=4 * 3600)
sbx.run_code("import duckdb, pandas as pd")
sbx.pause()      # billing stops, state is kept
Enter fullscreen mode Exit fullscreen mode

Details, prices and limits: getrollouts.dev/large-memory. The official E2B SDKs work unchanged.

Next: what you actually do with 64 GiB

This post is about the plumbing. The obvious follow-up question is whether agents really need this much memory, and what it costs per task. In the next post I will run real workloads in these sandboxes and publish the numbers: an agent analysing a large Parquet dataset with DuckDB and pandas, a full build and test run of a large repository, and a long agent session that is paused and resumed several times along the way. Runtime, peak memory, resume times and the cost of each run, including the cases where a small sandbox would have been enough.

If you have a workload you would like to see in that test, tell me in the comments.

If you self-host the E2B runtime and hit slow resumes with big sandboxes, I would also like to hear whether the flags help you.

getrollouts.dev is an independent service and is not affiliated with E2B.

Top comments (0)