# CubeSandbox Fork/Clone Mechanism: Creating New Sandboxes from Snapshots

> Learn how CubeSandbox fork/clone creates new sandboxes from snapshots. Discover the three-step process for efficient sandbox management and guaranteed cleanup.

- Repository: [Tencent Cloud/CubeSandbox](https://github.com/TencentCloud/CubeSandbox)
- Tags: internals
- Published: 2026-07-11

---

**CubeSandbox creates new sandboxes from snapshots through a three-step process that generates a temporary snapshot, launches fresh instances using that snapshot as a template with configurable concurrency, and performs guaranteed cleanup while atomically rolling back partial creations if any clone fails.**

The TencentCloud CubeSandbox Go SDK implements a robust fork/clone mechanism that allows developers to instantiate multiple isolated environments from an existing snapshot. This process, defined in [`sdk/go/snapshot.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/snapshot.go), handles the full lifecycle from template generation through parallel creation to automatic resource cleanup, ensuring no partial deployments leak resources.

## The Three-Step Fork/Clone Process

CubeSandbox exposes this functionality through the `Sandbox.Clone` method, which internally orchestrates three distinct phases implemented in the Go SDK.

### Step 1: Create a Temporary Snapshot

The process begins by calling `Sandbox.CreateSnapshot`, which issues a `POST /sandboxes/:id/snapshots` request to the CubeSandbox API. According to the implementation in [`sdk/go/snapshot.go:38-55`](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/go/snapshot.go#L38-L55), this returns a `SnapshotInfo` struct where the `SnapshotID` field doubles as a template ID for subsequent creation operations.

This temporary snapshot serves as the immutable blueprint for all cloned sandboxes, capturing the exact state of the source sandbox at the moment of forking.

### Step 2: Launch Fresh Sandboxes with Concurrency Control

The `Sandbox.Clone` method then enters its core execution loop defined in [`sdk/go/snapshot.go:64-74`](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/go/snapshot.go#L64-L74). For each requested clone, it invokes `Client.Create` with `CreateOptions{TemplateID: snapshot.SnapshotID}`, passing the snapshot ID obtained in step one as the template identifier.

The clone options struct, defined in [`sdk/go/snapshot.go:21-36`](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/go/snapshot.go#L31-L36), accepts two critical parameters:
- **N**: The total number of sandboxes to create
- **Concurrency**: The maximum number of parallel creation operations (automatically capped at `N`)

This worker pool pattern allows efficient bulk provisioning while respecting API rate limits and resource constraints.

### Step 3: Best-Effort Cleanup and Error Handling

After spawning all creation workers, the SDK registers a deferred cleanup routine. As implemented in [`sdk/go/snapshot.go:42-45`](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/go/snapshot.go#L42-L45), this calls `Client.DeleteSnapshot` to remove the temporary snapshot regardless of whether the clones succeeded or if the caller's context was cancelled.

If any individual clone creation fails, the SDK immediately aborts the entire operation, kills any sandboxes that were successfully created during the partial fan-out, and returns the first encountered error. This atomic guarantee ensures that failed fork operations never leave orphaned resources.

## Implementation Example

The following example demonstrates the high-level `Clone` method with concurrency control:

```go
// Example: Clone a sandbox into three fresh sandboxes.
ctx := context.Background()
sb, _ := client.GetSandbox(ctx, "sandbox-123") // obtain an existing sandbox

clones, err := sb.Clone(ctx, cubesandbox.CloneOptions{
    N:           3, // create three clones
    Concurrency: 2, // at most two creations in parallel
})
if err != nil {
    log.Fatalf("clone failed: %v", err)
}
for i, c := range clones {
    fmt.Printf("clone %d sandbox ID: %s\n", i+1, c.SandboxID)
}

```

For scenarios requiring custom cleanup logic or intermediate processing, you can manually execute the three steps:

```go
// Example: Manually perform the three steps (useful for custom cleanup).
snap, _ := sb.CreateSnapshot(ctx, "my-snapshot")
// Use the snapshot as a template to create a new sandbox.
newSB, _ := client.Create(ctx, cubesandbox.CreateOptions{TemplateID: snap.SnapshotID})
// Delete the temporary snapshot when done.
_ = client.DeleteSnapshot(context.Background(), snap.SnapshotID)

```

## Key Source Files

The fork/clone mechanism spans several files in the Go SDK:

- **[[`sdk/go/snapshot.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/snapshot.go)](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/go/snapshot.go)**: Implements `CreateSnapshot`, `DeleteSnapshot`, and the core `Clone` logic with worker pool management
- **[[`sdk/go/client.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/client.go)](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/go/client.go)**: Provides the low-level `doJSON` helper used for API communication
- **[[`sdk/go/sandbox.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/sandbox.go)](https://github.com/TencentCloud/CubeSandbox/blob/master/sdk/go/sandbox.go)**: Defines the `Sandbox` type and helper methods such as `ensureClient`

## Summary

- **CubeSandbox implements fork/clone as a three-phase operation**: snapshot creation, parallel sandbox instantiation, and deferred cleanup
- **Concurrency is configurable but capped**: The `Concurrency` parameter in `CloneOptions` controls worker parallelism but never exceeds the requested count `N`
- **Atomic failure handling**: If any clone fails, the SDK automatically deletes all successfully created sandboxes from that batch to prevent resource leaks
- **Snapshot ID reuse**: The `SnapshotID` returned from `CreateSnapshot` functions directly as the `TemplateID` for new sandbox creation
- **Guaranteed cleanup**: Temporary snapshots are deleted via deferred calls that execute even if the parent context is cancelled

## Frequently Asked Questions

### What happens if one clone fails during a bulk fork operation?

The SDK aborts the entire operation immediately and enters a cleanup phase. It kills any sandboxes that were successfully created during the partial fan-out and returns the first encountered error. This atomic behavior ensures you never end up with a partial set of clones when requesting multiple sandboxes.

### How does concurrency control work in the Clone method?

The `CloneOptions` struct accepts a `Concurrency` parameter that specifies the maximum number of parallel creation workers. According to the implementation in [`sdk/go/snapshot.go`](https://github.com/TencentCloud/CubeSandbox/blob/main/sdk/go/snapshot.go), this value is automatically capped at `N` (the total number of requested clones) to prevent spawning unnecessary goroutines when requesting small batches.

### Is the temporary snapshot automatically deleted after cloning?

Yes. The SDK registers a deferred cleanup function that calls `Client.DeleteSnapshot` after the clones are created. This cleanup runs even if the caller's context is cancelled or if the clone operation partially fails, mirroring the behavior of the Python SDK to prevent snapshot accumulation.

### Can I manually control the snapshot lifecycle instead of using the Clone method?

Absolutely. You can call `Sandbox.CreateSnapshot` directly to obtain a `SnapshotInfo`, then use `Client.Create` with `CreateOptions{TemplateID: snap.SnapshotID}` to build sandboxes individually. This manual approach is useful when you need to retain the snapshot for multiple distinct batch operations or implement custom retention policies.