FC Cloud Sandbox Best Practices for Large File Uploads: OSS Relay and Chunked Direct Upload

Updated at:

Cloud Sandbox limits the body of a single upload request to 32 MiB. Large files can be sent into the Sandbox through OSS relay or chunked direct upload.

Cloud Sandbox file upload APIs go through the Function Compute HTTP gateway. The maximum size of a single request body is 32 MiB (mebibytes, binary megabytes), or 33,554,432 bytes. When a file approaches or exceeds this limit, a direct call to sandbox.files.write() or an upload to the address returned by sandbox.upload_url() may be rejected by the gateway.

When the limit is exceeded, the API returns HTTP 400 with the following error response body:

{
    "RequestId": "<REQUEST-ID>",
    "Code": "EntityTooLarge",
    "Message": "payload size exceeds maximum allowed size (33554432 bytes)"
}

The Python SDK (Software Development Kit) e2b==2.31.0 converts this response into InvalidArgumentException, and the Code in the exception message remains EntityTooLarge.

This topic describes how to send large files into the Sandbox by using two methods, OSS (Object Storage Service) relay and chunked direct upload, and provides the selection criteria, end-to-end examples, and a production environment checklist.

Scope

The examples in this topic apply when you need to bypass the 32 MiB limit on a single request body to transfer large files to the Sandbox. Both solutions share the same basic environment preparation. Before you start, confirm the following items:

  • You have prepared a runtime environment with Python 3.10 or later and installed the E2B SDK. The examples in this topic all use e2b==2.31.0. For other version constraints, see Usage constraints.

  • You have obtained an API key and confirmed the endpoint value of the region where the Sandbox is located. For instructions, see E2B SDK connection parameters.

Install the SDK and configure the environment variables:

pip install e2b==2.31.0

export E2B_API_KEY="<YOUR-API-KEY>"
export E2B_API_URL="https://api.<REGION>.e2b.fc.aliyuncs.com"
export E2B_DOMAIN="<REGION>.e2b.fc.aliyuncs.com"
export LOCAL_FILE="<YOUR-LOCAL-FILE-PATH>"

E2B_API_URL contains the api. prefix, while E2B_DOMAIN does not. In both, the <REGION> must match the region where the Sandbox is located. LOCAL_FILE is the path of the local file to be uploaded. The examples in both Solution 1 and Solution 2 read the file from this variable.

Solution selection

The following table compares the two solutions in terms of data path, additional dependencies, recommended scale, and other aspects:

Dimension

OSS relay

Chunked direct upload

Data path

Client → OSS → Sandbox

Client → Sandbox

Additional dependencies

OSS bucket and OSS SDK

E2B SDK only

Recommended scale

Production environments and files ranging from hundreds of MiB to TiB

Occasional medium-sized files, preferably no larger than 500 MiB

Concurrency and resumable transfer

Natively supported by the OSS SDK

Must be implemented on the business side

Sharing across multiple Sandboxes

Supported. Multiple signed URLs can be generated for the same OSS object.

Not suitable

Sandbox disk usage

About the size of one file during the download

About twice the file size during merging

Large file download

Supported. The Sandbox can upload the results to OSS.

Requires reverse chunking. Use OSS instead.

You can select a solution based on the following rules:

  • If the file is smaller than 25 MiB: use the Filesystem API directly and call sandbox.files.write() to upload the file in a single request.

  • If the file is 25 to 500 MiB and you want to reduce external dependencies: upload it in 25 MiB chunks and merge the chunks inside the Sandbox.

  • If the file is larger than 500 MiB, or you need resumable transfer, concurrent transfer, sharing across Sandboxes, or long-term retention: use OSS relay.

  • If a large file generated by the Sandbox needs to be downloaded to the client: upload it to OSS first and then return an OSS signed URL to the client.

The 25 MiB value is a conservative figure that leaves room for HTTP request headers and multipart encoding, and 500 MiB is a recommended value for initial solution selection. Neither is a product limit. Adjust the actual thresholds based on the client upstream bandwidth, the cost of failure retries, the Sandbox disk capacity, and the task time limit. For the measured durations of both solutions under the same environment, see Performance notes.

Chunked direct upload keeps both the chunks and the target file during merging, so the disk usage is about twice the file size. Before you go live, confirm that the available disk space of the Sandbox you use can accommodate this usage.

Solution 1: Relay through OSS

OSS relay splits the transfer into two legs: the client uploads the file in parts by using the OSS SDK, and the Sandbox then downloads it through the internal OSS endpoint of the same region. After processing is complete, the Sandbox can also write the results back to OSS through a presigned PUT URL.

Client ──multipart upload──> OSS ──internal download──> Sandbox
Client <──signed download URL── OSS <──result upload── Sandbox

This solution delegates retries, concurrency, and resumable transfer to OSS, which makes it suitable for production environments and very large files. The bucket should be in the same region as the Sandbox and should keep private read and write permissions.

Important

This example creates a Sandbox instance and writes OSS objects. The sandbox is billed based on the Sandbox specifications, running state, and actual usage duration. External cloud resources such as OSS and Internet traffic are billed separately by the corresponding cloud services. For the billing rules, see Pay-as-you-go. The example cleans up only the temporary files inside the Sandbox. You must delete the transfer objects in OSS according to lifecycle rules; otherwise, storage fees continue to accrue.

Prepare OSS

The following environment variables use the Hangzhou region as an example, where OSS_SECURITY_TOKEN needs to be set only when you use STS (Security Token Service) temporary credentials:

pip install e2b==2.31.0 oss2

export OSS_ACCESS_KEY_ID="<YOUR-ACCESS-KEY-ID>"
export OSS_ACCESS_KEY_SECRET="<YOUR-ACCESS-KEY-SECRET>"
# Set this variable only when you use STS temporary credentials
export OSS_SECURITY_TOKEN="<YOUR-SECURITY-TOKEN>"

export OSS_BUCKET="<YOUR-PRIVATE-BUCKET>"
export OSS_PUBLIC_ENDPOINT="https://oss-cn-hangzhou.aliyuncs.com"
export OSS_INTERNAL_ENDPOINT="https://oss-cn-hangzhou-internal.aliyuncs.com"
export TRANSFER_ID="<STABLE-UNIQUE-TRANSFER-ID>"

This installation command matches the SDK version in Scope. You can copy and run the command independently. oss2 is a new dependency introduced by this solution. In production environments, use STS temporary credentials issued by a RAM (Resource Access Management) role, and grant least privilege by object prefix. The AccessKey ID (AK), AccessKey secret (SK), and Security Token Service token are used only by trusted business services to generate signed URLs. Do not pass them into the Sandbox.

Upload, process, and return the results

The following example performs four steps: upload the local file to OSS in parts, generate an internal signed URL, download the file inside the Sandbox and compute its SHA-256 (Secure Hash Algorithm 256-bit) value, and upload the verification result back to OSS.

import hashlib
import os
import shlex
from pathlib import Path

import oss2
from e2b import Sandbox


def require_env(name: str) -> str:
    value = os.environ.get(name, "").strip()
    if not value:
        raise RuntimeError(f"Missing environment variable: {name}")
    return value


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as file:
        for block in iter(lambda: file.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def run_checked(sandbox: Sandbox, command: str, timeout: int = 300):
    result = sandbox.commands.run(command, timeout=timeout)
    if result.exit_code != 0:
        raise RuntimeError(result.stderr or f"Command execution failed: {command}")
    return result


local_file = Path(require_env("LOCAL_FILE")).expanduser()
bucket_name = require_env("OSS_BUCKET")
transfer_id = require_env("TRANSFER_ID")
object_key = f"sandbox-transfer/{transfer_id}/input/{local_file.name}"
result_key = f"sandbox-transfer/{transfer_id}/result/{local_file.name}.sha256"
remote_file = f"/tmp/{local_file.name}"
remote_result = f"{remote_file}.sha256"

access_key_id = require_env("OSS_ACCESS_KEY_ID")
access_key_secret = require_env("OSS_ACCESS_KEY_SECRET")
security_token = os.environ.get("OSS_SECURITY_TOKEN", "").strip()
if security_token:
    auth = oss2.StsAuth(access_key_id, access_key_secret, security_token)
else:
    auth = oss2.Auth(access_key_id, access_key_secret)

public_bucket = oss2.Bucket(
    auth,
    require_env("OSS_PUBLIC_ENDPOINT"),
    bucket_name,
)
internal_bucket = oss2.Bucket(
    auth,
    require_env("OSS_INTERNAL_ENDPOINT"),
    bucket_name,
)

# 1. Client to OSS: Enable multipart and concurrent uploads when the file is larger than 10 MiB.
oss2.resumable_upload(
    public_bucket,
    object_key,
    str(local_file),
    multipart_threshold=10 * 1024 * 1024,
    part_size=10 * 1024 * 1024,
    num_threads=4,
)

# 2. URL uses the internal endpoint so that Sandboxes in the same region can access it.
download_url = internal_bucket.sign_url("GET", object_key, 3600, slash_safe=True)
upload_url = internal_bucket.sign_url("PUT", result_key, 3600, slash_safe=True)

sandbox = Sandbox.create(
    template="code-interpreter-v1",
    api_key=require_env("E2B_API_KEY"),
    api_url=require_env("E2B_API_URL"),
    domain=require_env("E2B_DOMAIN"),
    timeout=600,
)

try:
    # 3. OSS to Sandbox: Download by using a signed URL. OSS credentials do not need to be stored inside the Sandbox.
    run_checked(
        sandbox,
        "curl --fail --location --silent --show-error "
        f"{shlex.quote(download_url)} --output {shlex.quote(remote_file)}",
    )
    run_checked(
        sandbox,
        f"sha256sum {shlex.quote(remote_file)} > {shlex.quote(remote_result)}",
    )

    # Run the actual file processing logic here.

    # 4. Sandbox to OSS: Return the results through a presigned PUT URL.
    run_checked(
        sandbox,
        "curl --fail --silent --show-error --request PUT "
        f"--upload-file {shlex.quote(remote_result)} {shlex.quote(upload_url)}",
    )
finally:
    sandbox.kill()

remote_digest = public_bucket.get_object(result_key).read().decode().split()[0]
local_digest = sha256_file(local_file)
if remote_digest != local_digest:
    raise RuntimeError(f"File verification failed: local={local_digest}, sandbox={remote_digest}")

print(f"Upload and verification complete: oss://{bucket_name}/{object_key}")

Expected output:

Upload and verification complete: oss://<YOUR-PRIVATE-BUCKET>/sandbox-transfer/<STABLE-UNIQUE-TRANSFER-ID>/input/<LOCAL-FILE-NAME>

For each transfer task, the business side should generate a unique and persistent TRANSFER_ID, such as a UUID (Universally Unique Identifier), and reuse the value when the same task is retried. This isolates concurrent tasks on files with the same name and allows retries to continue accessing the original OSS object. Production services should also record the OSS Upload ID or use the resumable transfer information of oss2.resumable_upload(), and add retries with backoff for network errors. The validity period of the signed URL should cover the Sandbox queuing, download, and processing time.

Solution 2: Chunked direct upload

Chunked direct upload splits the local file into multiple chunks of no more than 25 MiB each, calls sandbox.files.write() for each chunk, and finally merges the chunks inside the Sandbox by number. This solution does not depend on OSS, but if any chunk fails, the business side must decide whether to re-upload from the beginning or record progress and resume the transfer. The chunking here is application-layer splitting and is not the same mechanism as OSS multipart upload: multipart upload natively supports concurrency and resumable transfer in the OSS SDK, whereas the progress recording and resumption logic for chunks must be implemented by the business side.

Client ──chunk_000000──> Sandbox
       ──chunk_000001──> Sandbox ──merge by number──> target file
       ──chunk_000002──> Sandbox

The following code uses use_octet_stream=True to reduce the encoding overhead of binary uploads. The SDK determines whether this mode is supported based on the envd version of the Sandbox (envd 0.5.7 or later is required) and automatically falls back to multipart/form-data when it is not supported. Regardless of the encoding used, each chunk remains 25 MiB. The example sets the Sandbox lifetime to timeout=600 and the timeout of a single write request to request_timeout=300. In actual use, estimate these values based on the file size and the client upstream bandwidth: the Sandbox lifetime must cover the time for uploading all chunks, merging, and verification, and the single request timeout must cover the write time of one chunk. When the upstream bandwidth is lower than the measured values in Performance notes, extend both values accordingly.

import hashlib
import os
import shlex
import uuid
from pathlib import Path

from e2b import Sandbox


CHUNK_SIZE = 25 * 1024 * 1024


def require_env(name: str) -> str:
    value = os.environ.get(name, "").strip()
    if not value:
        raise RuntimeError(f"Missing environment variable: {name}")
    return value


def run_checked(sandbox: Sandbox, command: str, timeout: int = 300):
    result = sandbox.commands.run(command, timeout=timeout)
    if result.exit_code != 0:
        raise RuntimeError(result.stderr or f"Command execution failed: {command}")
    return result


local_file = Path(require_env("LOCAL_FILE")).expanduser()
remote_file = f"/tmp/{local_file.name}"
remote_dir = f"/tmp/upload-{uuid.uuid4().hex}"

sandbox = Sandbox.create(
    template="code-interpreter-v1",
    api_key=require_env("E2B_API_KEY"),
    api_url=require_env("E2B_API_URL"),
    domain=require_env("E2B_DOMAIN"),
    timeout=600,
)

digest = hashlib.sha256()
chunk_count = 0

try:
    with local_file.open("rb") as file:
        while chunk := file.read(CHUNK_SIZE):
            digest.update(chunk)
            chunk_path = f"{remote_dir}/chunk_{chunk_count:06d}"
            sandbox.files.write(
                chunk_path,
                chunk,
                use_octet_stream=True,
                request_timeout=300,
            )
            chunk_count += 1

    if chunk_count == 0:
        sandbox.files.write(remote_file, b"")
    else:
        run_checked(
            sandbox,
            f"cat {shlex.quote(remote_dir)}/chunk_* > {shlex.quote(remote_file)}",
        )

    result = run_checked(
        sandbox,
        f"sha256sum {shlex.quote(remote_file)} | cut -d' ' -f1",
    )
    sandbox_digest = result.stdout.strip()
    local_digest = digest.hexdigest()
    if sandbox_digest != local_digest:
        raise RuntimeError(
            f"File verification failed: local={local_digest}, sandbox={sandbox_digest}"
        )

    # Delete the chunks only after verification succeeds. You can continue processing remote_file here.
    run_checked(sandbox, f"rm -rf -- {shlex.quote(remote_dir)}")
    print(f"Upload complete: {remote_file}, chunks={chunk_count}, sha256={local_digest}")
finally:
    sandbox.kill()

Expected output:

Upload complete: /tmp/<LOCAL-FILE-NAME>, chunks=<CHUNK-COUNT>, sha256=<SHA-256-DIGEST>

The temporary directory in the example uses a random name to prevent concurrent tasks from overwriting each other. The chunk names use fixed-width numbers so that the order remains correct when the shell expands them in lexicographic order. This basic example terminates the Sandbox through the finally clause, so all chunks must be re-uploaded if any chunk fails. To support resumable transfer, the business side must keep the Sandbox within a controlled recovery window, persist the Sandbox ID, chunk numbers, chunk sizes, and file digest, and use sandbox.files.exists() after reconnection to check which chunks have been uploaded. Terminate the Sandbox only after the upload succeeds or the task is explicitly abandoned.

Handle large file downloads

Large files are not suitable for returning through a single sandbox.files.read() call or a single download request: the client must receive the complete response at once, and a failure usually requires retrying from the beginning. (Recommended) Return the results through OSS:

  1. A trusted business service generates a short-lived PUT signed URL for the target OSS object.

  2. The Sandbox uses curl --upload-file to upload the results to OSS.

  3. The business service verifies the object size and digest, and then issues a GET URL to the client.

If you cannot use OSS, you can first use split inside the Sandbox to split the results into chunks of no more than 25 MiB, and then use sandbox.files.read(..., format="bytes") to read the chunks one by one and merge them on the client. This download approach of splitting first and then reading chunk by chunk also requires recording the chunk order and verifying the digest of the complete file, and it does not provide the native concurrency and resumable transfer capabilities of OSS.

Production environment checklist

Before you go live, review the following checklist:

  • Capacity: The chunks and the target file coexist during merging, so reserve disk space of about twice the file size.

  • Integrity: Compare the SHA-256 values before and after the upload. Do not treat the existence of the file as a success indicator.

  • Security: Keep the bucket private, use STS credentials with least privilege and short-lived signed URLs, and do not log complete URLs.

  • Paths: Generate the paths inside the Sandbox on the business side. Do not directly concatenate unvalidated user input.

  • Retries: Use multipart upload and resumable transfer on the OSS side, record the chunks that have succeeded on the chunked direct upload side, and use exponential backoff.

  • Cleanup: Delete the temporary chunks after verification succeeds, call sandbox.kill() after the task ends, and clean up the temporary OSS objects according to lifecycle rules.

  • Timeouts: Make sure that the timeouts for signed URLs, SDK requests, the Sandbox lifetime, and command execution cover the slowest link.

  • Observability: Log the file size, number of chunks, duration, number of retries, and digest. Do not log credentials or complete signed URLs.

Performance notes

In a reference test on July 9, 2026, a 100 MiB file was uploaded in the Hangzhou region, with the following results:

Solution

Client upload

OSS to Sandbox

End-to-end duration

OSS relay

About 10.27 MiB/s

About 99.87 MiB/s

About 14 seconds

Chunked direct upload with 4 × 25 MiB

About 10.87 MiB/s

Not applicable

About 13 seconds

In addition to the transfer itself, the end-to-end duration also includes stages such as Sandbox creation, download or merge, SHA-256 verification, and the result return in Solution 1. It is therefore longer than the transfer time calculated from the individual rates. The test results only show the order of magnitude of the two solutions in this environment and do not constitute a performance commitment. The actual speed depends on the client upstream bandwidth, region, OSS configuration, file size, and concurrency parameters. For production solution selection, run the stress test again with real files and the target network.

References