Warm pool autoscaling

Updated at:

PoolAutoscaler automatically adjusts the size of a warm pool based on the number of available sandboxes and cron schedules. It replenishes the pool when available sandboxes are insufficient and scales the pool in when sandboxes are idle, which balances the claim latency against the pre-warming costs.

Background information

PoolAutoscaler updates the spec.replicas field of a SandboxSet based on the number of unclaimed sandboxes and the configured cron schedules. It replenishes the pool when the number of available sandboxes is insufficient, scales the pool in when too many sandboxes are idle, and pre-warms the pool in advance before a known traffic peak.

Unlike autoscaling that is based on CPU or QPS metrics, PoolAutoscaler does not collect business metrics or predict traffic. It only manages the capacity of the warm pool. After a sandbox is claimed, the lifecycle of the business session is still handled by Agent Sandbox. For more information about the basic concepts of warm pools and how to create a warm pool, see Create an Agent Sandbox.

Use cases

This feature is suitable for the following scenarios:

  • Request volume changes over time: For example, you use the E2B API (the API of an open-source sandbox service) to create, use, and release sandboxes. You want to always keep a specific number of available sandboxes to reduce the wait time of claims.

  • Peak hours are predictable: For example, before the start of the workday on weekdays, before scheduled tasks run, or before an event starts. Create the warm pool in advance at a specified time.

  • Two types of traffic coexist: The capacity policy replenishes the pool on a daily basis, and a cron policy specifies the pre-warming size during known peaks.

Applicable scope

  • The ack-agent-sandbox-controller add-on is installed with version v0.6.6-release.5 or later. PoolAutoscaler is provided and enabled by default starting from this version. No additional configuration is required. Earlier versions do not support this feature and you must upgrade the add-on first. If the add-on version meets the requirement but you still cannot create a PoolAutoscaler, explicitly enable the feature by using the startup parameter --feature-gates=PoolAutoscaler=true. For more information about the versions, change records, and installation methods, see ack-agent-sandbox-controller usage notes.

  • A SandboxSet that you want to manage is created, and the SandboxSet controller runs as expected. For more information, see Create an Agent Sandbox.

  • Within the same namespace, a SandboxSet can be managed by at most one PoolAutoscaler.

  • Configure at least one of the following policies for the PoolAutoscaler: capacityPolicy or cronPolicies.

Limits

  • PoolAutoscaler only modifies the spec.replicas field of the specified SandboxSet. It does not directly create or delete pods. Do not allow an HPA (Horizontal Pod Autoscaler), an AHPA (Advanced Horizontal Pod Autoscaler), a script, or another controller to modify the same field at the same time. Otherwise, the scaling results overwrite each other.

  • The PoolAutoscaler and the SandboxSet must be in the same namespace.

Scenario 1: Automatically replenish the pool based on available capacity

This scenario applies to workloads whose request volume is difficult to predict accurately but that need consistently low claim latency. For example, a workload continuously creates sandboxes by using the E2B API to run code or commands, and then releases the sandboxes. Each claim consumes an available sandbox in the warm pool. The capacity policy replenishes the unclaimed sandboxes accordingly.

Step 1: Create a warm pool by using a SandboxSet

If a warm pool already exists, reuse the existing SandboxSet. The following sample provides the minimum configuration. The comments describe each field. Replace the fields that are marked as required replacements with values that are verified in your cluster.

  1. Save the following content as sandboxset.yaml.

    apiVersion: agents.kruise.io/v1alpha1
    kind: SandboxSet
    metadata:
      name: sandbox-pool        # The name of the SandboxSet. The PoolAutoscaler in Step 2 refers to the pool by this name. Change the name
      namespace: default        # The namespace in which the pool is deployed. The PoolAutoscaler must be in the same namespace
    spec:
      replicas: 2               # The initial size of the warm pool. After the PoolAutoscaler is applied, the PoolAutoscaler takes over this value. Set a smaller value to reduce costs
      scaleStrategy:
        maxUnavailable: "30%"   # Recommended. Also serves as the startup budget. Scale-up is paused when the number of startup failures or timeouts reaches this value
      runtimes:
        - name: agent-runtime   # Injects the envd-compatible runtime, which the code execution, file, and command features in Step 3 depend on
      template:
        spec:
          containers:
            - name: sandbox
              image: <YOUR-SANDBOX-IMAGE>   # Required replacement: the Agent Sandbox runtime image that can be pulled in the cluster
              resources:
                requests:         # The resources requested for scheduling, which affect the cost of each instance in the warm pool and the nodes on which the instance can be placed
                  cpu: "1"
                  memory: 1Gi
                limits:           # The upper limits of resources. Adjust the values based on your workload requirements. Excessive values waste pre-warming costs, and insufficient values affect startup
                  cpu: "1"
                  memory: 1Gi
  2. Create the warm pool and view its status.

    kubectl apply -f sandboxset.yaml
    kubectl get sandboxset sandbox-pool -n default
    runtimes: agent-runtime is a prerequisite for the E2B verification in Step 3 (run_code, file read and write, and command execution all depend on the injected envd runtime). For more information about the runtime injection mechanism and its dependency on the sandbox-injection-config ConfigMap, see Configure automatic sidecar injection for Agent Sandbox.

Step 2: Configure a PoolAutoscaler

The following policy maintains the warm pool based on a ratio. The target available ratio is 50%, and the default tolerance of 10% is used. The pool scales up when the recent average available ratio falls below 40%, and scales down when the ratio exceeds 60%. No adjustment is made if the ratio is between the two thresholds. Percentage-based watermarks change with the size of the pool, which is suitable for workloads with fluctuating loads.

  1. Save the following content as pool-autoscaler.yaml.

    apiVersion: agents.kruise.io/v1alpha1
    kind: PoolAutoscaler
    metadata:
      name: sandbox-pool-autoscaler   # The name of the PoolAutoscaler. It is used only for identification and subsequent kubectl queries. Change the name
      namespace: default              # Must be in the same namespace as the specified SandboxSet
    spec:
      scaleTargetRef:
        apiVersion: agents.kruise.io/v1alpha1
        kind: SandboxSet              # Only SandboxSet is supported. This field cannot be changed
        name: sandbox-pool            # The name of the SandboxSet that is created in Step 1
      minReplicas: 2                  # The lower limit of the warm pool. A percentage target must meet the scale-down reachability rules. For more information, see the following sections
      maxReplicas: 50                 # The upper limit of the warm pool. Set the value based on the peak concurrency of your workload and the cluster capacity
      capacityPolicy:
        targetAvailable: "50%"        # The target ratio of unclaimed (available) sandboxes to the number of replicas. The ratio changes with the size of the pool
        # If tolerance is not configured, the default value is 10%. Combined with the target, the value forms a no-adjustment range of 40% to 60%
        scaleUp:
          stabilizationWindowSeconds: 60    # The scale-up stabilization window, which is the minimum interval between two consecutive scale-up operations. A smaller value speeds up pool replenishment, but an excessively small value causes too frequent scale-ups
        scaleDown:
          stabilizationWindowSeconds: 300   # The scale-down stabilization window, which is the minimum interval between two consecutive scale-down operations. A longer value prevents the warm pool from being frequently reclaimed when traffic fluctuates
    
  2. Create the PoolAutoscaler and view its status.

    kubectl apply -f pool-autoscaler.yaml
    kubectl get poolautoscaler sandbox-pool-autoscaler -n default

minReplicas and maxReplicas always take effect. The number of replicas that is calculated by all policies is limited to this range. The values of targetAvailable, tolerance, and minReplicas jointly determine whether an idle warm pool can scale in to minReplicas. For more information about the configuration rules, see the Capacity policy tuning.

Set a longer stabilization window for scale-down than for scale-up. By default, the scale-up window is 60 seconds and the scale-down window is 300 seconds. The preceding example also keeps this relationship. A quick scale-up replenishes the warm pool in a timely manner to ensure a low claim latency. A slow scale-down prevents transient traffic drops from reclaiming pre-warmed capacity and causing capacity jitter.

Step 3: Verify the policy with E2B business traffic

The following single-file script simulates real business traffic. Each concurrent loop claims a sandbox from the warm pool, runs code, reads and writes files, runs commands, and then releases the sandbox after a short hold. Observe the scaling status of the warm pool by using the commands in Step 4.

Preparations:

  1. Python 3.9 or later is installed on your on-premises machine, and the kubeconfig file of the target cluster is configured for kubectl to observe the status.

  2. Install the E2B SDK. The version must be compatible with the ack-sandbox-manager add-on: pip install e2b-code-interpreter.

  3. Prepare an accessible E2B service domain name and API key. If the cluster uses self-signed certificates, prepare a CA certificate.

Save the script as poolautoscaler-verify.py.

#!/usr/bin/env python3
"""Generate E2B business traffic against a PoolAutoscaler-managed pool.

Usage:
  E2B_API_KEY='<YOUR-E2B-API-KEY>' \
  E2B_DOMAIN='<YOUR-E2B-DOMAIN>' \
  SSL_CERT_FILE='<YOUR-CA-FILE>' \
  python poolautoscaler-verify.py --template sandbox-pool
"""
import argparse, os, sys, threading, time
from concurrent.futures import ThreadPoolExecutor

stop = threading.Event()

def business_loop(loop_id, template, hold, deadline):
    """One worker: claim a sandbox, run business calls, hold, then release."""
    from e2b_code_interpreter import Sandbox
    seq = 0
    while time.monotonic() < deadline and not stop.is_set():
        seq += 1
        sandbox = None
        try:
            # no timeout: the SDK timeout is the sandbox lifetime, not a create wait
            sandbox = Sandbox.create(template=template)
            sandbox.run_code(f"print('loop={loop_id} seq={seq}')")
            path = f"verify-{loop_id}-{seq}.txt"
            content = f"loop={loop_id} seq={seq}\n"
            sandbox.files.write(path, content)
            assert sandbox.files.read(path) == content, "file content mismatch"
            assert sandbox.commands.run(f"cat {path}").stdout == content
            stop.wait(hold)          # simulate the business holding the sandbox
            sandbox.kill()
        except Exception as exc:
            if sandbox is not None:
                try:
                    sandbox.kill()   # release the claimed sandbox before backing off
                except Exception:
                    pass
            print(f"loop {loop_id} seq {seq} failed: "
                  f"{type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
            stop.wait(5)             # back off before the next attempt
 
 
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--template", default="sandbox-pool",
                        help="SandboxSet name, i.e. the E2B template")
    parser.add_argument("--concurrency", type=int, default=10,
                        help="simultaneous business sandboxes; each consumes one pool slot")
    parser.add_argument("--duration-seconds", type=int, default=300)
    parser.add_argument("--hold-seconds", type=int, default=30,
                        help="how long each loop holds its sandbox before releasing")
    args = parser.parse_args()
    if not os.getenv("E2B_API_KEY"):
        parser.error("E2B_API_KEY must be set")

    deadline = time.monotonic() + args.duration_seconds
    print(f"load: {args.concurrency} loops x {args.duration_seconds}s, "
          f"hold={args.hold_seconds}s (Ctrl+C stops early)", flush=True)
    try:
        with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
            futures = [pool.submit(business_loop, i, args.template,
                                   args.hold_seconds, deadline)
                       for i in range(args.concurrency)]
            for future in futures:
                future.result()
    except KeyboardInterrupt:
        print("interrupted; waiting for in-flight sandboxes to settle...", flush=True)
    finally:
        stop.set()
    return 0


if __name__ == "__main__":
    main()

Run the script. Open another terminal to run the observation commands in Step 4 so that you can view scale-up events in real time:

E2B_API_KEY='<YOUR-E2B-API-KEY>' \
E2B_DOMAIN='<YOUR-E2B-DOMAIN>' \
SSL_CERT_FILE='<YOUR-CA-FILE>' \
python poolautoscaler-verify.py \
  --template sandbox-pool \
  --concurrency 10 \
  --duration-seconds 300 \
  --hold-seconds 30

Parameter descriptions:

  • --concurrency: The number of concurrent claims. Keep the value at or below the steady-state number of available sandboxes in the pool, which is determined by minReplicas and targetAvailable. If the number of concurrent claims exceeds this value, the warm pool is depleted and the first data plane call may return the 503 error. This is an expected behavior. Try again later. It takes about 20 to 30 seconds to replenish the pool.

  • --hold-seconds: The period of time for which each sandbox is held by the workload. A longer period results in fewer claims per unit of time.

  • --duration-seconds: The total duration of the load test. Set the value to at least three times the scale-up stabilization window (60 seconds by default) so that at least two rounds of scale-up can be observed.

Expected result: During the load test, run the commands in Step 4 to observe that the value of currentCapacity.available decreases and desiredReplicas increases step by step. This indicates that the capacity policy detects the consumption caused by claims and replenishes the warm pool. If the warm pool is depleted, the create operation still returns the running state, but the data plane may not be ready. The first call returns the 503 error as expected. Try again later.

Optional: Verify the scale-down. After the traffic stops, manually reduce the value of targetAvailable and observe how the warm pool converges.

kubectl patch poolautoscaler sandbox-pool-autoscaler -n default \
  --type merge -p '{"spec":{"capacityPolicy":{"targetAvailable":"10%"}}}'
kubectl get sandboxset sandbox-pool -n default -w

The warm pool should gradually scale in to minReplicas (2 in this example). After the verification is complete, restore the value of targetAvailable to the original value.

Step 4: Observe the scaling cadence and startup protection

kubectl get poolautoscaler sandbox-pool-autoscaler -n default -o yaml
kubectl get sandboxset sandbox-pool -n default -o yaml
kubectl describe poolautoscaler sandbox-pool-autoscaler -n default

Check the status.currentReplicas, status.desiredReplicas, status.currentCapacity.available, and status.conditions. These are the observed values of the most recent reconcile operation, which is the process in which the controller periodically aligns the actual state with the desired state. The values may be temporarily inconsistent with the real-time status of the SandboxSet. If the number of available sandboxes is 0, the status.currentCapacity.available field is not displayed. The scaling actions and the causes of exceptions are recorded as events on the PoolAutoscaler object. For more information about common events, see the Common events.

The capacity policy makes decisions based on the average number of available sandboxes within a recent observation period to smooth out transient fluctuations. The first scale-up or scale-down can be performed immediately, and subsequent operations follow the stabilization windows. The scale-up stabilization window is 60 seconds by default, and the scale-down stabilization window is 300 seconds by default. Adjust the windows by using stabilizationWindowSeconds. For more information, see the Parameter constraints section in this topic. The default value of the scale-up stabilization window includes a safety margin for Pending timeouts. If you configure a larger value, the configured value takes precedence.

When the SandboxSet reports ScalingLimited=True for the current generation, PoolAutoscaler pauses further scale-up. This prevents the target from continuing to increase after the startup budget is exhausted by startup failures or Pending timeouts. Scale-down is not affected. The concurrency of sandbox creation is controlled by the SandboxSet. PoolAutoscaler does not directly manage pods. For more information about the trigger conditions, recovery methods, and troubleshooting steps of scale-up throttling, see the Troubleshooting: scale-up throttling triggers and recovery.

Tuning suggestions: Start with a small scope. Set small values for minReplicas and maxReplicas, and set a longer scale-down stabilization window. Then adjust the values based on the startup success rate, the claim latency, and the pre-warming costs. If you need to temporarily observe the pool or take manual control, pause the auto scaling. To resume the auto scaling, set this parameter to false or remove the field:

kubectl patch poolautoscaler sandbox-pool-autoscaler -n default \
  --type merge -p '{"spec":{"suspend":true}}'

Step 5: (Optional) Delete the PoolAutoscaler

If you no longer require auto scaling, for example, when the workload is retired or the pool is set to a fixed size, you can delete the PoolAutoscaler. After the PoolAutoscaler is deleted, the SandboxSet and all existing sandboxes are retained. The number of SandboxSet replicas remains the value before the deletion and does not automatically scale in. To reclaim the warm pool, manually adjust spec.replicas or delete the SandboxSet.

Warning

If you delete the SandboxSet, all sandboxes in the warm pool are deleted, including the sandboxes that are claimed by workloads and still running. The business sessions are interrupted and the deletion cannot be undone. Reclaim the warm pool in the following order: first, reduce spec.replicas or set it to 0. After you confirm that all sandboxes in the pool are released by workloads, delete the SandboxSet.

kubectl delete poolautoscaler sandbox-pool-autoscaler -n default

Scenario 2: Pre-warm the pool in advance based on a schedule

This scenario applies to workloads with specific peak hours. For example, a large number of users create development environments before 09:00 on each weekday. The cron policy sets the target of the warm pool before the peak period starts, instead of waiting until the available sandboxes are exhausted.

The following example sets the warm pool to 30 replicas at 08:30 on weekdays and adjusts the pool to 5 replicas at 20:00.

  1. Save the following content as pool-autoscaler-cron.yaml.

    apiVersion: agents.kruise.io/v1alpha1
    kind: PoolAutoscaler
    metadata:
      name: sandbox-pool-schedule   # Used only for identification. Change the name
      namespace: default            # Must be in the same namespace as the specified SandboxSet
    spec:
      scaleTargetRef:
        apiVersion: agents.kruise.io/v1alpha1
        kind: SandboxSet            # Only SandboxSet is supported
        name: sandbox-pool          # Required replacement: the name of an existing SandboxSet
      minReplicas: 2                # The lower limit. The cron target is also limited to this range
      maxReplicas: 50               # The upper limit. The value must be greater than or equal to the largest targetReplicas in all cron policies
      cronPolicies:
        - name: weekday-peak        # The name of the policy, which must be unique in the same PoolAutoscaler
          timeZone: Asia/Shanghai   # If this parameter is not configured, the time zone of the controller is used. Specify the time zone
          schedule: "30 8 * * 1-5"  # A five-field cron expression: minute hour day-of-month month day-of-week. This example runs at 08:30 on weekdays
          targetReplicas: 30        # Sets the warm pool to 30 replicas when the policy is triggered. The value cannot exceed maxReplicas
        - name: weekday-offpeak
          timeZone: Asia/Shanghai
          schedule: "0 20 * * 1-5"  # Scales the pool back to the off-peak size at 20:00 on weekdays
          targetReplicas: 5
  2. Create the PoolAutoscaler and view its status.

    kubectl apply -f pool-autoscaler-cron.yaml
    kubectl get poolautoscaler sandbox-pool-schedule -n default

cronPolicies uses five-field cron expressions: minute, hour, day of month, month, and day of week. If timeZone is not configured, the time zone of the controller manager process is used. When the cron schedule is triggered, the number of replicas is immediately adjusted to the targetReplicas of the policy. This is not limited by the stabilization window of the capacity policy. The final number of replicas is still limited by minReplicas and maxReplicas. Scale-up is also limited by the startup protection of the SandboxSet. For more information, see the Troubleshooting: scale-up throttling triggers and recovery.

If you configure both policies, the capacity policy replenishes the pool when no cron policy is triggered. Between two cron triggers, the capacity policy continuously adjusts the number of replicas based on the available capacity watermarks. The number of replicas may deviate from the cron target, including downward adjustments. The cron target is not a capacity limit that always takes effect. The cron policy directly specifies the target number of replicas and is not subject to the watermark and scale-down reachability rules of the capacity policy. However, scale-up throttling still applies: if the cron policy raises the target when the startup budget of the SandboxSet is exhausted, the scale-up is blocked and waits until the budget is released. To ensure a minimum capacity during a cron period, specify the capacity by using minReplicas, which always takes effect. Do not set the cron target below the expected watermark of the capacity policy. Otherwise, the number of replicas repeatedly changes between the two targets.

Troubleshooting: scale-up throttling triggers and recovery

Scale-up throttling is a startup protection mechanism of the SandboxSet. When too many sandboxes fail to start or stay Pending at the same time, the system pauses further replica increases to avoid creating more sandboxes that cannot start. PoolAutoscaler reads this signal and pauses scale-up.

Trigger conditions

The spec.scaleStrategy.maxUnavailable field of the SandboxSet also serves as the startup budget. If this field is not configured, its value defaults to the current number of replicas, which is equivalent to 100%. In this case, throttling is triggered only when all instances fail to start. Note that this field is different from updateStrategy.maxUnavailable, which is used for rolling updates and defaults to 20%. Sandboxes in the creation phase consume the budget based on the following two types of counts:

  • Failed: The Ready condition is False and the reason is StartContainerFailed, PodCreateFailed, or Unschedulable. This indicates an explicit startup failure, such as a container startup failure, an image or configuration error, a creation API failure, or a scheduling failure caused by insufficient node resources or underlying scheduling errors.

  • TimedOut: The sandbox remains in the Creating or ResourcePending state for an extended period of time, and the sandbox is still not ready after the Pending timeout threshold is exceeded. By default, the threshold is 50 seconds. This count is displayed in the status message and the events of the SandboxSet as Timeout.

Note

An image pull failure ImagePullBackOff is not counted as Failed. Instead, it is counted as Timeout after the Pending threshold (50 seconds by default) is exceeded. In this case, the reason of the Ready condition of the pod is still PodReady.

When Failed + TimedOut >= the startup budget, the SandboxSet writes the following status and sends a Warning-level ScalingLimited event.

apiVersion: agents.kruise.io/v1alpha1
kind: SandboxSet
metadata:
  name: sandbox-pool
  namespace: default
status:
  conditions:
    - type: ScalingLimited
      status: "True"
      reason: StartupBudgetExhausted
      message: '2 of 2 startup slots are blocked: Timeout=1, Failed=1'

After PoolAutoscaler detects this condition:

  • Scale-up is paused: the value of status.desiredReplicas no longer increases, even if the number of available sandboxes falls below the lower watermark. During the waiting period, a Normal-level ScaleBlocked event is periodically sent.

  • Scale-down is not affected: the scale-down operations that are triggered by the upper watermark are performed as usual.

  • Fault tolerance: the scale-up is blocked only if the SandboxSet reports an explicit True for the current generation. If the condition is missing, outdated, or Unknown, the system treats it as no signal and scale-up proceeds as usual. This prevents false blocks during upgrades or the first reconcile operation.

Important

Note that two conditions have the same name. The ScalingLimited condition in the status of the SandboxSet indicates that the startup budget is exhausted. The ScalingLimited condition of the PoolAutoscaler itself (for more information, see the CRD field reference in this topic) indicates that the desired number of replicas reaches the minReplicas/maxReplicas limits. The two conditions have different meanings.

Recovery methods

No manual intervention is required for recovery. The budget is automatically released after one of the following conditions is met:

  • The failed sandbox is deleted, either manually or by the workload, or its pod returns to the Running state and the Ready condition changes to True;

  • A sandbox that times out in the Pending state completes the startup and enters the Running state, or the sandbox is deleted.

When Failed + TimedOut decreases to a value below the budget, the next reconcile operation of the SandboxSet changes ScalingLimited back to False. Then PoolAutoscaler resumes scale-up and continues to replenish the pool.

Troubleshooting and solutions

# Query the throttling status and the Timeout/Failed counts
kubectl get sandboxset sandbox-pool -n default -o jsonpath='{.status.conditions[?(@.type=="ScalingLimited")]}'
kubectl describe sandboxset sandbox-pool -n default

# Query the throttling and blocking events
kubectl get events -n default --field-selector involvedObject.name=sandbox-pool

# List the sandboxes in the warm pool and their states
kubectl get sandbox -n default -l agents.kruise.io/sandbox-pool=sandbox-pool

# Query the Ready condition and the specific cause of a failed instance
kubectl get sandbox <YOUR-SANDBOX-NAME> -n default -o jsonpath='{.status.conditions[?(@.type=="Ready")]}'

Identify the main issue based on the counts in the message:

  • Mostly Failed: The issue is mostly caused by image pull failures, invalid resource configurations, or insufficient quotas. Check the message of the Ready condition of the failed sandbox to identify the cause, fix the SandboxSet configuration, and then delete the failed sandbox.

    kubectl delete sandbox <YOUR-SANDBOX-NAME> -n default

    The SandboxSet automatically recreates a sandbox. If the configuration is not fixed, the new sandbox still fails and triggers throttling again.

  • Mostly TimedOut: The underlying creation speed cannot keep up with the scaling pace. Explicitly set a smaller scaleStrategy.maxUnavailable value for the SandboxSet to trigger throttling at the earliest opportunity and pause further increases in the number of replicas. Alternatively, contact the cluster administrator to evaluate the underlying provisioning capacity.

Important

An image pull failure usually results in a high Timeout count and a Failed count of 0. The message is in the format of "Timeout=N, Failed=0". Check the kubectl describe pod events of ImagePullBackOff to determine whether the issue is caused by an invalid image address or credentials. Do not troubleshoot based only on the Failed count.

Common events

PoolAutoscaler records the scaling actions and the causes of exceptions as events on its own object during each reconcile operation. Use the following commands to view the events:

# List the events of the PoolAutoscaler
kubectl describe poolautoscaler sandbox-pool-autoscaler -n default

# Filter the events by object
kubectl get events -n default --field-selector involvedObject.name=sandbox-pool-autoscaler

Event (reason)

Level

Description and solution

ScaledUp

Normal

The number of replicas increases. The message contains the values before and after the adjustment and the reason for the decision. For example, the number of available sandboxes falls below the lower watermark (available below lower watermark) or a cron policy is triggered.

ScaledDown

Normal

The number of replicas decreases. The message contains the values before and after the adjustment and the reason for the decision. For example, the number of available sandboxes exceeds the upper watermark, or the scale-down is limited by the lower limit minReplicas.

ScaleBlocked

Normal

A scaling action is suppressed. The target is still within the stabilization window of the corresponding direction. The message is in the format of blocked by stabilization window (cooldown remaining: 45s). A long window is displayed in the format of 3m55s. During the cooldown period, the event is repeated and the count is aggregated in each reconcile operation. Or the scale-up is suppressed because the startup budget of the SandboxSet is exhausted. The message is in the format of scaling blocked by SandboxSet ScalingLimited condition (reason=StartupBudgetExhausted). The event is sent when the block starts or when the corresponding condition changes.

FailedGetScale

Warning

The specified SandboxSet cannot be read. Check whether scaleTargetRef.name is spelled correctly, and check whether the SandboxSet and the PoolAutoscaler are in the same namespace.

FailedComputeReplicas

Warning

The desired number of replicas fails to be calculated. This is usually caused by an invalid policy configuration. For more information, see the Parameter constraints section in this topic, and check the values of capacityPolicy and cronPolicies.

FailedScale

Warning

The new number of replicas fails to be written to the SandboxSet. For example, an API conflict occurs or the webhook rejects the request. The controller automatically retries the operation. If the error persists, troubleshoot the issue.

When the startup budget is exhausted, the SandboxSet sends a Warning-level ScalingLimited event on its own object. This event appears in pairs with the ScaleBlocked event on the PoolAutoscaler side. For more information, see the Troubleshooting: scale-up throttling triggers and recovery.

Capacity policy tuning

The capacity policy calculates the upper and lower watermarks based on the target value and the tolerance:

  • targetAvailable is an absolute value, such as 10: the lower watermark is the target value minus the tolerance, and the upper watermark is the target value plus the tolerance.

  • targetAvailable is a percentage, such as "60%": the calculation is based on the recent average number of replicas. The percentages of the target and the tolerance are combined and rounded up. The lower watermark = ceil(average number of replicas × (target - tolerance)%), the upper watermark = ceil(average number of replicas × (target + tolerance)%).

  • tolerance defaults to 10%. If the target is a percentage, the percentages are combined. If the target is an absolute value, the default tolerance is 10% of the target value, rounded up. For example, if the target is 10, the tolerance is 1. If the target is 15, the tolerance is 2.

The pool scales up when the average number of available sandboxes falls below the lower watermark, and is replenished to around the target value. The pool scales down when the average number exceeds the upper watermark. No adjustment is made if the number is between the two watermarks.

Warning

Do not set targetAvailable to "100%". The number of available sandboxes is at most equal to the number of replicas and never strictly exceeds the upper watermark. Therefore, the idle warm pool never scales down regardless of the tolerance. Use a 100% target only if you want the pool size to never decrease.

Ensure that an idle warm pool can scale in to minReplicas

The capacity policy must ensure that an idle warm pool can scale in to minReplicas. Otherwise, the warm pool remains above minReplicas, and idle resources cannot be reclaimed to the expected lower limit. To make this determination, check the last scale-down step: when the number of replicas in the warm pool is minReplicas + 1, the upper watermark must be no greater than minReplicas. Otherwise, this scale-down cannot be triggered.

  • For an absolute target T and a resolved tolerance D (including the default tolerance), the following condition must be met: T + D <= minReplicas. If the condition is met, the stable size of an idle warm pool is minReplicas.

  • For a percentage target p% and a percentage tolerance q% (including the default tolerance), the following condition must be met: p + q <= 100 × minReplicas / (minReplicas + 1). The percentage watermarks decrease as the warm pool scales in, and the pool gradually converges to minReplicas.

  • For a percentage target with an absolute tolerance D: The condition is evaluated when the number of replicas is minReplicas + 1. The following condition must be met: ceil((minReplicas + 1) × p%) + D <= minReplicas.

  • For an absolute target T with a percentage tolerance q%: The tolerance is resolved as ceil(T × q%). The following condition must be met: T + ceil(T × q%) <= minReplicas.

The following table describes the effects of common configurations:

minReplicas

targetAvailable

tolerance

Upper watermark when the number of replicas is minReplicas+1

Effect

1

"40%"

Default ("10%")

1

Scales in from 2 replicas to 1 replica

1

"50%"

Default ("10%")

2

The upper watermark is 2. The pool remains at 2 replicas.

1

1

0

1

Keeps one available sandbox as the guaranteed minimum

1

1

Default ("10%")

2

The default tolerance raises the upper watermark to 2. The pool remains at 2 replicas.

2

"50%"

Default ("10%")

2

Scales in from 3 replicas to 2 replicas. This is the example in Scenario 1.

1

"100%"

Any (including 0)

>= the number of replicas

The number of available sandboxes is at most equal to the number of replicas and never exceeds the upper watermark. The idle pool never scales down.

4

"70%"

"10%"

4

Scales in from 5 replicas to 4 replicas

Scenario 1 shows how to configure a percentage target. The watermarks change with the size of the pool, which is suitable for workloads with fluctuating loads. If you require a warm pool of a fixed size, use an absolute target and set tolerance: 0, and make sure that minReplicas is not less than the target value. In both cases, check minReplicas against the rules above.

If the warm pool remains at a size that is greater than minReplicas for an extended period of time and no exceptions are reported in status.conditions, the preceding rules are usually not met. In this case, reduce targetAvailable or tolerance, or increase minReplicas. Then observe whether status.desiredReplicas and status.currentCapacity.available gradually converge.

Parameter constraints

When you create or update a PoolAutoscaler, a webhook validates the following rules. If a rule is violated, the request is rejected and the HTTP 422 status code is returned with the specific cause.

General constraints

Field

Constraint

spec.scaleTargetRef.kind

Only SandboxSet is supported.

spec.scaleTargetRef.name

Required. The value must point to an existing SandboxSet in the same namespace. If the SandboxSet does not exist, the creation is not blocked. Only a FailedGetScale Warning event is generated. Run kubectl describe poolautoscaler <name> to view the events and identify the cause. For more information about the event summary, see the Common events.

spec.maxReplicas

Required and must be greater than 0.

spec.minReplicas

Must be greater than or equal to 0 and cannot be greater than maxReplicas.

spec.capacityPolicy / spec.cronPolicies

At least one of the two policies must be configured. Otherwise, no policy drives the scaling.

Uniqueness in the same namespace

A SandboxSet can be managed by only one PoolAutoscaler.

Capacity policy constraints

Field

Constraint

targetAvailable

An absolute value must be >= 0 and <= maxReplicas. If the value exceeds the limit, the target can never be reached. The percentage format is "<number>%", and the value ranges from 0 to 100.

targetAvailable is a percentage

You must also set minReplicas >= 1. Otherwise, all watermarks are 0 when the pool is empty, and the warm pool cannot bootstrap.

tolerance

The format constraints are the same as those of targetAvailable. The value must be less than targetAvailable, which can be statically determined if both values are percentages or both values are absolute values. Otherwise, the lower watermark is limited to 0 and scale-up never occurs. If an absolute target is used with a percentage tolerance, the percentage of the tolerance must be less than 100%.

scaleUp.stabilizationWindowSeconds

If this parameter is not configured, the default value is 60 seconds. If you explicitly configure this parameter, the value must be within the range of 60 to 3600 seconds.

scaleDown.stabilizationWindowSeconds

If this parameter is not configured, the default value is 300 seconds. If you explicitly configure this parameter, the value must be within the range of 60 to 3600 seconds. Set a longer scale-down stabilization window than the scale-up stabilization window. A quick scale-up replenishes the warm pool in a timely manner to ensure a low claim latency. A slow scale-down prevents the warm pool from being frequently reclaimed when traffic drops and helps maintain stable capacity for the cluster.

Scale-down reachability is not a hard validation in the current version. However, invalid configurations may prevent the warm pool from scaling in to minReplicas. Check the value based on the rules described in the Ensure that an idle warm pool can scale in to minReplicas section of this topic.

cronPolicies validation rules are as follows: a maximum of 20 policies can be configured, the name must be unique, the schedule must be a valid five-field cron expression, the time zone must be valid, and targetReplicas >= 0. For more information, see the CRD field reference section in this topic. The rules are not described again in this section.

CRD field reference

PoolAutoscaler is a Custom Resource Definition (CRD) provided by Agent Sandbox. This section describes the meaning and constraints of each field.

Field

Description

spec.scaleTargetRef

The reference to the SandboxSet to be managed. The value of the kind field must be SandboxSet. The SandboxSet and the PoolAutoscaler must be in the same namespace.

spec.minReplicas / spec.maxReplicas

The lower and upper limits of the number of replicas in the warm pool. The value of maxReplicas must be greater than 0, and the value of minReplicas cannot be greater than maxReplicas. The capacity policy must be able to scale an idle warm pool in to minReplicas. For more information about the value constraints, see the Capacity policy tuning.

spec.capacityPolicy.targetAvailable

The number of available sandboxes to maintain. Set an absolute value or a percentage. Examples: 10, "60%". The percentage is calculated based on the recent average number of replicas. If you use a percentage, you must set minReplicas: 1 or higher. The value must be used with tolerance and minReplicas to meet the scale-down reachability rules. For more information, see the Capacity policy tuning.

spec.capacityPolicy.tolerance

The acceptable deviation from the target. Set an absolute value or a percentage. If this parameter is not configured, the default value is 10%. For example, if the target is 10 and the deviation is 2, the pool scales up when the number falls below 8 and scales down when the number exceeds 12. For more information about the resolution method and the scale-down reachability constraints, see the Capacity policy tuning.

spec.capacityPolicy.scaleUp.stabilizationWindowSeconds

The scale-up stabilization window, which is the minimum interval between two consecutive scale-up operations. Valid values if explicitly configured: 60 to 3600 seconds. Default value: 60 seconds.

spec.capacityPolicy.scaleDown.stabilizationWindowSeconds

The scale-down stabilization window, which is the minimum interval between two consecutive scale-down operations. Valid values if explicitly configured: 60 to 3600 seconds. Default value: 300 seconds. Set a longer window than the scale-up stabilization window to prevent capacity jitter caused by quick scale-down.

spec.cronPolicies

The list of cron policies. A maximum of 20 policies are supported. The webhook validates the following rules: name is required and must be unique in the same list. schedule is required and must be a valid five-field cron expression (minute hour day-of-month month day-of-week). timeZone is optional. If you configure this parameter, the value must be a valid time zone (such as Asia/Shanghai); targetReplicas must be greater than or equal to 0. If the value exceeds maxReplicas, the value is limited to maxReplicas.

spec.suspend

If you set this parameter to true, subsequent auto scaling is paused, and existing sandboxes are not deleted. To resume the auto scaling, set this parameter to false or remove the field.

status.currentReplicas

The most recently observed number of replicas of the specified SandboxSet.

status.desiredReplicas

The most recently calculated desired number of replicas of the PoolAutoscaler.

status.currentCapacity.available

The most recently observed number of available sandboxes.

status.conditions

ScalingActive indicates whether the controller is available. AbleToScale indicates whether the target can be calculated and written. ScalingLimited indicates whether the number of replicas is limited by the upper or lower limit.

status.appliedCronPolicies

The time when each cron policy last ran successfully.