Pools
This page tells you how the daemon keeps started sandboxes in a pool and how it hands them out. It is for a contributor who must change internal/sandbox/pool.go.
The hand-out is a part of Manager.Create in internal/sandbox/manager.go. The page manager.md describes the other parts of a create.
A pool can also start its sandboxes from a snapshot, see snapshots-and-forks.md.
What a pool is
Section titled “What a pool is”A pool is a set of sandboxes that the daemon keeps started for one image or one snapshot, all with the same shape. A waiting sandbox is a sandbox in a pool that no client owns. When a client creates a sandbox that matches the pool, the daemon hands out a waiting sandbox and does not start a new container. The daemon then starts a replacement in the background.
These numbers come from README.md. The measurement was on the test machine: Docker with gVisor, 20 rounds each.
| Measurement | Median |
|---|---|
| A create without a pool | 139 ms |
| A create that a pool serves | 1.5 ms |
| Time until the pool is full again after one hand-out | 143 ms |
README.md also gives the cost of a waiting sandbox on the test machine, for eight waiting ubuntu:24.04 sandboxes under gVisor.
Docker reported about 11 MiB for each sandbox. The used memory of the machine increased by about 27 MB for each sandbox.
The pool record
Section titled “The pool record”The daemon keeps one poolRecord for each pool, in Manager.pools and in the state file.
| Field | JSON name | Meaning |
|---|---|---|
ID |
id |
pool_ plus random characters. |
Image or Snapshot |
image, snapshot |
What the sandboxes of the pool start from. Only one of the two is set. |
Size |
size |
The number of waiting sandboxes that the pool keeps. |
CPUs, MemoryMB, Network |
cpus, memory_mb, network |
The shape of each sandbox. |
CreatedAt |
created_at |
The time of the first request for the pool. |
Ready |
ready |
The number of waiting sandboxes now. poolView calculates it for each answer. |
LastError |
last_error |
Why the last start for the pool failed. It is empty after a successful start or a new request for the pool. |
filling |
not saved | The number of sandboxes that the fill loop starts for the pool now. |
retryAt |
not saved | The time before which the fill loop does not try the pool again. |
dying |
not saved | True while the daemon deletes the pool. |
A pool has no GPU setting, no environment variables and no volumes of its own.
Its sandboxes mount the default volumes of the daemon, because the fill loop uses a normal Create.
The record of a waiting sandbox
Section titled “The record of a waiting sandbox”A waiting sandbox is a normal sandbox record with these differences:
| Field | Value | Effect |
|---|---|---|
Pool |
The pool id | The record is hidden: Get, List, Kill and use answer “not found”. |
Setup |
The setup mark of the daemon at the start | See “The setup mark”. |
ExpiresAt |
Not set | A waiting sandbox has no timeout, also when the daemon has --max-timeout. |
SuspendAfterSeconds |
0 | The daemon never suspends a waiting sandbox. |
claimed (not saved) |
True while a create asks the engine about it | No other create takes it, and drainPools does not touch it. |
draining (not saved) |
True from the decision to kill it | No create takes it. |
A waiting sandbox does not count for --max-sandboxes. Manager.owned leaves out each record with Pool set.
Create, resize and delete a pool
Section titled “Create, resize and delete a pool”| Operation | HTTP | Manager function |
|---|---|---|
| Create a pool, or change the size of a pool with the same source and shape | POST /v1/pools |
SetPool |
| List the pools, get one pool | GET /v1/pools, GET /v1/pools/{id} |
ListPools, GetPool |
| Change the size by id | PATCH /v1/pools/{id} |
ResizePool |
| Delete | DELETE /v1/pools/{id} |
DeletePool |
SetPool
Section titled “SetPool”SetPool returns immediately. The fill loop starts the sandboxes later.
- It refuses negative
cpusormemory_mb, an image together with a snapshot, and a bad image reference. - It refuses an image reference that names a snapshot image (
isSnapshotImage). - It fills in the defaults: the default image,
DefaultCPUs,DefaultMemoryMB, and network on. - For a snapshot, it refuses a snapshot that is missing,
dyingor temporary. poolLikelooks for a pool with the same image, snapshot, CPUs, memory and network.sizeAlloweddoes the check of the size against--max-pooled.- If such a pool exists,
resizechanges its size. The API answers 200. - If not,
SetPoolmakes a record, saves the state file and callskickPools. The API answers 201.
Because step 3 comes before step 5, a request without an image and a request with the default image name the same pool.
--max-pooled
Section titled “--max-pooled”Config.MaxPooled is the maximum number of waiting sandboxes in all pools together.
The flag --max-pooled of boxfork serve sets it. The default is DefaultMaxPooled, 64.
cmd/boxfork/main.go changes a value of zero or less to -1, which means “keep none”.
sizeAllowed applies these rules:
| Case | Error |
|---|---|
| Size less than 1 | InvalidError: delete the pool to stop it |
MaxPooled is negative |
LimitError: this daemon keeps no waiting sandboxes |
Size more than MaxPooled |
LimitError |
Size plus the sizes of the other pools more than MaxPooled |
LimitError |
The API sends status 429 with the code limit_reached for a LimitError.
The sum uses the Size of each pool, not the number of waiting sandboxes at that moment.
sizeAllowed runs only in SetPool and ResizePool. See “Limits” for what this means after a restart.
Resize
Section titled “Resize”resize sets the new size and saves the state file. If the save fails, it puts the old size back.
It also clears retryAt and LastError. A new request for the pool is a new start: the fill loop tries immediately.
- A larger size: the next pass of the fill loop starts the missing sandboxes.
- A smaller size:
drainPoolscounts the waiting sandboxes from the oldest, and kills those after the new size. The newest ones go.
Delete
Section titled “Delete”DeletePool does these steps:
- It sets
dying, removes the pool fromManager.poolsand saves the state file. If the save fails, it puts the pool back. - It calls
drainPools. The waiting sandboxes of the pool now belong to no pool, anddrainPoolskills them. - For a pool of an image, it returns.
- For a pool of a snapshot, it waits until
fillingof the pool is zero, or until the context ends.
Sandboxes that the pool already handed out stay. They belong to their clients.
The wait in step 4 has a reason. A sandbox that the fill loop starts from a snapshot holds one reference to that snapshot. A client that deletes the pool usually wants to delete the snapshot next. Without the wait, the delete of the snapshot fails with “in use” for a sandbox that the client cannot see.
The wait is only for a snapshot, because of the time that it costs.
A start from a snapshot does not pull an image and is short. A start from an image can be a long pull.
For a pool of an image no snapshot depends on the start, thus DeletePool does not wait.
When the start ends, fillOne sees that the pool is gone. It marks the new sandbox as draining and kills it.
fillOne subtracts filling after that kill, thus the wait in step 4 ends when the sandbox is gone.
The API handler gives DeletePool a context of 2 minutes that does not end when the client stops the request.
What a create must match
Section titled “What a create must match”Manager.take decides if a pool can serve a create. It runs under m.mu.
A pool never serves a create that has one of these:
- A GPU request with a count more than zero.
- Environment variables.
- Volumes of its own.
- The internal marks of a fork copy or of a fill job (
fork,pool,volumesFinal).
For each other create, take makes a Pool value from the request after the defaults and calls poolLike.
All five values must be equal:
| Value | Rule |
|---|---|
| Image | The same text. ubuntu and ubuntu:24.04 are different pools. A request without an image uses the default image. |
| Snapshot | The same snapshot id. For a snapshot request the image is not compared. |
| CPUs | The same number, after the default. |
| Memory | The same number, after the default. |
| Network | The same value. The default is on. |
These parts of a request do not have to match. handOut applies them to the waiting sandbox:
metadatatimeout_seconds: the timeout starts at the hand-out.suspend_after_seconds
One case is special. If the request names an idle time for suspend and the oldest waiting sandbox has UnsavedPaths, take returns nil.
The normal start then refuses the request and gives the reason. See suspend.md.
A create that finds no waiting sandbox is not an error. It continues as a normal create.
The hand-out
Section titled “The hand-out”sequenceDiagram participant C as Client participant M as Manager.Create participant E as Engine participant L as Fill loop C->>M: POST /v1/sandboxes M->>M: checks of the request M->>M: take m.mu, check --max-sandboxes M->>M: take: oldest waiting sandbox of the pool M->>M: claimed = true, pending + 1, release m.mu M->>E: Inspect(container) E-->>M: running, not paused M->>M: take m.mu, claimed = false, pending - 1 M->>M: handOut: Pool empty, metadata, times, save M->>L: kickPools M-->>C: 201 and the sandbox L->>E: start a replacementManager.fromPool does the hand-out in a loop:
takereturns the oldest waiting sandbox of the pool, or nil. With nil,fromPoolreturns andCreatestarts a container.fromPoolsetsclaimedon the record and adds one tom.pending. The create then counts for--max-sandboxeswhile the lock is free.- It releases
m.muand callsEngine.Inspectfor the container. - It takes
m.muagain, clearsclaimedand subtracts one fromm.pending. - If the context of the request ended, it returns that error.
- If the record is gone, it starts again from step 1.
- If the container does not run, see “A waiting sandbox whose container died”.
- If not, it calls
handOut.
waiting gives the candidates for step 1. It lists the records of the pool that are not dying, not draining and not claimed.
Each one must have the state running and the current setup mark. The order is by CreatedAt, then by id.
handOut changes the record under m.mu:
- It clears
Pool. The record is now visible, and it counts for--max-sandboxes. - It sets
Metadatafrom the request. - It sets
CreatedAtandlastUsedto the current time. - It sets
ExpiresAtfrom the timeout of the request. - It sets
SuspendAfterSecondsto the value that a new start gives. - It saves the state file.
If the save fails, restoreFields puts all these fields back. The sandbox waits again, and the create fails with the error.
After a successful hand-out, fromPool calls kickPools, and the fill loop starts a replacement.
The engine inspect
Section titled “The engine inspect”The daemon learns that a container died only in Reconcile, each 20 seconds.
A waiting sandbox whose container was killed, or that used too much memory, can thus still look good in the records.
The inspect at the hand-out closes this gap: the daemon asks the engine about that one container before it gives the sandbox to a client.
The cost is one engine call for each hand-out. The 1.5 ms in the table above includes it.
A waiting sandbox whose container died
Section titled “A waiting sandbox whose container died”fromPool treats a waiting sandbox as dead in each of these cases:
Inspectreturns an error.- The container does not run.
- The container is paused.
- The state of the record is not
running.
fromPool then sets draining on the record, writes a line to the log and calls kickPools.
It starts again from step 1 and tries the next waiting sandbox.
The next pass of the fill loop kills the dead sandbox and starts a replacement.
If the pool has no other waiting sandbox, the create continues as a normal create. The client gets a sandbox in both cases.
The setup mark
Section titled “The setup mark”Manager.setupOf makes a mark of all that the daemon gives a sandbox and that is not in the request.
New calculates it one time and stores it in m.setup.
The mark is the first 16 hexadecimal characters of a SHA-256 hash of these values:
Config.Version, the build of the daemon.Config.IsolationandConfig.Runtime.Config.DNS.- The default volumes, after
checkMounts. Config.PidsLimit.- The bytes of the helper for
amd64and forarm64.
Create writes the mark into Setup of each record that it starts for a pool. The state file keeps it.
waiting lists only records whose Setup is equal to m.setup, and drainPools kills the others.
The fill loop
Section titled “The fill loop”Manager.WatchPools runs in its own goroutine. Manager.Watch starts it.
It calls FillPools, then waits for one of three events: the end of the context, a signal on poolKick, or 10 seconds.
kickPools puts one signal on poolKick and does not wait when one is already there.
FillPools calls fillPass again and again while fillPass reports that more sandboxes are missing.
flowchart TD A[WatchPools: start, kick or 10 seconds] --> B[fillPass] B --> C[drainPools: kill the waiting sandboxes that no pool keeps] C --> D[For each pool, oldest first: need = Size - waiting - filling] D --> E[Take one job from each pool in turn, maximum poolBatch] E --> F{Jobs in the batch?} F -- no --> G[Wait for the next event] F -- yes --> H[Run fillOne for each job, maximum poolParallel at the same time] H --> I{Jobs that did not fit in the batch?} I -- yes --> B I -- no --> G G --> AOne pass
Section titled “One pass”fillPass does these steps:
- It calls
drainPools. - Under
m.mu, it goes through the pools from the oldest. It skips a pool that isdyingor whoseretryAtis in the future. - For each pool, the number of missing sandboxes is
Sizeminus the waiting sandboxes minusfilling. - It makes one job for each missing sandbox. A job is a
CreateRequestwith the shape of the pool, no timeout, no suspend and thepoolmark. - It takes the jobs round-robin: one from each pool in turn, until the batch has
poolBatch(8) jobs. - It adds one to
fillingof the pool for each job in the batch. - It runs the jobs with a maximum of
poolParallel(4) at the same time, and waits for all of them. - It returns true if jobs stayed outside the batch.
The round-robin order has a reason: a large pool must not delay a small pool. TestALargePoolDoesNotHoldUpASmallOne holds this.
The batch has a reason too. Between two batches drainPools runs again, and a pool that a client created in that time gets its turn.
filling makes two passes at the same time safe. A sandbox counts in filling until it waits in the pool or is gone.
TestPassesAtOnceDoNotOverfillAPool holds this.
One start
Section titled “One start”fillOne starts one sandbox:
- It skips the job if the pool is gone, is
dying, or has aretryAtin the future. - It calls
Manager.Createwith the job. - If the create fails, it stores the error text in
LastError. It setsretryAtto the current time pluspoolRetry(30 seconds). - If the pool is gone after the create, it marks the new sandbox as
drainingand kills it. - If not, it clears
LastError. - At its end it subtracts one from
filling.
Step 1 has this effect: after one failure, the other jobs of the same pool in the pass do not start.
The jobs that already run at that moment continue.
fillOne writes the error to the log only when the text is different from the last one.
It records no error when the context of the daemon ended, because a daemon that stops did not find a defect.
drainPools
Section titled “drainPools”drainPools kills the waiting sandboxes that nothing keeps. It goes through the records from the oldest and skips each claimed record.
| A waiting sandbox goes when | Cause |
|---|---|
draining is already set |
An earlier decision, for example from fromPool. |
Its pool is not in Manager.pools, or is dying |
A client deleted the pool. |
Its Setup is not m.setup |
The daemon restarted with a different build or different settings. |
Its state is not running |
For example, Reconcile found the container paused. |
It is after the first Size waiting sandboxes of its pool |
A client made the pool smaller. |
drainPools sets draining under m.mu, the same lock under which take runs.
Thus a create never gets a sandbox that the daemon decided to kill.
If a kill fails, draining stays set, and the next pass tries again.
What a restart does
Section titled “What a restart does”Pools and waiting sandboxes are in the state file. New loads them.
| Item | What New does |
|---|---|
| A pool record | Keeps it. It sets Ready to zero and clears LastError. |
| A pool with a size less than 1 | Drops it. |
| A pool whose snapshot is not in the loaded snapshots | Drops it and writes a line to the log. |
| A waiting sandbox whose container runs | Keeps the record, with Pool and Setup from the state file. |
| A waiting sandbox whose container is gone or stopped | Drops the record, as for each other sandbox. |
filling, retryAt, claimed, draining |
Not saved. All start at zero. |
After a restart with the same build and settings, the setup mark is the same.
A create can get a waiting sandbox from before the restart, also before the first pass of the fill loop.
TestPoolsSurviveARestart holds this.
After a restart with a different build or different settings, the setup mark is different.
The settings that change it are the ones in the list under “The setup mark”: for example --dns, a default --volume, or the isolation.
waiting then lists none of the old sandboxes, thus no create gets one and ready is zero.
The first pass of the fill loop kills the old sandboxes and starts new ones.
TestWaitingSandboxesStartedUnderOtherSettingsAreReplaced and TestWaitingSandboxesOfAnotherSetupAreReplaced hold this.
Waiting sandboxes of a pool that is not in the state file go in the first drainPools.
Reference: constants
Section titled “Reference: constants”| Name | Value | Meaning |
|---|---|---|
DefaultMaxPooled |
64 | The default of --max-pooled. |
poolParallel |
4 | The maximum number of starts for pools at the same time. |
poolBatch |
8 | The maximum number of starts in one pass. |
poolRetry |
30 seconds | The wait after a failed start for a pool. |
| The period of the fill loop | 10 seconds | A literal in WatchPools. |
The poll period of DeletePool |
10 ms | A literal in DeletePool. |
| The length of the setup mark | 16 characters | A literal in setupOf. |
Invariants that a change must keep
Section titled “Invariants that a change must keep”- A client never gets a waiting sandbox whose container the engine did not report as running in that same create.
- A client never gets a waiting sandbox with a setup mark different from the mark of the daemon.
- Two creates never get the same waiting sandbox.
claimedandm.mumake this sure. - The daemon never hands out a
drainingordyingsandbox. - A waiting sandbox is hidden. No client can run a command in it, list it or kill it.
- A waiting sandbox has no timeout and no suspend. Both start at the hand-out.
- A waiting sandbox does not count for
--max-sandboxes. The handed-out sandbox does, and the check runs before the hand-out. - A hand-out is in the state file before the client gets the answer. If the save fails, the sandbox still waits.
- A pool that cannot serve a create does not make the create fail.
Sizeminus waiting minusfillingis the only source of new starts. No pass starts more than that.- A delete of a pool leaves no waiting sandbox of that pool, also when a start was in progress.
- A snapshot with a pool cannot be deleted.
Failure cases
Section titled “Failure cases”| Failure | What the daemon does |
|---|---|
| The image of a pool cannot be pulled | LastError shows the reason. The fill loop tries again after 30 seconds. |
| The snapshot image of a pool is gone from the machine | Each start fails with ErrSnapshotNotFound in LastError. The pool stays until a client deletes it or the daemon restarts. |
| The container of a waiting sandbox died | The inspect finds it at the hand-out, or Reconcile finds it. The fill loop starts a replacement. |
| The engine does not answer the inspect | The daemon treats the sandbox as dead and kills it. |
| A waiting sandbox was paused behind the daemon | Reconcile marks the record as paused. waiting then does not list it, and drainPools kills it. |
The save in handOut fails |
The fields go back. The create fails with “recording the sandbox”. |
| The request ends in the middle of the inspect | fromPool clears claimed and returns the context error. The sandbox waits again. |
The kill of a draining sandbox fails |
The sandbox stays draining. Each pass tries again. |
| A client deletes the pool while a sandbox starts for it | fillOne kills the new sandbox after its start. |
A client deletes the pool while a create has a sandbox claimed |
drainPools skips the record. The hand-out continues, and the sandbox belongs to the client. |
The save in SetPool, resize or DeletePool fails |
The change is undone in memory, and the client gets the error. |
| The daemon stops in the middle of a start | The create fails with a context error. fillOne records no LastError. |
How to change it
Section titled “How to change it”- Decide first if your change touches the shape of a pool. The shape is what
poolLikecompares. - If you add a field to the shape, add it to
Pool,PoolRequest,poolLike,takeand the job infillPass. - Add the same field to the
setPoolhandler ininternal/api/server.go. - Make sure that old state files load. A pool without the new field must get the default.
- If you add a create option that a waiting sandbox cannot have, add it to the first
ifoftake. - If you add a daemon setting that changes a new container, add it to the hash in
setupOf. - If you add a field that
handOutchanges, add it tohandedFields,snapshotOfFieldsandrestoreFields. - If you add a reason to kill a waiting sandbox, add it to the
switchindrainPools. - Do not call the engine with
m.muheld. Use theclaimedmark for the time without the lock. - Add tests to
pool_test.goorpool_more_test.go. Usee.m.FillPools(ctx)to run the fill loop in a test. - Do a break-it check for each new rule in
take,waitingordrainPools. - Run
make test. - Run
scripts/proof/pool.shon a machine with a real engine, if you have one.
Caution: Do not hand out a waiting sandbox without the check of Setup. The client then gets a sandbox with the helper, the isolation or the volumes of an earlier build.
Where the tests are
Section titled “Where the tests are”| File | Most important tests |
|---|---|
| internal/sandbox/pool_test.go | TestAPoolHandsOutASandboxThatIsAlreadyRunning, TestOnlyARequestForExactlyThePoolsSandboxIsServedFromIt, TestAskingAgainForAPoolChangesItsSize, TestDeletingAPoolRemovesWhatWaitsAndKeepsWhatWasHandedOut, TestAPoolOfASnapshot, TestWaitingSandboxesAreNotCountedAgainstTheLimit, TestPoolsSurviveARestart, TestAPoolThatCannotBeFilledSaysWhyAndWaits, TestAHandOutThatCannotBeRecordedIsNotOne, TestManyRequestsAtOnceEachGetTheirOwnSandbox |
| internal/sandbox/pool_more_test.go | TestAWaitingSandboxWhoseContainerDiedIsNotHandedOut, TestAWaitingSandboxTheEngineCannotBeAskedAboutIsNotHandedOut, TestAWaitingSandboxPausedBehindTheDaemonsBackIsReplaced, TestTheOldestWaitingSandboxGoesFirstAndTheNewestIsGivenUp, TestTheHostLimitsWhatAllItsPoolsKeepReady, TestDeletingAPoolWaitsForTheSandboxesBeingStartedForIt, TestALargePoolDoesNotHoldUpASmallOne, TestPassesAtOnceDoNotOverfillAPool, TestAfterOneFailureTheRestOfAPassIsNotTried |
| internal/api/pool_test.go | The HTTP routes for pools. |
The proof script scripts/proof/pool.sh does the checks on a real engine and measures the times. It covers a pool of an image, a pool of a snapshot and a burst larger than the pool. It also covers the refill, a restart of the daemon, dead containers, a resize and a delete.
Limits
Section titled “Limits”- The numbers on this page come from one test machine: Docker with gVisor on arm64, in a nested virtual machine. Nothing ran on x86_64.
- A pool has no GPU setting. A create with a GPU always starts a new container. Nothing ran on a machine with an NVIDIA GPU.
- A waiting sandbox started from its image as the image was at that moment. If you pull a newer image with the same name, delete the pool and create it again. The setup mark does not include the image.
- The image name is compared as text. A create for
ubuntudoes not get a sandbox from a pool forubuntu:24.04. - A waiting sandbox is a started container. It uses memory while it waits.
sizeAllowedruns only when a client creates or changes a pool. After a restart with a smaller--max-pooled, or with--max-pooled 0, the daemon still fills the pools in the state file to their sizes. No test covers this case.- The setup mark does not include the default CPU, the default memory or the default image. A pool keeps the values that it got when a client created it.
takelooks only at the oldest waiting sandbox for theUnsavedPathsrule.- The inspect at the hand-out shows the state of the container at one moment. A container that dies after the inspect goes to the client, as for each sandbox.
- A pool whose starts always fail stays, and tries again each 30 seconds, until a client deletes it.