Skip to content

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 ​

  1. Template build (POST /templates): The template boots and takes its snapshot at the baseline cpu and memory, while configuring the MicroVM with hotplug ceilings maxCpu and maxMemory.
  2. Baseline sandbox creation: If you omit cpu and memory on POST /sandboxes, the sandbox restores directly at the template's baseline specification.
  3. Resized sandbox creation: If you pass a larger cpu and/or memory within [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 to postStart hooks 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 — pass 2000 for 2 vCPUs, 4000 for 4 vCPUs, and 8000 for 8 vCPUs. Memory fields are in MiB.

  • Scale-up only: Sandbox cpu and memory must satisfy template.cpu <= cpu <= template.maxCpu and template.memory <= memory <= template.maxMemory. Scaling below the template baseline is rejected.
  • Granularity:
    • maxCpu and any overridden sandbox cpu must be whole-vCPU multiples of 1000 millicores (for example 2000, 4000, 8000).
    • Memory growth (maxMemory - template.memory and memory - template.memory) must be a multiple of 128 MiB.
  • 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_64 hosts 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/resume and commit into 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 an fs-only snapshot to reset slots.
  • Lifecycle persistence:
    • pause / resume preserves the resized CPU and memory.
    • Cold-boot restart boots 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 original maxCpu / maxMemory ceilings, allowing further scale-up up to those ceilings.

Parameter Mapping Across Interfaces ​

OperationREST API (CubeAPI)CLI (cubemastercli)Python SDKNode.js SDKGo SDKUnit
Template base CPUcpu--cpucpu_countcpuCountCPUMillicores (2000 = 2 vCPUs)
Template base memorymemory--memorymemory_mbmemoryMbMemoryMiB
Template max CPUmaxCpu--max-cpumax_cpu_countmaxCpuCountMaxCPUMillicores (multiple of 1000)
Template max memorymaxMemory--max-memorymax_memory_mbmaxMemoryMbMaxMemoryMiB (128 MiB step above base)
Sandbox CPU overridecpu—cpu_countcpuCountCPUMillicores (multiple of 1000)
Sandbox memory overridememory—memory_mbmemoryMbMemoryMiB (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) ​

bash
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) ​

bash
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 4096

SDKs ​

python
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)
ts
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));
}
go
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:

bash
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 ​

python
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)
ts
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();
}
go
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=64000 on a 1-vCPU template does not spawn 64 host vCPU threads.
  • Host backing RAM: Setting maxMemory does 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 ConfigRestore TimeGuest possible CPUsGuest MemTotalGuest MemAvailableGuest PercpuGuest SlabHost Shim RSSHost Threads
boot=1C/1G, max=none~61 ms0985,760 kB682,272 kB300 kB30,592 kB137,964 kB24
boot=1C/1G, max=16C/1G~63 ms0-15981,636 kB679,488 kB4,800 kB32,980 kB141,292 kB24
boot=1C/1G, max=32C/1G~67 ms0-31977,280 kB668,412 kB9,600 kB35,484 kB142,364 kB24
boot=1C/1G, max=64C/1G~67 ms0-63968,560 kB652,060 kB19,200 kB40,368 kB153,388 kB24
boot=1C/1G, max=64C/8G~67 ms0-63968,560 kB652,432 kB19,200 kB40,372 kB147,800 kB23

Key takeaways:

  • maxCpu overhead: Exposing more possible CPUs expands Linux kernel per-CPU (Percpu) and Slab allocations inside the guest — roughly ~0.5 MiB of guest RAM per possible vCPU. Going from maxCpu=1000 to maxCpu=64000 reduces guest MemAvailable by ~30 MiB and raises host VMM RSS by ~15 MiB, with zero extra host threads.
  • maxMemory overhead: Declaring a larger maxMemory (e.g. 8 GiB on a 1 GiB base template) adds negligible pre-resize overhead to both guest MemAvailable and 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 OverrideEffective Guest SpecEnd-to-End Create LatencyDelta vs Baseline
None (baseline)2 vCPU / 1 GiB (MemTotal 960 MiB)~52 ms—
memory=2048 only2 vCPU / 2 GiB (MemTotal 1984 MiB)~108 ms+~56 ms
cpu=4000 only4 vCPU / 1 GiB (MemTotal 960 MiB)~203 ms+~151 ms
cpu=4000, memory=20484 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 next pause or 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 cpu and/or memory, 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 maxCpu to a realistic ceiling, especially for small-memory templates (256 MiB–512 MiB), where ~30 MiB of per-CPU kernel overhead from an oversized maxCpu=64000 is a noticeable share of guest RAM. For example, maxCpu=8000 or maxCpu=16000 costs only ~3–7 MiB in guest memory.
  • Set maxMemory generously within your tier needs (aligned to 128 MiB above memory), 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/2G or 8C/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 ​