Use Traefik for Canary Traffic Routing

Updated at:

Background

When running an online service in a cloud Sandbox, you often need to roll out a new version (v2) gradually without interrupting the service: first send a small portion of traffic to the new version to observe it, then expand the ratio after confirming it works, or let internal users access the new version directly for verification. This "canary / gradual release" capability can be implemented inside the Sandbox by introducing the lightweight reverse proxy Traefik.

About Traefik: Traefik is an open-source, cloud-native reverse proxy and load balancer. It ships as a single, dependency-free binary that can be downloaded and run directly inside the Sandbox. Its defining feature is dynamic configuration—routing rules, backend services, and split weights can all be delivered in real time through a config file, and combined with file watching (watch) it hot-reloads within seconds without restarting the process. This makes it a great fit for canary and blue-green releases that need to adjust traffic online.

This document uses two versions of an HTTP service (v1 / v2) as an example and shows how to perform two kinds of canary routing with Traefik inside a single cloud Sandbox:

  • Weight-based canary: default traffic is split between v1 / v2 by ratio (for example 70% / 30%), and the ratio can be hot-adjusted at runtime without a restart.

  • Header-based pinning: requests carrying a specific header (for example X-Version: v2) are forced to hit a specific version, commonly used for internal / allowlist verification.

Solution overview

The Sandbox exposes only Traefik's entry port to the outside; Traefik forwards requests to v1 / v2 inside the Sandbox according to rules:

Traffic path of Traefik canary routing inside a cloud Sandbox

  • The cloud Sandbox assigns an external address to each port listening inside the Sandbox. Get it via the SDK's sandbox.get_host(port) and prefix https:// to access it from outside. The exposable port range is [3000, 65535].

  • v1 / v2 are two backend services listening only inside the Sandbox; there is no need to (and you should not) access them directly from outside—all traffic goes through the Traefik entry.

  • Traefik uses "file configuration + hot reload" (--providers.file.watch=true): to adjust canary rules you only rewrite one config file, and Traefik applies it within seconds—no process restart, no traffic interruption.

Prerequisites

  • FC Agent Sandbox is enabled, and you have the E2B_API_KEY for the target region.

  • The target region is US (Silicon Valley), with the following endpoints:

    • api_url: https://api.us-west-1.e2b.fc.aliyuncs.com

    • domain: us-west-1.e2b.fc.aliyuncs.com

  • The Sandbox needs public network access to download the Traefik binary (the default uses the Serverless OSS global download domain; see "FAQ").

  • Install the cloud Sandbox Python SDK and an HTTP client, and set the connection parameters as environment variables:

    pip install e2b==2.31.0 httpx
    
    export E2B_API_KEY="<your-e2b-api-key>"
    export E2B_DOMAIN="us-west-1.e2b.fc.aliyuncs.com"
    export E2B_API_URL="https://api.us-west-1.e2b.fc.aliyuncs.com"

Procedure

Step 1: Create a Sandbox and start two versions of the backend service

Use python3 -m http.server to simulate two versions, each with a version-identifying homepage in its own directory, so you can verify "which version this request hit."

import os
import time

from e2b import Sandbox

WORKDIR = "/tmp/canary"
V1_PORT, V2_PORT = 9000, 9001

conn = {
    "api_key": os.environ["E2B_API_KEY"],
    "api_url": os.environ["E2B_API_URL"],
    "domain": os.environ["E2B_DOMAIN"],
}

# secure=True (SDK default): access control enabled; attach X-Access-Token as needed when accessing dynamic ports (see Step 5)
sbx = Sandbox.create(template="base", timeout=600, secure=True, **conn)

# v1 backend: homepage content marked as v1
sbx.files.write(f"{WORKDIR}/v1/index.html", "backend=v1\n")
sbx.commands.run(f"python3 -m http.server {V1_PORT}", cwd=f"{WORKDIR}/v1", background=True)

# v2 backend: homepage content marked as v2
sbx.files.write(f"{WORKDIR}/v2/index.html", "backend=v2\n")
sbx.commands.run(f"python3 -m http.server {V2_PORT}", cwd=f"{WORKDIR}/v2", background=True)
Note

secure=True is the SDK default and the recommended production setting—once the Sandbox has access control enabled, accessing dynamic ports from outside requires attaching X-Access-Token as needed (see Step 5 and FAQ #3). For quick local verification without handling tokens, you can temporarily use secure=False (open access without a token, for demo/testing only).

Step 2: Deploy Traefik inside the Sandbox

Download and extract Traefik inside the Sandbox (equivalent to running curl -O then unpacking). The snippet below uses Python for the download—compatible with templates that don't preinstall curl / wget, with a resumable-download fallback for weak networks.

GET_TRAEFIK = r'''
import os, shutil, subprocess, tarfile, time, urllib.request, hashlib
DEST, URL = "/tmp/canary", os.environ["TRAEFIK_TARBALL"]
SHA256 = os.environ.get("TRAEFIK_SHA256", "")
TAR, BIN = DEST + "/traefik.tar.gz", DEST + "/traefik"

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()

def done():
    try:
        with tarfile.open(TAR) as t:
            t.getmembers()
        return True
    except Exception:
        return False

def via_cmd(argv):
    for _ in range(10):
        if subprocess.call(argv) == 0 and done():
            return True
        time.sleep(2)
    return done()

def via_py():
    for _ in range(30):
        have = os.path.getsize(TAR) if os.path.exists(TAR) else 0
        try:
            req = urllib.request.Request(URL, headers={"Range": f"bytes={have}-", "User-Agent": "x"})
            with urllib.request.urlopen(req, timeout=60) as r:
                # if the server ignores Range it returns 200 + the full file; overwrite instead of appending
                mode = "ab" if have and r.status == 206 else "wb"
                with open(TAR, mode) as f:
                    shutil.copyfileobj(r, f, 1 << 20)
        except Exception:
            time.sleep(2)
            continue
        if done():
            return True
    return done()

ok = shutil.which("wget") and via_cmd(["wget", "-c", "-q", "-T", "60", "-O", TAR, URL])
if not ok and shutil.which("curl"):
    ok = via_cmd(["curl", "-fsSL", "-C", "-", "--max-time", "120", "-o", TAR, URL])
if not ok:
    ok = via_py()
if not ok:
    raise SystemExit("download failed")
# Require SHA-256 verification before extraction to reject tampered or incomplete downloads.
if not SHA256:
    raise SystemExit("TRAEFIK_SHA256 is required")
actual_sha256 = sha256(TAR)
if actual_sha256 != SHA256:
    raise SystemExit("sha256 mismatch: got %s, expected %s" % (actual_sha256, SHA256))
with tarfile.open(TAR) as t:
    t.extract("traefik", DEST)
os.chmod(BIN, 0o755)
print("traefik ready")
'''

# Traefik binary served from the Serverless OSS global download domain. Override with the TRAEFIK_TARBALL env var
# to use an internal mirror; when overriding, you MUST also provide a matching SHA-256 via TRAEFIK_SHA256.
# In production, prefer baking the binary into a custom template (see "FAQ") so no download is needed at runtime.
TRAEFIK_TARBALL = os.environ.get(
    "TRAEFIK_TARBALL",
    "https://images.devsapp.cn/e2b/traefik/"
    "v3.7.8/traefik_v3.7.8_linux_amd64.tar.gz",
)
TRAEFIK_SHA256 = os.environ.get(
    "TRAEFIK_SHA256",
    "dbd809b1de85d86d0718c80bedbaabd9aebaa3c6697f9e986ab5f387f4196cb7",
)

sbx.files.write(f"{WORKDIR}/get_traefik.py", GET_TRAEFIK)
res = sbx.commands.run(
    f"python3 {WORKDIR}/get_traefik.py",
    envs={"TRAEFIK_TARBALL": TRAEFIK_TARBALL, "TRAEFIK_SHA256": TRAEFIK_SHA256},
    timeout=600,
)
assert res.exit_code == 0, res.stderr

Step 3: Write the two-tier forwarding rules

In Traefik's dynamic configuration, write two kinds of rules and use priority to make the header-pinning rules take precedence over the default weighting rule:

TRAEFIK_PORT = 8080

def dynamic_config(w1: int, w2: int) -> str:
    """Split by weight w1:w2 by default; requests with the X-Version header are forced to the matching version."""
    return f"""\
http:
  routers:
    pin-v1:                                  # X-Version: v1 -> force v1
      rule: "Header(`X-Version`, `v1`)"
      entryPoints: [web]
      service: v1
      priority: 100
    pin-v2:                                  # X-Version: v2 -> force v2
      rule: "Header(`X-Version`, `v2`)"
      entryPoints: [web]
      service: v2
      priority: 100
    default:                                 # other traffic -> weighted split
      rule: "PathPrefix(`/`)"
      entryPoints: [web]
      service: weighted
      priority: 1
  services:
    weighted:
      weighted:
        services:
          - {{name: v1, weight: {w1}}}
          - {{name: v2, weight: {w2}}}
    v1:
      loadBalancer:
        servers: [{{url: "http://127.0.0.1:{V1_PORT}"}}]
    v2:
      loadBalancer:
        servers: [{{url: "http://127.0.0.1:{V2_PORT}"}}]
"""

def set_weights(w1: int, w2: int):
    """Write/overwrite the config file; Traefik has watch enabled and hot-reloads automatically."""
    sbx.files.write(f"{WORKDIR}/dynamic.yml", dynamic_config(w1, w2))

Step 4: Start Traefik

Start Traefik with 8080 as the external entry, and enable file-config hot reload:

set_weights(100, 0)   # initial: all traffic to v1
sbx.commands.run(
    f"{WORKDIR}/traefik"
    f" --entrypoints.web.address=:{TRAEFIK_PORT}"
    f" --providers.file.filename={WORKDIR}/dynamic.yml"
    f" --providers.file.watch=true"
    f" --api.dashboard=false --log.level=INFO --accesslog=true",
    background=True,
)
time.sleep(3)   # wait for Traefik to start and load config (in production, poll for readiness—see wait_ready in "Complete example")

Step 5: Verify the canary effect

Access the Traefik entry from outside and count the ratio of versions hit.

import httpx
from collections import Counter

BASE = f"https://{sbx.get_host(TRAEFIK_PORT)}"
# When secure=True and traffic tokens are enabled, accessing dynamic ports requires X-Access-Token; otherwise traffic_access_token is None
TOKEN = sbx.traffic_access_token

def sample(n: int, version: str | None = None) -> Counter:
    headers = {"X-Access-Token": TOKEN} if TOKEN else {}
    if version:
        headers["X-Version"] = version
    hits = Counter()
    with httpx.Client(timeout=5) as c:
        for _ in range(n):
            body = c.get(BASE + "/", headers=headers).text
            hits["v2" if "backend=v2" in body else "v1" if "backend=v1" in body else "?"] += 1
    return hits

# 1) Default weight-based canary: hot-adjust 100/0 -> 70/30 -> 30/70
for w1, w2 in ((100, 0), (70, 30), (30, 70)):
    set_weights(w1, w2)
    time.sleep(3)                       # wait for hot reload
    print(f"weight {w1}/{w2}:", dict(sample(100)))

# 2) Header pinning: the default weight is still 30/70, but header requests should hit the specified version 100%
print("X-Version=v1:", dict(sample(100, "v1")))
print("X-Version=v2:", dict(sample(100, "v2")))

Expected output (exact ratios, and header pinning hitting 100%):

weight 100/0: {'v1': 100}
weight 70/30: {'v1': 70, 'v2': 30}
weight 30/70: {'v1': 30, 'v2': 70}
X-Version=v1: {'v1': 100}
X-Version=v2: {'v2': 100}
Note

weighted round-robin is a deterministic smooth interleave; sampling 100 requests yields a near-exact ratio—do not judge the ratio from a tiny sample (the printed dict key order may vary by which version is hit first, which does not affect the ratio). Remember to call sbx.kill() when done to reclaim the Sandbox and its background processes.

Advanced usage

You only need to change the rules generated by dynamic_config(); the overall architecture stays the same:

  • Path / query-based canary: replace Header(...) with PathPrefix(`/beta`) or Query(`canary`, `true`) to route requests with a specific path or query parameter to the new version.

  • Blue-green deployment: switch the weight from 100/0 to 0/100 in one shot for a full cutover.

  • Session stickiness: configure sticky.cookie on the service so the same user always hits the same version during the canary, avoiding a jarring experience.

  • Traffic mirroring: use mirroring to copy a portion of traffic to the new version (responses discarded), observing without affecting real users.

  • Active health checks: configure loadBalancer.healthCheck for backends so unhealthy instances are removed automatically, making the canary safer.

FAQ

1. Traefik download is slow or fails? The default download URL points to the Serverless OSS global download domain, which is reachable worldwide and does not rely on GitHub. Suggestions:

  • The download is integrity-checked against the built-in SHA-256 after completing. If you override the URL via the TRAEFIK_TARBALL environment variable (for example, to use your own object storage / internal mirror), you must also provide a matching SHA-256 via TRAEFIK_SHA256 so the integrity check still passes.

  • Recommended for production: bake the Traefik binary into a custom Sandbox template image so no download is needed at runtime (see Build a Sandbox Template from a GHCR Custom Image).

2. Port access returns 5xx? Confirm the exposed port is within [3000, 65535] and the corresponding service inside the Sandbox is already listening and ready.

3. How do I ensure secure access in production? Enable Sandbox access control (secure=True). When traffic tokens are enabled, accessing dynamic ports requires the X-Access-Token header, obtained via the public property sbx.traffic_access_token (this property is None when traffic tokens are not enabled, in which case no header is needed); see the cloud Sandbox "Secure Access" documentation for how to obtain and use the token. Never write access tokens into logs or front-end code.

4. How do I choose the version identification method? This document distinguishes versions by "response content" for demo simplicity; in production, prefer having the backend expose the version via a response header (such as X-App-Version)—it is out-of-band metadata that does not pollute the business response body and is easier for gateways, monitoring, and tracing to collect uniformly.

Complete example

Combine the steps above into a single runnable script canary_demo.py. Compared with the demo snippets in the procedure, this script adds production hardening: it creates the Sandbox with secure=True by default (automatically attaching X-Access-Token when traffic tokens are enabled in the environment), adds port-readiness polling, asserts the ratio for each weight tier, and cleans up processes and the Sandbox in a finally block. E2B_API_KEY, E2B_DOMAIN, and E2B_API_URL are all read from environment variables.

#!/usr/bin/env python3
"""A runnable example of Traefik-based service traffic canary routing inside a single Sandbox.

Hot-adjust weights in stages (100/0 -> 70/30 -> 30/70) to verify weight-based canary,
then use the X-Version header to verify header pinning (higher priority than the weighted split).
"""
from __future__ import annotations

import os
import sys
import time
from collections import Counter

import httpx

from e2b import Sandbox

TEMPLATE = os.environ.get("E2B_TEMPLATE_ID", "base")

TRAEFIK_PORT = 8080                 # Traefik external entry
V1_PORT, V2_PORT = 9000, 9001       # two backends (visible only inside the Sandbox)
N_REQUESTS = 100                    # number of sample requests per round
SANDBOX_TIMEOUT = 600               # sandbox lifetime in seconds
VERSION_HEADER = "X-Version"        # this header (value v1/v2) forces the matching version
WORKDIR = "/tmp/canary"

# Traefik binary served from the Serverless OSS global download domain. Override with the TRAEFIK_TARBALL env var
# to use an internal mirror; when overriding, you MUST also provide a matching SHA-256 via TRAEFIK_SHA256.
# In production, prefer baking the binary into a custom template (see "FAQ") so no download is needed at runtime.
TRAEFIK_TARBALL = os.environ.get(
    "TRAEFIK_TARBALL",
    "https://images.devsapp.cn/e2b/traefik/"
    "v3.7.8/traefik_v3.7.8_linux_amd64.tar.gz",
)
TRAEFIK_SHA256 = os.environ.get(
    "TRAEFIK_SHA256",
    "dbd809b1de85d86d0718c80bedbaabd9aebaa3c6697f9e986ab5f387f4196cb7",
)


# --------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------
def log(step: str, msg: str = "") -> None:
    print(f"\n[{step}] {msg}", flush=True)


def conn_opts() -> dict:
    """Assemble SDK connection parameters from environment variables."""
    api_key = os.environ.get("E2B_API_KEY")
    if not api_key:
        sys.exit("ERROR: E2B_API_KEY must be set")
    opts = {"api_key": api_key}
    for env, key in (("E2B_API_URL", "api_url"), ("E2B_DOMAIN", "domain")):
        if val := os.environ.get(env):
            opts[key] = val
    return opts


def auth(sbx: Sandbox) -> dict:
    """Sandboxes with traffic tokens enabled need X-Access-Token to access dynamic ports; traffic_access_token is None when not enabled."""
    token = sbx.traffic_access_token
    return {"X-Access-Token": token} if token else {}


def url(sbx: Sandbox, port: int = TRAEFIK_PORT, path: str = "/") -> str:
    return f"https://{sbx.get_host(port)}{path}"


def classify(resp: httpx.Response) -> str | None:
    """Determine which version was hit from the response body (backend homepage content is backend=v1 / backend=v2)."""
    if "backend=v2" in resp.text:
        return "v2"
    if "backend=v1" in resp.text:
        return "v1"
    return None


def wait_ready(sbx: Sandbox, port: int, expect: str, retries: int = 30) -> bool:
    """Poll a port until it returns 200 and the body contains expect."""
    for _ in range(retries):
        try:
            r = httpx.get(url(sbx, port), headers=auth(sbx), timeout=3)
            if r.status_code == 200 and expect in r.text:
                return True
        except (httpx.ConnectError, httpx.ReadTimeout, httpx.RemoteProtocolError):
            pass
        time.sleep(1)
    return False


def sample(sbx: Sandbox, n: int, version: str | None = None) -> Counter:
    """Make n requests (if version is set, add the X-Version header to pin the version); count hit versions by response body."""
    headers = auth(sbx)
    if version:
        headers[VERSION_HEADER] = version
    hits: Counter = Counter()
    with httpx.Client(timeout=5) as client:
        for _ in range(n):
            try:
                r = client.get(url(sbx), headers=headers)
                hits[classify(r) or f"other({r.status_code})"] += 1
            except Exception as exc:  # count exceptions too in this demo
                hits[f"error:{type(exc).__name__}"] += 1
    return hits


def show(hits: Counter, n: int) -> None:
    for k in sorted(hits):
        print(f"        {k:>12}: {hits[k]:>4}  ({hits[k] / n * 100:5.1f}%)", flush=True)


# --------------------------------------------------------------------------
# Backends & Traefik
# --------------------------------------------------------------------------
def start_backend(sbx: Sandbox, name: str, port: int):
    """Write a version marker page and start a python http.server as that version's backend."""
    sbx.files.write(f"{WORKDIR}/{name}/index.html", f"backend={name} port={port}\n")
    return sbx.commands.run(
        f"python3 -m http.server {port}", cwd=f"{WORKDIR}/{name}", background=True
    )


def dynamic_config(w1: int, w2: int) -> str:
    """Two-tier routing: header-pinned version (high priority) takes precedence over the default weighted (w1:w2) split."""
    return f"""\
http:
  routers:
    pin-v1:                                  # X-Version: v1 -> force v1
      rule: "Header(`{VERSION_HEADER}`, `v1`)"
      entryPoints: [web]
      service: v1
      priority: 100
    pin-v2:                                  # X-Version: v2 -> force v2
      rule: "Header(`{VERSION_HEADER}`, `v2`)"
      entryPoints: [web]
      service: v2
      priority: 100
    default:                                 # other traffic -> weighted split
      rule: "PathPrefix(`/`)"
      entryPoints: [web]
      service: weighted
      priority: 1
  services:
    weighted:
      weighted:
        services:
          - {{name: v1, weight: {w1}}}
          - {{name: v2, weight: {w2}}}
    v1:
      loadBalancer:
        servers: [{{url: "http://127.0.0.1:{V1_PORT}"}}]
    v2:
      loadBalancer:
        servers: [{{url: "http://127.0.0.1:{V2_PORT}"}}]
"""


def set_weights(sbx: Sandbox, w1: int, w2: int) -> None:
    """Write/overwrite dynamic.yml; Traefik has watch enabled and hot-reloads the new weights within seconds."""
    sbx.files.write(f"{WORKDIR}/dynamic.yml", dynamic_config(w1, w2))


# Download and unpack traefik inside the Sandbox, hardened with resumable download for rate-limited/broken connections.
GET_TRAEFIK = r'''
import os, shutil, subprocess, tarfile, time, urllib.request, hashlib
DEST, URL = "/tmp/canary", os.environ["TRAEFIK_TARBALL"]
SHA256 = os.environ.get("TRAEFIK_SHA256", "")
TAR, BIN = DEST + "/traefik.tar.gz", DEST + "/traefik"

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()

def done():
    try:
        with tarfile.open(TAR) as t:
            t.getmembers()
        return True
    except Exception:
        return False

def via_cmd(argv):
    for _ in range(10):
        if subprocess.call(argv) == 0 and done():
            return True
        time.sleep(2)
    return done()

def via_py():
    for _ in range(30):
        have = os.path.getsize(TAR) if os.path.exists(TAR) else 0
        try:
            req = urllib.request.Request(URL, headers={"Range": f"bytes={have}-", "User-Agent": "x"})
            with urllib.request.urlopen(req, timeout=60) as r:
                # if the server ignores Range it returns 200 + the full file; overwrite instead of appending
                mode = "ab" if have and r.status == 206 else "wb"
                with open(TAR, mode) as f:
                    shutil.copyfileobj(r, f, 1 << 20)
        except Exception:
            time.sleep(2)
            continue
        if done():
            return True
    return done()

ok = shutil.which("wget") and via_cmd(["wget", "-c", "-q", "-T", "60", "-O", TAR, URL])
if not ok and shutil.which("curl"):
    ok = via_cmd(["curl", "-fsSL", "-C", "-", "--max-time", "120", "-o", TAR, URL])
if not ok:
    ok = via_py()
if not ok:
    raise SystemExit("download failed")
# Require SHA-256 verification before extraction to reject tampered or incomplete downloads.
if not SHA256:
    raise SystemExit("TRAEFIK_SHA256 is required")
actual_sha256 = sha256(TAR)
if actual_sha256 != SHA256:
    raise SystemExit("sha256 mismatch: got %s, expected %s" % (actual_sha256, SHA256))
with tarfile.open(TAR) as t:
    t.extract("traefik", DEST)
os.chmod(BIN, 0o755)
print("traefik ready")
'''


def provision_traefik(sbx: Sandbox) -> None:
    sbx.files.write(f"{WORKDIR}/get_traefik.py", GET_TRAEFIK)
    res = sbx.commands.run(
        f"python3 {WORKDIR}/get_traefik.py",
        envs={"TRAEFIK_TARBALL": TRAEFIK_TARBALL, "TRAEFIK_SHA256": TRAEFIK_SHA256},
        timeout=600,
    )
    if res.exit_code != 0:
        raise RuntimeError(f"Failed to download traefik; point TRAEFIK_TARBALL to an internal mirror:\n{res.stderr}")


def start_traefik(sbx: Sandbox):
    """Start the traefik process (dynamic.yml must be written first by set_weights)."""
    cmd = (
        f"{WORKDIR}/traefik"
        f" --entrypoints.web.address=:{TRAEFIK_PORT}"
        f" --providers.file.filename={WORKDIR}/dynamic.yml"
        f" --providers.file.watch=true"
        f" --api.dashboard=false --log.level=INFO --accesslog=true"
    )
    return sbx.commands.run(cmd, background=True)


# --------------------------------------------------------------------------
# Main flow: hot-adjust weights in stages (100/0 -> 70/30 -> 30/70), sampling each time to verify the ratio
# --------------------------------------------------------------------------
def check_ratio(sbx: Sandbox, w1: int, w2: int) -> None:
    """Sample N times and verify the v1 ratio is close to w1/(w1+w2)."""
    hits = sample(sbx, N_REQUESTS)
    show(hits, N_REQUESTS)
    # First reject errors/unknown responses, then validate the weighted ratio.
    assert hits["v1"] + hits["v2"] == N_REQUESTS, f"unexpected hits: {dict(hits)}"
    exp_v1 = w1 / (w1 + w2) * 100
    got_v1 = hits["v1"] / N_REQUESTS * 100
    # weighted round-robin is a deterministic interleave; ±12 percentage points covers jitter
    assert abs(got_v1 - exp_v1) <= 12, f"ratio deviation: v1={got_v1:.0f}% expected≈{exp_v1:.0f}%"


def reweight(sbx: Sandbox, w1: int, w2: int) -> None:
    """Hot-update weights and wait for the file provider to reload."""
    set_weights(sbx, w1, w2)
    time.sleep(3)  # file provider watch hot-reload latency is about 1~2s


def main() -> int:
    log("create", f"create sandbox (template={TEMPLATE})")
    sbx = Sandbox.create(template=TEMPLATE, timeout=SANDBOX_TIMEOUT, secure=True, **conn_opts())
    print(f"    sandbox_id = {sbx.sandbox_id}", flush=True)

    procs = []
    try:
        # 1. start v1 service
        log("1", f"start v1 service: http.server:{V1_PORT}")
        procs.append(start_backend(sbx, "v1", V1_PORT))
        if not wait_ready(sbx, V1_PORT, "v1"):
            raise RuntimeError("v1 not ready")

        # start traefik (initial weight 100/0, only v1 exists at this point)
        log("traefik", "download and start traefik")
        provision_traefik(sbx)
        set_weights(sbx, 100, 0)
        procs.append(start_traefik(sbx))
        if not wait_ready(sbx, TRAEFIK_PORT, "backend="):
            raise RuntimeError("traefik entry not ready")
        print(f"    external URL: {url(sbx)}", flush=True)

        # 2. test requests to v1 (through traefik, expect all v1)
        log("2", f"test requests to v1 ({N_REQUESTS} times, expect 100% v1)")
        check_ratio(sbx, 100, 0)

        # 3. start v2 service
        log("3", f"start v2 service: http.server:{V2_PORT}")
        procs.append(start_backend(sbx, "v2", V2_PORT))
        if not wait_ready(sbx, V2_PORT, "v2"):
            raise RuntimeError("v2 not ready")

        # 4. hot-adjust weights in stages, sampling each time to verify the ratio: 100/0 -> 70/30 -> 30/70
        for w1, w2 in ((100, 0), (70, 30), (30, 70)):
            log(f"weight {w1}/{w2}", f"hot-reload weight and sample {N_REQUESTS} times to verify the ratio")
            reweight(sbx, w1, w2)
            check_ratio(sbx, w1, w2)

        # 5. Header pinning: force the specified version with the X-Version header (higher priority than default weighting)
        for want in ("v1", "v2"):
            log(f"Header {want}", f"with {VERSION_HEADER}: {want}, sample {N_REQUESTS} times, expect 100% {want}")
            hits = sample(sbx, N_REQUESTS, version=want)
            show(hits, N_REQUESTS)
            assert hits[want] == N_REQUESTS, f"Header pin {want} did not all hit: {dict(hits)}"

        print("\nStaged weighting + Header pinning verified ✔", flush=True)
        return 0
    finally:
        log("cleanup", "clean up processes and sandbox")
        for p in procs:
            try:
                sbx.commands.kill(p.pid)
            except Exception:
                pass
        sbx.kill()


if __name__ == "__main__":
    raise SystemExit(main())

Set the environment variables, then run it directly:

export E2B_API_KEY="<your-e2b-api-key>"
export E2B_DOMAIN="us-west-1.e2b.fc.aliyuncs.com"
export E2B_API_URL="https://api.us-west-1.e2b.fc.aliyuncs.com"
python3 canary_demo.py

A normal run prints the split ratio for each stage, closely matching the configured weights:

[create] create sandbox (template=base)
    sandbox_id = sbx-xxxxxxxx
    external URL: https://8080-sbx-xxxxxxxx.us-west-1.e2b.fc.aliyuncs.com/

[2] test requests to v1 (100 times, expect 100% v1)
                  v1:  100  (100.0%)

[weight 70/30] hot-reload weight and sample 100 times to verify the ratio
                  v1:   70  ( 70.0%)
                  v2:   30  ( 30.0%)

[weight 30/70] hot-reload weight and sample 100 times to verify the ratio
                  v1:   30  ( 30.0%)
                  v2:   70  ( 70.0%)

[Header v1] with X-Version: v1, sample 100 times, expect 100% v1
                  v1:  100  (100.0%)

[Header v2] with X-Version: v2, sample 100 times, expect 100% v2
                  v2:  100  (100.0%)

Staged weighting + Header pinning verified ✔