Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sandbox Pool

A SandboxPool manages a bounded set of warm sandbox instances for high-throughput concurrent execution. Instead of creating a new sandbox per request, you lease one from the pool, execute code, and return it automatically.

Use a pool when you serve concurrent requests and want to bound resource usage while avoiding per-request sandbox creation cost.

Creating a Pool

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), eryx::PoolError> {
    let config = PoolConfig::default()
        .with_max_size(4)
        .with_min_idle(1)
        .with_acquire_timeout(Duration::from_secs(5))
        .with_idle_timeout(Duration::from_secs(300));

    let pool = SandboxPool::new(Sandbox::embedded(), config).await?;

    // Or with a custom builder for more control:
    let pool = SandboxPool::with_builder(
        || Sandbox::embedded().with_trace_collection(true).build(),
        PoolConfig::default(),
    ).await?;

    Ok(())
}
import eryx

factory = eryx.SandboxFactory(cache=True)
pool = factory.create_pool(
    max_size=4,          # at most 4 concurrent sandboxes
    min_idle=1,          # keep 1 warm sandbox ready
    acquire_timeout_ms=5000,   # wait up to 5s for a sandbox
    idle_timeout_ms=300_000,   # evict idle sandboxes after 5min
)

In Python, the pool reuses the factory’s precompiled artifact and shared Tokio runtime. When the pool needs a new sandbox (because the idle queue is empty), creation is fast since the precompiled artifact avoids re-deserializing the WASM component.

Acquiring and Releasing Leases

Acquire a sandbox, use it, and return it to the pool. The sandbox is returned automatically when the scope ends:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
// Acquire a sandbox from the pool
let sandbox = pool.acquire().await?;

let result = sandbox.execute("print('Hello from pool!')").await?;
println!("{}", result.stdout_text());

// Sandbox is returned to the pool when dropped
drop(sandbox);
    Ok(())
}
import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(max_size=1)

with pool.acquire() as sandbox:
    result = sandbox.execute('print("Hello from pool!")')
    print(result.stdout_text)
# sandbox is returned to the pool here

In Python, use-after-release raises ValueError, and repeated release is safe (idempotent):

with pool.acquire() as sandbox:
    sandbox.execute('pass')

sandbox.execute('pass')  # raises ValueError: sandbox has been released

# Explicit release is also available:
sandbox = pool.acquire()
sandbox.execute('print(42)')
sandbox.release()   # returned to pool
sandbox.release()   # no-op

Per-Request Configuration

Each acquisition accepts per-request callbacks, output handlers, and resource limits. These are cleared automatically on release so the next borrower gets a clean sandbox:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};
use eryx::ResourceLimits;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
let limits = ResourceLimits::default()
    .with_execution_timeout(Duration::from_secs(2));
let sandbox = pool.acquire().await?
    .with_resource_limits(limits);

let result = sandbox.execute("print('with limits')").await?;
// Limits are cleared when sandbox is returned to pool
    Ok(())
}
import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(max_size=1)

def handle_output(chunk: bytes):
    print(f"[stdout] {chunk.decode()}", end="")

with pool.acquire(
    resource_limits=eryx.ResourceLimits(execution_timeout_ms=2000),
    on_stdout=handle_output,
    callbacks=[{"name": "greet", "fn": lambda: {"msg": "hi"}, "description": "greet"}],
) as sandbox:
    result = sandbox.execute('import json; print(json.dumps(await greet()))')

If you don’t pass callbacks in Python, the factory’s default callbacks (baked into the snapshot) are used.

Network and Secrets

In Rust, a lease can have its own network configuration and secrets, which replace the pool’s (by default, no network) until it’s returned:

use std::collections::HashMap;
use eryx::{NetConfig, SecretConfig};

let secret = SecretConfig::new("sk-xxx", vec!["api.example.com".to_string()]);
let sandbox = pool.acquire().await?.with_network(
    NetConfig::default().allow_host("api.example.com"),
    HashMap::from([("API_KEY".to_string(), secret)]),
)?;

with_network checks them as build does. Create new SecretConfigs for each lease, so each gets its own placeholder.

A shell pool’s commands can reach the network through each lease’s network too (with_child_network, see External commands). SandboxPool::new sets this up. Sandboxes built in a SandboxPool::with_builder closure need with_network_per_lease() alongside with_child_network, or build fails asking for with_network:

use eryx::{ChildNetwork, PoolConfig, Sandbox, SandboxPool};

let pool = SandboxPool::with_builder(
    move || {
        Sandbox::embedded()
            .shell()
            .with_command("curl", curl.clone())
            .with_child_network(ChildNetwork::Inherit)
            .with_network_per_lease()
            .build()
    },
    PoolConfig::default(),
)
.await?;

A lease without a network fails closed: its children get no proxy and no network, whatever the child network and the commands’ networks say, and the execution still runs.

For networking and secrets that every pooled sandbox gets, for the pool’s lifetime, configure them in the closure passed to SandboxPool::with_builder. In Python, that’s the only way: pass them to create_pool:

import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(
    max_size=4,
    network=eryx.NetConfig(allowed_hosts=["api.example.com"]),
    secrets={"API_KEY": {"value": "sk-xxx", "allowed_hosts": ["api.example.com"]}},
)

As with Sandbox, scrub_stdout, scrub_stderr and scrub_files default to True when secrets are given and can be overridden on create_pool.

Non-Blocking Acquire

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
if let Some(sandbox) = pool.try_acquire()? {
    let result = sandbox.execute("print('got one')").await?;
} else {
    println!("pool is busy");
}
    Ok(())
}
import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(max_size=1)

sandbox = pool.try_acquire()
if sandbox is not None:
    with sandbox:
        sandbox.execute('print("got one")')
else:
    print("pool is busy")

Pool Stats and Eviction

Monitor pool usage and evict idle sandboxes that have exceeded the idle timeout (respects min_idle):

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
let stats = pool.stats();
println!("idle={}, in_use={}, total={}", stats.idle, stats.in_use, stats.total);

let evicted = pool.evict_idle();
println!("evicted {} idle sandboxes", evicted);
    Ok(())
}
import eryx

pool = eryx.SandboxFactory(cache=True).create_pool(max_size=1)

stats = pool.stats()
print(f"idle={stats.idle}, in_use={stats.in_use}, total={stats.total}")
print(f"acquisitions={stats.total_acquisitions}, avg_wait={stats.average_wait_time_ms:.1f}ms")

evicted = pool.evict_idle()

Closing the Pool

close() prevents new acquisitions, wakes any threads blocked on acquire(), and drops idle sandboxes. Existing leases continue to work but are not returned on release:

extern crate eryx;
extern crate tokio;
use eryx::{Sandbox, SandboxPool, PoolConfig, PoolError};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let pool = SandboxPool::new(Sandbox::embedded(), PoolConfig::default()).await?;
pool.close();
assert!(pool.is_closed());

match pool.acquire().await {
    Err(PoolError::Closed) => println!("pool is closed"),
    _ => unreachable!(),
}
    Ok(())
}
import eryx

factory = eryx.SandboxFactory(cache=True)
pool = factory.create_pool(max_size=1)

pool.close()
try:
    pool.acquire()
except eryx.PoolClosedError:
    print("pool is closed")

# The pool is also a context manager:
with factory.create_pool(max_size=4) as pool:
    with pool.acquire() as sandbox:
        sandbox.execute('print("ok")')
# pool.close() called automatically

Thread Safety

The pool is safe to use from multiple threads. In Python, the GIL is released while waiting for a sandbox and during guest code execution, so other threads can make progress — including returning their own leases to unblock waiting acquirers.

import threading

def worker(pool, idx):
    with pool.acquire() as sandbox:
        result = sandbox.execute(f'print("worker {idx}")')

threads = [threading.Thread(target=worker, args=(pool, i)) for i in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()

Pool Exceptions

ExceptionWhen
PoolTimeoutErroracquire() timed out waiting for a sandbox
PoolClosedErrorPool has been closed

All inherit from PoolError (Rust: eryx::PoolError, Python: eryx.PoolError).

Next Steps