POST /sandboxes can resume instead of paying a cold boot. The mechanism is small, but it sits at the intersection of the snapshot store, the sandbox table and the create path, and each has its own invariants. This post describes how the pieces fit together. The user-facing description and the latency numbers live in the docs page Internals: pre-warmed pools; this post is about code structure.
The four pieces
The feature is split into four daemon files, each with one concern. Three live undercore/crates/daemon/src/lifecycle/ and the HTTP surface under http/routes/.
lifecycle/pool.rs has no dependency on AppState. That is deliberate: every transition (push_warm, take_warm, record_claim, record_release, needs_replenish) is a plain method on a struct, which is why the module carries a dozen unit tests that run under cargo test --workspace with no KVM. Everything that needs a real VM (resume, boot, snapshot) lives in the modules around it and is exercised by the 18-pool.sh topic of the integration suite.
The pool model
A pool is identified by a caller-chosen string id and described byPoolConfig:
PoolConfig, core/crates/daemon/src/lifecycle/pool.rs:28.)
Two numbers shape behavior, and they mean different things:
warm_countis a target for how many snapshots sit ready. It is not a cap. A claim that arrives with nothing warm does not fail; it cold-creates.max_countis an optional ceiling on live instances of the profile: warm snapshots plus sandboxes that were claimed from, or cold-created under, the pool and are still alive.Nonemeans unbounded. When it is set, a claim at the ceiling queues rather than exceeding it.
max_count of 0 (omit the field for unbounded), rejects an empty id, rejects an unknown image_id, and returns 409 for a duplicate pool id. warm_count: 0 is accepted, since it is not incorrect, only pointless.
Matching is plain equality on resolved values
A request is matched against pools byPoolKey, which holds image_id, vcpu_count and mem_size_mib. Both sides of the comparison are resolved values. create_pool runs the same resolve_resource_override helper the create path uses, so a pool created with no resource fields stores the daemon’s configured defaults, and a request with no resource fields resolves to those same defaults. The comparison is then derived PartialEq, with no “is this field defaulted” logic anywhere.
The alternative, storing Option<u8> overrides in the pool and resolving at match time, was rejected: it would thread daemon-default lookups through every comparison and would make two pools that resolve to the same profile look different.
What disqualifies a request
A request that carriesdrives, or any rate_limit, never matches a pool. Both are applied to the VM at boot time, and a warm snapshot was booted with neither, so resuming it cannot add them. The create path checks this before it even builds a PoolKey:
create_sandbox_core, core/crates/daemon/src/http/routes/sandbox.rs:154.)
Such a request also never queues on a pool. If it did, it could wait up to 30 seconds for a slot it could never legitimately use. It goes straight to a cold create.
Egress policy is different. It does not disqualify a claim, because it is host-side iptables applied after boot rather than state baked into the VM. claim_from_pool takes the resolved policy as an argument and applies it to the resumed sandbox’s tap device after the health check. A failure to apply it is fatal for the claim (the sandbox is torn down): silently returning an unrestricted sandbox when the caller asked for restrictions would be a security gap. Per-sandbox env is likewise applied at claim time rather than baked into the warm instance.
The replenisher
pool_replenisher::run (lifecycle/pool_replenisher.rs) is a fixed-interval loop, spawned unconditionally from main.rs:
lifecycle/pool_replenisher.rs.)
An idle tick with no pools configured is one empty lock-and-filter. The interval is a constant, not an environment variable.
Each tick, replenish_once takes the AppState::pools lock, collects clones of the PoolConfig of every pool whose needs_replenish() is true, and releases the lock before doing any slow work. It then processes the due pools sequentially, producing at most one warm slot per pool per tick. A large warm_count therefore fills in gradually instead of spiking boot load.
Producing one warm slot reuses the ordinary lifecycle operations rather than a pool-specific boot path:
create_sandbox_corewith a placeholder request: no name, a single tagsandkiln.pool=<pool id>, the pool’s resolved vCPU and memory, its image, no drives, no rate limit, no egress, no env. This is a full normal create, so it goes through the same lease, rootfs clone and boot sequence.snapshot_and_stop(http/routes/snapshot.rs), the same function thatDELETE /sandboxes/:id, the idle reaper and orderly shutdown use. It returns a snapshot id that is now a normal entry inAppState::snapshots.- Under the
poolslock again,push_warm(snapshot_id).
VecDeque<String>. That keeps ownership simple: the snapshot lives in the snapshot table and on disk, and the pool holds a reference to it. The snapshot mechanics themselves are covered in the snapshots, resume and fork post (06).
effective_warm_target makes a bounded pool respect its own ceiling:
Pool, lifecycle/pool.rs:88.)
With max_count: 3 and one claimed instance, only two slots of headroom exist, so the target is min(warm_count, 2). saturating_sub matters: a race can leave claimed above max_count, and an unchecked subtraction there would panic in a debug build or wrap in release.
Failure inside replenishment
Each step can fail without leaving anything behind that the system does not understand.
The last row is the one that needs thought. Boot plus snapshot takes long enough for an operator to
DELETE /pools/:id in the middle. The replenisher re-checks membership at the moment it pushes, inside the same lock acquisition, and if the pool is gone it deletes the snapshot instead of leaving it orphaned.
The loop does not back off on failure. A persistently failing boot is retried every 2 seconds and logs a warning each time. That is a simplification, not a designed behavior.
The claim path
Resolving: lock, decide, unlock, await
resolve_pool_claim is the consumer half of the queue. Its contract is stated in its doc comment: never hold the pools lock across an await. The structure that satisfies it is “lock, decide or clone the Notify, unlock, optionally await, loop with fresh state”:
resolve_pool_claim, lifecycle/pool_claim.rs:53.)
There are three outcomes:
Warm { pool_id, snapshot_id }: a snapshot was popped and a slot was reserved, atomically under one lock acquisition. No other claimant can observe the pool between the two.ColdSlot { pool_id }: nothing warm, butclaimed < max_count(or there is nomax_count), so a slot is reserved and the caller cold-creates, attributed to this pool.NoPool: no pool matches the key.
Notify under a single deadline of POOL_QUEUE_TIMEOUT, 30 seconds. When the deadline passes, it returns AppError::ServiceUnavailable, which the error mapping turns into HTTP 503.
Notify as a condition variable
Pool::notify is a tokio::sync::Notify used the way a condition variable is used. push_warm and record_release call notify_waiters(). Every waiter wakes, loops, re-takes the lock, and re-evaluates the real condition. An extra wakeup costs one re-check. That is why notify_waiters is used instead of notify_one: a single-wakeup scheme would have to guarantee that the woken waiter is one that can proceed. Broadcast plus re-check sidesteps that.
A notify_waiters that races the timeout is not lost. The loop’s next iteration re-reads the pool state first, so a slot that freed up in the gap is found directly.
The alternatives were polling on a short sleep (wasteful, and it adds latency to every wake) and a semaphore sized to max_count. A semaphore models slots well, but a claim must atomically choose between taking a warm snapshot and reserving a cold slot, and the warm target depends on claimed. Keeping the counters in Pool under the existing mutex and using Notify purely as a wakeup signal keeps one source of truth.
The slot lifecycle and PoolClaimGuard
Reserving a slot (record_claim) increments claimed before any resume or boot begins. That stops two concurrent claimants from both seeing “one slot left” and over-committing during the window before a Sandbox is inserted. But a reservation that leaks is worse than none, since it permanently shrinks a bounded pool. PoolClaimGuard makes the release automatic:
PoolClaimGuard, lifecycle/pool_claim.rs:91.)
The guard is created right after resolve_pool_claim returns a slot, and commit() is called only when a live Sandbox durably owns the slot. From then on the slot is released by the stop paths: destroy_sandbox_by_id and snapshot_and_stop both check Sandbox::source_pool_id and call record_release on the matching pool, which also wakes queued waiters.
The Drop-based design means every early return and every ? in the claim and cold-create paths is correct by construction, with no per-exit cleanup code to forget. create_sandbox_cold builds the same guard for the ColdSlot case, so both kinds of reservation share one release mechanism. If the pool is deleted while a guard is outstanding, get_mut returns None and the drop does nothing.
The claim itself
claim_from_pool takes the reserved snapshot id and does four things in order.
1. Resume. It calls resume_snapshot_by_id(state, snapshot_id, true), the same function behind the snapshot resume endpoint. The true is retain_history: the consumed checkpoint is retired into the snapshot history rather than deleted. The code comment explains why: from inside the claim there is no way to tell “the pool’s own warm checkpoint” from any other, so both are kept. Because the checkpoint is kept, resume_snapshot_by_id clones the warm snapshot’s rootfs before resuming and the claimed VM runs on that private clone through rootfs_override, never on the retired checkpoint’s disk (http/routes/snapshot.rs:481-502; post 27 explains why). The clone is a reflink on a suitable filesystem, so it adds little to a claim.
2. Health check. It runs Request::Exec { command: "true", .. } through sandbox.vm.call, inside spawn_blocking_in_current_span because it is blocking vsock I/O. This exists because a resumed guest kernel can panic shortly after restore, and the process then exits. The failure was first seen building this feature, at a rate the code comment records as one in three to two in three resumes, with a divide-by-zero trap in the console log. Later loops are much cleaner: 160 of 160 resume and re-snapshot cycles were clean in isolated and 4-way-parallel runs. What still shows up is a different panic (“Attempted to kill the idle task!”, about 20ms after restore) that appears only in the full parallel integration suite (see the known limitation below). The root cause of either is unconfirmed, so a resume is untrusted until the guest agent answers. The code comments in pool_claim.rs and create_sandbox_core still quote the older rate, and I did not re-measure it.
3. Teardown on failure. A failed check calls destroy_unhealthy_claim, (lifecycle/pool_claim.rs:252), which removes the sandbox from the table, releases the network lease, deletes the rootfs clone, and stops the VM with Vm::force_stop:
sandkiln-vmm, core/crates/vmm/src/vm/mod.rs:244.)
stop first asks the guest to sync so unflushed writes to attached drives are not lost, and that call has its own timeout budget (the source comment says about 5 seconds). For a VM the health check just proved is not answering, the sync cannot succeed and would only burn that budget before the kill. force_stop goes straight to the kill and socket cleanup. The slot guard is not committed, so the slot is released on return.
4. Identity overwrite. The warm snapshot carries the replenisher’s placeholder identity. For a healthy guest the claim replaces it with the caller’s:
- Egress is applied if requested (fatal on error, as above).
Vm::update_metadatarewrites the guest-visible MMDS document with the realid,nameandtags.- The
Sandboxrecord gets the caller’s tags, name,created_at,egress,envandsource_pool_idin one critical section, and thenrecord_createdand the created-sandbox metric fire.
PATCH fails. update_metadata redoes the whole sequence:
sandkiln-vmm, core/crates/vmm/src/vm/mod.rs:230.) What MMDS is and why the guest reads identity from it is covered in Internals: MMDS.
Because PUT /mmds/config can be rejected just after a resume even when the resume fully succeeded, the daemon wraps the call in a bounded retry: UPDATE_METADATA_MAX_ATTEMPTS is 10, with UPDATE_METADATA_RETRY_DELAY of 300 ms between attempts, so about 3 seconds in total. The loop runs inside spawn_blocking, which is why it can use std::thread::sleep without stalling the runtime. It takes the sandbox-table lock per attempt, so the lock is never held through a sleep.
If every attempt fails, the failure is non-fatal. The guest already passed its health check, so the result is a sandbox with stale MMDS content and a warning in the log. This is the explicit asymmetry with egress: stale metadata is a degraded sandbox, while a missing egress policy is a security hole.
Fallback and the bounded retry
Whenclaim_from_pool fails (resume error, health check, egress application), create_sandbox_core does not return the error. It loops up to MAX_POOL_CLAIM_ATTEMPTS (3) times, re-running resolve_pool_claim. Each failed attempt has already released its slot through the guard, so the next iteration competes for capacity honestly, and a fallback cold create still counts against max_count if it comes back as ColdSlot.
If the loop exhausts its attempts, or no pool matches, the request falls through to create_sandbox_cold with no pool attribution. A pathological run of three consecutive bad warm snapshots therefore yields an unattributed sandbox that is not counted against the pool. The code comment calls this an accepted rare edge case, and it is the one place the max_count accounting is knowingly loose.
The cost of an unlucky resume is visible to the caller only as latency. The caller receives either a verified sandbox id or the error of a cold create.
What is and is not durable
Pool configuration lives only inAppState::pools, an in-memory Mutex<HashMap<String, Pool>>. Pools are inserted only by the create handler, and nothing reads them back at startup. The consequences follow directly:
- After a daemon restart there are no pools.
GET /poolsis empty until an operator re-creates them. - The warm snapshots are on disk like any snapshot.
reconcileinsnapshots/held.rsrebuildsAppState::snapshotsfrom the filesystem at startup, so they come back as ordinary snapshots, but no code re-links them to a pool. They are not lost, and they are not claimable either: they sit in the snapshot list until deleted. - A sandbox claimed from a pool is snapshotted by orderly shutdown like any other live sandbox (see the daemon internals post), and
snapshot_and_stopends its pool membership, so after a restart it is an ordinary snapshot and theclaimedcounter would have nothing meaningful to restore. After aSIGKILLor crash it is simply gone.
POST /pools at startup is cheap, and a persisted design would first have to say what claimed means once every live sandbox has been orphaned. It is a deferred feature, not an implied one.
The deletion path shows the ownership model. delete_pool removes the Pool from the map under the lock, wakes every queued waiter once so they re-check and find no matching pool (they then cold-create instead of waiting out 30 seconds), and drains take_warm() calling delete_snapshot_by_id for each snapshot. A cleanup failure for one snapshot is logged and the loop continues. A snapshot that a claimant took before the delete acquired the lock is owned by that claimant’s in-flight resume, not by the pool.
Concurrency summary
Three kinds of caller touch a pool: HTTP handlers (
resolve_pool_claim, create, delete), the replenisher, and the stop paths calling record_release. All of them use short critical sections on one mutex, and the only cross-task signaling is the Notify. No code path holds the pools lock while acquiring another lock.
Testing
The pure logic inpool has unit tests for FIFO ordering, key inequality across image and resource differences, max_count blocking and release, saturating release, and the effective warm target arithmetic including a claimed above max_count. Those run in the cargo test --workspace pass (340 tests across the crates as of 2026-11-24, 222 of them in the daemon).
The integration suite (about 320 checks in total across 25 topics) covers live behavior in 18-pool.sh: a real background replenishment, a claim from the warm pool, MMDS reflecting the claimer’s name (polled on the guest side), a second claim at max_count queueing, and the queued claim waking promptly once a slot frees. SANDKILN_INTEGRATION_TEST_ONLY=pool runs just that topic. The topic polls for real replenishment rather than sleeping a fixed time, because it runs concurrently with other topics that compete for host resources.