Template pre-warming

Updated at:

Template pre-warming (Template Cache) prepares the image data of a built template in advance. This reduces the cold start time caused by image pulls when a sandbox is created for the first time.

Overview

The pre-warming policies and billing rules for each template type are as follows:

  • Official templates: automatically pre-warmed by the platform. No manual intervention is required, and no pre-warming fees are charged.

  • Custom templates: must be pre-warmed by calling API operations, and you are charged based on the actual storage volume of the pre-warmed data. Pre-warm custom templates as needed before they are published or before sandboxes are created in batches.

Prerequisites

RAM permissions

Before you call the template pre-warming API operations as a Resource Access Management (RAM) user or with an STS temporary credential, grant the required permissions to the calling identity. Skip this section if you call the operations with an Alibaba Cloud account.

Least-privilege policy example:

{
  "Version": "1",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "sandbox:CreateTemplateCache",
        "sandbox:DescribeTemplateCache",
        "sandbox:ListTemplateCache",
        "sandbox:DeleteTemplateCache"
      ],
      "Resource": "*"
    }
  ]
}

Grant permissions on a specific Team. Resource format:

  • CreateTemplateCache and ListTemplateCache are authorized on a Team-level collection: acs:sandbox:<region>:<account-id>:teams/<team-id>/template-caches/*.

  • DescribeTemplateCache and DeleteTemplateCache can be scoped to the pre-warming task of a single template: acs:sandbox:<region>:<account-id>:teams/<team-id>/template-caches/<template-id>.

Note
  • ListTemplateCache is authorized on a Team-level collection. An identity that is granted only the Alibaba Cloud Resource Name (ARN) of a single pre-warming task (.../template-caches/<template-id>) can query and delete that task. Calls to ListTemplateCache are still denied.

  • This topic also involves template permissions: sandbox:GetTemplate is required to check the build status of a template (GetTemplate), and sandbox:DeleteTemplate is also required to delete a template (DeleteTemplate).

  • If the calling identity lacks a required permission, the API returns HTTP 403 with the NoPermission error code and the error message You are not authorized to perform this action. Check the RAM policy and the resource ownership.

Procedure

Step 1: Install the SDK and configure credentials

Install the Python software development kit (SDK):

python3 -m venv .venv
source .venv/bin/activate
python -m pip install "alibabacloud-sandbox20260820==1.2.0"

Set the access credentials and the region:

export ALIBABA_CLOUD_ACCESS_KEY_ID="<YOUR-ACCESS-KEY-ID>"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="<YOUR-ACCESS-KEY-SECRET>"
# If you use STS temporary credentials, also set the following variable:
# export ALIBABA_CLOUD_SECURITY_TOKEN="<YOUR-SECURITY-TOKEN>"
export SANDBOX_REGION_ID="cn-hangzhou"
export SANDBOX_ENDPOINT="sandbox.cn-hangzhou.aliyuncs.com"
A long-term AccessKey does not require ALIBABA_CLOUD_SECURITY_TOKEN. You must set it when you use STS temporary credentials.

The following examples are based on OpenAPI version 2026-08-20.

Step 2: Create a pre-warming task and poll until the task is ready

Call CreateTemplateCache to submit the pre-warming task, and then poll DescribeTemplateCache until status changes to ready. A successful request indicates that the platform has accepted the task, and the pre-warming runs asynchronously in the background. Acceptance does not indicate that the pre-warming is complete. The example queries the task immediately, then polls every 15 seconds for at most 20 minutes. If the wait times out, the script exits and reports the timeout. Continue to query the task status instead of creating the task again. If 409 TemplateCacheAlreadyExists is returned when you run the script again, the script queries the existing task. If the template has not finished building, CreateTemplateCache returns 409 TemplateNotReady, and no pre-warming task is created.

Save the following code as prewarm_template.py, replace the Team ID and the template ID, and then run python prewarm_template.py warm. The region is specified by SANDBOX_REGION_ID and SANDBOX_ENDPOINT, and must be the region where the template resides.

import logging
import os
import sys
import time

from alibabacloud_sandbox20260820 import models as sandbox_models
from alibabacloud_sandbox20260820.client import Client as SandboxClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_openapi.exceptions import ClientException

TEAM_ID = "<YOUR-TEAM-ID>"
TEMPLATE_ID = "<YOUR-TEMPLATE-ID>"
POLL_INTERVAL_SECONDS = 15
WARM_TIMEOUT_SECONDS = 20 * 60
DELETE_TIMEOUT_SECONDS = 5 * 60


def build_client() -> SandboxClient:
    """Build a client from the credentials, region, and endpoint in environment variables."""
    config = open_api_models.Config(
        access_key_id=os.environ["ALIBABA_CLOUD_ACCESS_KEY_ID"],
        access_key_secret=os.environ["ALIBABA_CLOUD_ACCESS_KEY_SECRET"],
        security_token=os.environ.get("ALIBABA_CLOUD_SECURITY_TOKEN") or None,
        region_id=os.environ["SANDBOX_REGION_ID"],
        endpoint=os.environ["SANDBOX_ENDPOINT"],
    )
    return SandboxClient(config)


def describe_template_cache(client: SandboxClient):
    """Query a single pre-warming task and return (template_cache, request_id)."""
    resp = client.describe_template_cache(
        TEMPLATE_ID,
        sandbox_models.DescribeTemplateCacheRequest(team_id=TEAM_ID),
    )
    return resp.body.template_cache, resp.body.request_id


def warm(client: SandboxClient) -> None:
    """Submit the pre-warming task and poll until it is ready."""
    try:
        resp = client.create_template_cache(sandbox_models.CreateTemplateCacheRequest(
            body=sandbox_models.CreateTemplateCacheInput(team_id=TEAM_ID, template_id=TEMPLATE_ID),
        ))
        logging.info("Pre-warming task created: status=%s requestId=%s", resp.body.template_cache.status, resp.body.request_id)
    except ClientException as exc:
        # 409 means the pre-warming task already exists (including failed and evicted remnants).
        # Query the existing task instead of creating another one.
        if exc.status_code != 409:
            raise
        logging.info("Pre-warming task already exists (%s); querying the existing task", exc.code)

    deadline = time.monotonic() + WARM_TIMEOUT_SECONDS
    while time.monotonic() < deadline:
        cache, request_id = describe_template_cache(client)
        logging.info("status=%s requestId=%s", cache.status, request_id)
        if cache.status == "ready":
            logging.info("The template is pre-warmed. You can create a sandbox.")
            return
        if cache.status in ("failed", "evicted"):
            raise RuntimeError(f"Pre-warming did not succeed: status={cache.status} statusReason={cache.status_reason}")
        time.sleep(POLL_INTERVAL_SECONDS)
    raise TimeoutError("Timed out waiting for pre-warming. Continue to call DescribeTemplateCache instead of creating the task again.")


def delete(client: SandboxClient) -> None:
    """Delete the pre-warming task and poll until 404 is returned."""
    try:
        resp = client.delete_template_cache(
            TEMPLATE_ID,
            sandbox_models.DeleteTemplateCacheRequest(team_id=TEAM_ID),
        )
        logging.info("Delete request accepted: requestId=%s", resp.body.request_id)
    except ClientException as exc:
        # 404 means the pre-warming task no longer exists (repeated deletion). Treat it as deleted.
        if exc.status_code != 404:
            raise
        logging.info("The pre-warming task does not exist. Nothing to delete.")
        return

    deadline = time.monotonic() + DELETE_TIMEOUT_SECONDS
    while time.monotonic() < deadline:
        try:
            cache, request_id = describe_template_cache(client)
            logging.info("Deleting: status=%s requestId=%s", cache.status, request_id)
        except ClientException as exc:
            if exc.status_code == 404:
                logging.info("The pre-warming task is deleted.")
                return
            raise
        time.sleep(POLL_INTERVAL_SECONDS)
    raise TimeoutError("Timed out waiting for the deletion. Continue to call DescribeTemplateCache.")


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    action = sys.argv[1] if len(sys.argv) > 1 else "warm"
    sandbox_client = build_client()
    if action == "warm":
        warm(sandbox_client)
    elif action == "delete":
        delete(sandbox_client)
    else:
        raise SystemExit(f"Unknown action: {action}. Valid values: warm / delete")

The pre-warming is complete only when status is ready. Create the sandbox after ready is returned.

Step 3: Create a sandbox from a pre-warmed template

Wait until status is ready before you use the template to create a sandbox, so that the pre-warming speedup takes effect. If a sandbox is created before the pre-warming is complete, the speedup is usually unavailable. If the accelerated image data is still being prepared, sandbox creation may fail. Try again after the data is ready. For more information, see Create a Sandbox.

More operations

Query the pre-warming status

Call DescribeTemplateCache with the template ID and the Team ID, and determine the task status from the returned status:

  • creating: The task is accepted and may be queuing, waiting for capacity, waiting for a concurrency slot, or being pre-warmed. Continue to query the task instead of creating it again.

  • ready: The pre-warming is complete. Use the template to create a sandbox.

  • failed: Pre-warming failed. Check statusReason to identify the cause, and then delete the task and create it again.

  • evicted: The platform has reclaimed the pre-warmed data, so the task no longer provides the pre-warming speedup. Delete the task, wait until a query returns 404, and then create it again.

Query pre-warming tasks with pagination

Call ListTemplateCache to paginate through the pre-warming tasks of the current Team. Filter the results by templateID and status. maxResults defaults to 20. Valid values range from 1 to 100. If the value is out of the range, the boundary value is used and no error is returned. Base the end of pagination on whether nextToken is empty, not on the number of entries on the current page.

Delete a pre-warming task

When pre-warming is no longer needed, call DeleteTemplateCache to delete the pre-warming task. The prewarm_template.py script already includes this process.

python prewarm_template.py delete

The command keeps querying after the delete request is submitted, until 404 TemplateCacheNotFound is returned. The logical deletion of the pre-warming task is complete only after this error is returned. A successful response only indicates that the delete request is accepted, and the platform asynchronously and safely cleans up the underlying image data after all references to it are released. A repeated delete request returns 404, and the script reports that the task does not exist and then exits.

To pre-warm a task again after its status becomes failed or evicted, delete the task first and then call CreateTemplateCache.

For more information about the request parameters, authorization information, and response fields of each operation, see Alibaba Cloud SDK and API guide.

Limits

  • Pre-warming is isolated by region. A pre-warming task created in one region is not automatically synchronized to other regions.

  • Template Cache applies only to custom templates built from your own images, such as images in Container Registry (ACR) repositories. Those templates must have finished building. Built-in templates of the platform and second-generation templates that are built from official public images are already pre-warmed by the platform.

  • By default, each account has a 10 GiB pre-warming capacity quota in each region. The usage is calculated by summing the image data size (imageSizeMB, in MiB) of the pre-warming tasks in the region.

    To increase the capacity quota, submit a ticket.
  • If the used capacity plus the requested capacity exceeds the quota of the current region, the task is still accepted and remains in the creating state until capacity becomes available. The create request returns 429 TemplateCacheLimitExceeded only when too many new tasks are queued. This check is aggregated at the account level, rather than triggered only when a single task exceeds the quota.

  • If a single task is within the quota but the remaining capacity is temporarily insufficient, the task may stay in the creating state. The platform evicts eligible older tasks and then continues to process the task.

  • A pre-warming task is retained for at least 30 minutes after it is created, and can become a candidate for capacity reclamation only after this period. The platform reclaims tasks based on capacity usage and the least recently used (LRU) policy. An evicted task retains its metadata, and its status is reported as evicted.

  • Within the same Team, a template can have only one visible pre-warming task. A repeated create request does not overwrite the existing task, but returns 409 TemplateCacheAlreadyExists. The object of an evicted task still exists, and pre-warming the template again without deleting the task first returns the same error.

  • Delete the corresponding pre-warming task before you delete the template, and wait until DescribeTemplateCache returns 404. If an active pre-warming task exists, deleting the template may return 409 TemplateHasActiveCache.

    Warning

    After a template is deleted, it cannot be used to create new sandbox instances. To use the template again, rebuild it. Before you delete the template, make sure that your workloads no longer depend on it.

  • Creation, deletion, and status changes are eventually consistent. If an SDK call times out or returns 500, call DescribeTemplateCache first to confirm the result, and then decide whether to retry. This prevents duplicate operations.

Troubleshooting

Error code

Meaning and recommended action

TemplateNotReady

The template has not finished building. Wait until GetTemplate returns ready, and then retry.

TemplateCacheAlreadyExists

The pre-warming task already exists. Query the existing task instead. If the status is evicted or failed, delete the task and then create it again.

TemplateCacheLimitExceeded

Too many new tasks are queued. The error message indicates Too many images are waiting to be prewarmed. Delete the pre-warming tasks that are no longer used (including evicted tasks) or submit a ticket to increase the quota, and then retry with exponential backoff and random jitter.

TemplateCacheDeleting

The pre-warming task is being deleted. Wait until a query returns 404, and then create the task again.

TemplateCacheNotFound

The pre-warming task does not exist, or the deletion is complete.

InvalidParameter

The request parameters are invalid: teamID is missing, the template is a built-in template of the platform, or the template is a second-generation template that uses an official public image. Such templates are pre-warmed by the platform and do not support manual pre-warming.

TemplateNotFound

The template ID does not exist, or the template does not belong to the Team. An invalid teamID also returns this error code.

TemplateHasActiveCache

A pre-warming task still exists when you delete the template. Delete the pre-warming task before you delete the template.

NoPermission

The request is denied by RAM authentication. The calling identity does not have the required API permission. Check the RAM policy and the resource ownership. If the Team or template ownership is invalid, the platform returns 404 TemplateNotFound.

InternalError

An internal error occurred on the platform. Query the task first to confirm whether the creation or deletion has taken effect, and then decide whether to retry.

If a task remains in the creating state for an extended period, continue to query the task instead of submitting the task again. If the task still does not complete, submit a ticket. Handle errors in your business logic based on stable error codes, and do not match error messages.

When you submit a ticket, retain the requestId in each response, and provide the region, Team ID, template ID, API operation name, request time, and the error code or statusReason.

References