Dynamic CPU & Memory Resize
Normally, every sandbox created from a CubeSandbox template inherits the exact CPU and memory baked into that template's MicroVM snapshot. If a workload needs 2C/1G, 4C/2G, and 8C/4G tiers, you would otherwise have to build, distribute, and maintain three separate templates.
With dynamic CPU and memory resize, you can declare optional hotplug ceilings (maxCpu and maxMemory) when building a template, and then specify a larger cpu and/or memory when creating a sandbox from that template. Sandboxes still restore from the same warm snapshot and hotplug the additional vCPUs and RAM before startup hooks (postStart), readiness probes, and SDK commands run.
How It Works
- Template build (
POST /templates): The template boots and takes its snapshot at the baselinecpuandmemory, while configuring the MicroVM with hotplug ceilingsmaxCpuandmaxMemory. - Baseline sandbox creation: If you omit
cpuandmemoryonPOST /sandboxes, the sandbox restores directly at the template's baseline specification. - Resized sandbox creation: If you pass a larger
cpuand/ormemorywithin[cpu, maxCpu]and[memory, maxMemory], CubeMaster schedules and places the sandbox using the resized capacity requirement, and Cubelet/CubeShim hotplugs the extra vCPUs and memory into the restored VM, updates host and guest cgroups, and exposes the expanded resources topostStarthooks and user processes.
Units, Rules, and Constraints
Unit warning: CPU fields in REST, CLI, Go (
cpu/maxCpu), Python (cpu_count/max_cpu_count), and Node.js (cpuCount/maxCpuCount) are in millicores, not vCPU counts — pass2000for 2 vCPUs,4000for 4 vCPUs, and8000for 8 vCPUs. Memory fields are in MiB.
- Scale-up only: Sandbox
cpuandmemorymust satisfytemplate.cpu <= cpu <= template.maxCpuandtemplate.memory <= memory <= template.maxMemory. Scaling below the template baseline is rejected. - Granularity:
maxCpuand any overridden sandboxcpumust be whole-vCPU multiples of1000millicores (for example2000,4000,8000).- Memory growth (
maxMemory - template.memoryandmemory - template.memory) must be a multiple of128MiB.
- Single-dimension resize: You can scale only CPU, only memory, or both at the same time. Any omitted dimension stays at the template's baseline value.
- Architecture: VM CPU/memory hotplug is supported on
x86_64hosts only. ARM64 hosts reject VM hotplug resize requests. - ACPI memory hotplug slot limit: Cloud Hypervisor exposes at most 8 ACPI memory hotplug slots per VM. Each memory scale-up on a VM snapshot consumes one slot, and consumed slots persist across
pause/resumeandcommitinto derived VM-snapshot templates. Up to 8 chained memory scale-ups are supported on the same snapshot lineage; a 9th memory growth fails explicitly at restore/resize time (NoSlotAvailable). Build from a fresh base template or use anfs-onlysnapshot to reset slots. - Lifecycle persistence:
pause/resumepreserves the resized CPU and memory.- Cold-boot
restartboots directly with the resized specification. commit(creating a template or snapshot from a resized sandbox) promotes the resized CPU/memory to the new baseline while retaining the originalmaxCpu/maxMemoryceilings, allowing further scale-up up to those ceilings.
Parameter Mapping Across Interfaces
| Operation | REST API (CubeAPI) | CLI (cubemastercli) | Python SDK | Node.js SDK | Go SDK | Unit |
|---|---|---|---|---|---|---|
| Template base CPU | cpu | --cpu | cpu_count | cpuCount | CPU | Millicores (2000 = 2 vCPUs) |
| Template base memory | memory | --memory | memory_mb | memoryMb | Memory | MiB |
| Template max CPU | maxCpu | --max-cpu | max_cpu_count | maxCpuCount | MaxCPU | Millicores (multiple of 1000) |
| Template max memory | maxMemory | --max-memory | max_memory_mb | maxMemoryMb | MaxMemory | MiB (128 MiB step above base) |
| Sandbox CPU override | cpu | — | cpu_count | cpuCount | CPU | Millicores (multiple of 1000) |
| Sandbox memory override | memory | — | memory_mb | memoryMb | Memory | MiB (128 MiB step above base) |
Step 1: Build a Template with Max CPU and Memory
The examples below build a template that boots with 2 vCPUs / 1024 MiB and allows sandboxes to scale up to 8 vCPUs / 4096 MiB.
REST API (POST /templates)
curl -X POST "http://<cubeapi-host>:3000/templates" \
-H "Content-Type: application/json" \
-H "X-API-Key: <your-api-key>" \
-d '{
"image": "ghcr.io/example/python-runtime:3.12",
"alias": "python-resizable",
"writableLayerSize": "2G",
"exposedPorts": [49983],
"probePort": 49983,
"probePath": "/health",
"cpu": 2000,
"memory": 1024,
"maxCpu": 8000,
"maxMemory": 4096
}'Poll GET /templates/<templateID> until the template status becomes READY before creating sandboxes.
CLI (cubemastercli)
cubemastercli tpl create-from-image \
--image ghcr.io/example/python-runtime:3.12 \
--alias python-resizable \
--writable-layer-size 2G \
--expose-port 49983 \
--probe 49983 \
--probe-path /health \
--cpu 2000 \
--memory 1024 \
--max-cpu 8000 \
--max-memory 4096SDKs
import time
from cubesandbox import Template
job = Template.build(
image="ghcr.io/example/python-runtime:3.12",
name="python-resizable",
writable_layer_size="2G",
exposed_ports=[49983],
probe_port=49983,
probe_path="/health",
cpu_count=2000, # 2 vCPUs baseline (millicores)
memory_mb=1024, # 1024 MiB baseline
max_cpu_count=8000, # up to 8 vCPUs (millicores)
max_memory_mb=4096, # up to 4096 MiB
)
while True:
info = Template.get(job.template_id)
if info.status == "READY":
break
if info.status in ("FAILED", "ERROR"):
raise RuntimeError(f"template build failed: {info}")
time.sleep(2)import { Template } from "@cubesandbox/sdk";
const job = await Template.build({
image: "ghcr.io/example/python-runtime:3.12",
name: "python-resizable",
writableLayerSize: "2G",
exposedPorts: [49983],
probePort: 49983,
probePath: "/health",
cpuCount: 2000, // 2 vCPUs baseline (millicores)
memoryMb: 1024, // 1024 MiB baseline
maxCpuCount: 8000, // up to 8 vCPUs (millicores)
maxMemoryMb: 4096, // up to 4096 MiB
});
while (true) {
const info = await Template.get(job.templateId);
if (info.status === "READY") break;
if (info.status === "FAILED" || info.status === "ERROR") {
throw new Error(`template build failed: ${JSON.stringify(info)}`);
}
await new Promise((r) => setTimeout(r, 2000));
}package main
import (
"context"
"fmt"
"time"
cubesandbox "github.com/tencentcloud/CubeSandbox/sdk/go"
)
func main() {
ctx := context.Background()
client, err := cubesandbox.NewClient()
if err != nil {
panic(err)
}
defer client.Close()
probePort := uint16(49983)
job, err := client.BuildTemplate(ctx, cubesandbox.BuildTemplateOptions{
Image: "ghcr.io/example/python-runtime:3.12",
Name: "python-resizable",
WritableLayerSize: "2G",
ExposedPorts: []uint16{49983},
ProbePort: &probePort,
ProbePath: "/health",
CPU: cubesandbox.Uint32Ptr(2000), // 2 vCPUs baseline (millicores)
Memory: cubesandbox.Uint32Ptr(1024), // 1024 MiB baseline
MaxCPU: cubesandbox.Uint32Ptr(8000), // up to 8 vCPUs (millicores)
MaxMemory: cubesandbox.Uint32Ptr(4096), // up to 4096 MiB
})
if err != nil {
panic(err)
}
for {
info, err := client.GetTemplate(ctx, job.TemplateID)
if err != nil {
panic(err)
}
if info.Status == "READY" {
fmt.Println("template ready:", info.TemplateID)
break
}
if info.Status == "FAILED" || info.Status == "ERROR" {
panic(fmt.Sprintf("template build failed: %+v", info))
}
time.Sleep(2 * time.Second)
}
}Step 2: Create a Sandbox with Custom CPU and Memory
Once the template is READY, create sandboxes at either the baseline size (by omitting CPU/memory) or a scaled-up size within [cpu, maxCpu] and [memory, maxMemory].
REST API (POST /sandboxes)
Scale up both CPU and memory to 4 vCPUs / 2048 MiB:
curl -X POST "http://<cubeapi-host>:3000/sandboxes" \
-H "Content-Type: application/json" \
-H "X-API-Key: <your-api-key>" \
-d '{
"templateID": "python-resizable",
"timeout": 300,
"cpu": 4000,
"memory": 2048
}'You can also scale a single dimension (for example pass only "memory": 2048 to keep 2 vCPUs, or only "cpu": 4000 to keep 1024 MiB), or omit both fields to launch at the baseline 2C/1024Mi.
SDKs
from cubesandbox import Sandbox
# Scaled-up sandbox: 4 vCPUs / 2048 MiB
with Sandbox.create(
template="python-resizable",
timeout=300,
cpu_count=4000, # 4 vCPUs (millicores)
memory_mb=2048, # 2048 MiB
) as sb:
res = sb.commands.run("nproc && grep MemTotal /proc/meminfo")
print(res.stdout)
# Baseline sandbox: inherits template's 2 vCPUs / 1024 MiB
with Sandbox.create(template="python-resizable", timeout=300) as sb:
print(sb.commands.run("nproc").stdout)import { Sandbox } from "@cubesandbox/sdk";
// Scaled-up sandbox: 4 vCPUs / 2048 MiB
const sb = await Sandbox.create({
template: "python-resizable",
timeout: 300,
cpuCount: 4000, // 4 vCPUs (millicores)
memoryMb: 2048, // 2048 MiB
});
try {
const res = await sb.commands.run("nproc && grep MemTotal /proc/meminfo");
console.log(res.stdout);
} finally {
await sb.kill();
}package main
import (
"context"
"fmt"
"time"
cubesandbox "github.com/tencentcloud/CubeSandbox/sdk/go"
)
func main() {
ctx := context.Background()
client, err := cubesandbox.NewClient()
if err != nil {
panic(err)
}
defer client.Close()
// Scaled-up sandbox: 4 vCPUs / 2048 MiB
sb, err := client.Create(ctx, cubesandbox.CreateOptions{
TemplateID: "python-resizable",
Timeout: 5 * time.Minute,
CPU: cubesandbox.Uint32Ptr(4000), // 4 vCPUs (millicores)
Memory: cubesandbox.Uint32Ptr(2048), // 2048 MiB
})
if err != nil {
panic(err)
}
defer sb.Kill(ctx)
res, err := sb.Commands().Run(ctx, "nproc && grep MemTotal /proc/meminfo", cubesandbox.CommandOptions{})
if err != nil {
panic(err)
}
fmt.Println(res.Stdout)
}Additional Overhead and Cost
Declaring maxCpu and maxMemory on a template does not reserve maximum resources on the host before a sandbox actually scales up, but it does introduce a small, measurable overhead inside the guest kernel and VMM process.
What Is Not Pre-Allocated
- Host vCPU threads: Cloud Hypervisor only starts threads for the baseline boot vCPUs. Setting
maxCpu=64000on a 1-vCPU template does not spawn 64 host vCPU threads. - Host backing RAM: Setting
maxMemorydoes not pre-allocate backing RAM on the host or consume scheduler memory quota until a sandbox actually requests more memory. - Restore latency: Snapshot restore time changes by only a few milliseconds even with large ceilings.
Measured Pre-Resize Overhead (boot = 1 vCPU / 1024 MiB)
The table below was measured on a live KVM (x86_64) node restoring unresized 1C/1G sandboxes from templates with different maxCpu / maxMemory ceilings:
| Template Config | Restore Time | Guest possible CPUs | Guest MemTotal | Guest MemAvailable | Guest Percpu | Guest Slab | Host Shim RSS | Host Threads |
|---|---|---|---|---|---|---|---|---|
boot=1C/1G, max=none | ~61 ms | 0 | 985,760 kB | 682,272 kB | 300 kB | 30,592 kB | 137,964 kB | 24 |
boot=1C/1G, max=16C/1G | ~63 ms | 0-15 | 981,636 kB | 679,488 kB | 4,800 kB | 32,980 kB | 141,292 kB | 24 |
boot=1C/1G, max=32C/1G | ~67 ms | 0-31 | 977,280 kB | 668,412 kB | 9,600 kB | 35,484 kB | 142,364 kB | 24 |
boot=1C/1G, max=64C/1G | ~67 ms | 0-63 | 968,560 kB | 652,060 kB | 19,200 kB | 40,368 kB | 153,388 kB | 24 |
boot=1C/1G, max=64C/8G | ~67 ms | 0-63 | 968,560 kB | 652,432 kB | 19,200 kB | 40,372 kB | 147,800 kB | 23 |
Key takeaways:
maxCpuoverhead: Exposing more possible CPUs expands Linux kernel per-CPU (Percpu) andSlaballocations inside the guest — roughly ~0.5 MiB of guest RAM per possible vCPU. Going frommaxCpu=1000tomaxCpu=64000reduces guestMemAvailableby ~30 MiB and raises host VMM RSS by ~15 MiB, with zero extra host threads.maxMemoryoverhead: Declaring a largermaxMemory(e.g.8 GiBon a1 GiBbase template) adds negligible pre-resize overhead to both guestMemAvailableand host RSS.
Startup Latency Impact When Scaling Up (boot = 2 vCPU / 1 GiB, max = 8 vCPU / 4 GiB)
While unresized sandboxes restore at nearly identical speed, requesting a larger cpu and/or memory at creation time runs VM hotplug, guest kernel online settling, and synchronous cgroup updates before create returns. Measured end-to-end create latency on an x86_64 XFS node with a local template image:
| Sandbox Create Override | Effective Guest Spec | End-to-End Create Latency | Delta vs Baseline |
|---|---|---|---|
| None (baseline) | 2 vCPU / 1 GiB (MemTotal 960 MiB) | ~52 ms | — |
memory=2048 only | 2 vCPU / 2 GiB (MemTotal 1984 MiB) | ~108 ms | +~56 ms |
cpu=4000 only | 4 vCPU / 1 GiB (MemTotal 960 MiB) | ~203 ms | +~151 ms |
cpu=4000, memory=2048 | 4 vCPU / 2 GiB (MemTotal 1984 MiB) | ~223 ms | +~171 ms |
- Memory-only scale-up adds moderate startup latency (~50–60 ms) for ACPI memory hotplug, guest sysfs memory online, and cgroup refresh.
- CPU scale-up adds noticeably more latency (~150 ms) because guest Linux SMP bring-up and sysfs CPU onlining take longer than memory block onlining; scaling both CPU and memory together takes roughly ~220 ms.
- First
pause/ snapshot after memory growth: Because the resized VM's memory exceeds the template's base memory image, the nextpauseor snapshot (create_snapshot/commit) after a memory scale-up falls back to a full memory dump instead of an incremental CoW/soft-dirty snapshot, so that operation takes longer and writes more data. Once that full memory snapshot is written, subsequent pauses and snapshots at the same memory size resume using incremental memory snapshots (until memory is scaled up again). - Post-resize accounting: Once a sandbox is actually created with a higher
cpuand/ormemory, cluster scheduling, cross-node snapshot placement, and host/guest cgroups account for and enforce the resized specification, not the template baseline.
Practical Sizing Recommendations
- Set
maxCputo a realistic ceiling, especially for small-memory templates (256 MiB–512 MiB), where ~30 MiB of per-CPU kernel overhead from an oversizedmaxCpu=64000is a noticeable share of guest RAM. For example,maxCpu=8000ormaxCpu=16000costs only ~3–7 MiB in guest memory. - Set
maxMemorygenerously within your tier needs (aligned to128 MiBabovememory), since its pre-resize cost is negligible. - Balance template consolidation vs. startup latency: Use a single resizable template to cover variable or lower-frequency tiers without maintaining extra templates; if a high-volume larger tier (such as
4C/2Gor8C/4G) strictly requires ~50 ms cold-start latency, keeping a dedicated baseline template for that tier avoids the ~150–170 ms hotplug overhead on every creation.
Next Steps
- Templates Overview — understand how snapshots, probes, and readiness work.
- Create Templates from OCI Image — full CLI workflow for building templates.
- Sandbox Lifecycle — how resized specs behave across pause, resume, timeout, and restart.
- Snapshot, Rollback & Clone — how snapshots and clones interact with resized sandboxes.