Skip to Content
Lifecycle

Last Updated: 3/7/2026


Sandbox Lifecycle

Understand how E2B sandboxes are created, managed, and destroyed.

Overview

A sandbox is a fast, secure Linux VM that provides an isolated environment for code execution. Each sandbox has a complete lifecycle from creation to termination.

Creating a Sandbox

Basic Creation

import { Sandbox } from 'e2b' const sandbox = await Sandbox.create() console.log('Sandbox ID:', sandbox.id)

With Options

const sandbox = await Sandbox.create({ apiKey: 'your-api-key', // Optional if E2B_API_KEY is set template: 'custom-template-id', // Use custom template metadata: { // Custom metadata project: 'my-project', user: 'user-123' }, timeoutMs: 300000 // 5 minutes })

Using Templates

// Use a pre-built template const sandbox = await Sandbox.create({ template: 'python-data-science' // Template with pandas, numpy, etc. })

Sandbox States

A sandbox progresses through several states:

  1. Creating - Sandbox is being provisioned
  2. Running - Sandbox is active and ready
  3. Stopped - Sandbox has been paused
  4. Closed - Sandbox has been terminated

Managing Sandboxes

Check Sandbox Status

const status = await sandbox.getStatus() console.log('Status:', status)

Keep Alive

// Extend sandbox lifetime await sandbox.keepAlive(600000) // Keep alive for 10 more minutes

Metadata

// Get metadata const metadata = await sandbox.getMetadata() // Update metadata await sandbox.setMetadata({ stage: 'testing', version: '1.0' })

Closing Sandboxes

Graceful Shutdown

// Close sandbox and clean up resources await sandbox.close()

Automatic Cleanup

try { const sandbox = await Sandbox.create() // Do work } finally { await sandbox.close() // Always cleanup }

Force Kill

// Force terminate immediately await sandbox.kill()

Timeouts

Default Timeout

Sandboxes have a default timeout of 5 minutes. After this period, they automatically shut down.

Custom Timeout

const sandbox = await Sandbox.create({ timeoutMs: 600000 // 10 minutes })

Extending Timeout

// Extend timeout while sandbox is running await sandbox.setTimeout(900000) // Extend to 15 minutes total

Reconnecting to Sandboxes

Save Sandbox ID

const sandbox = await Sandbox.create() const sandboxId = sandbox.id // Store sandboxId for later

Reconnect Later

// Reconnect to existing sandbox const sandbox = await Sandbox.connect(sandboxId) // Continue working const result = await sandbox.commands.run('ls')

Listing Sandboxes

List All Running Sandboxes

import { Sandbox } from 'e2b' const sandboxes = await Sandbox.list() console.log('Running sandboxes:', sandboxes)

Filter by Metadata

const sandboxes = await Sandbox.list({ metadata: { project: 'my-project' } })

Best Practices

1. Always Close Sandboxes

const sandbox = await Sandbox.create() try { // Your code here } finally { await sandbox.close() }

2. Use Appropriate Timeouts

// Short-lived tasks const sandbox = await Sandbox.create({ timeoutMs: 60000 }) // 1 minute // Long-running tasks const sandbox = await Sandbox.create({ timeoutMs: 3600000 }) // 1 hour

3. Handle Errors

try { const sandbox = await Sandbox.create() // Work with sandbox } catch (error) { console.error('Sandbox creation failed:', error) // Handle error } finally { if (sandbox) await sandbox.close() }

4. Use Metadata for Organization

const sandbox = await Sandbox.create({ metadata: { user: userId, session: sessionId, purpose: 'code-execution' } })

Lifecycle Events

Monitor sandbox lifecycle events:

sandbox.on('start', () => { console.log('Sandbox started') }) sandbox.on('close', () => { console.log('Sandbox closed') }) sandbox.on('error', (error) => { console.error('Sandbox error:', error) })

Resource Limits

CPU and Memory

Sandboxes have default resource limits:

  • CPU: 2 vCPUs
  • Memory: 2GB RAM
  • Disk: 10GB storage

Custom limits can be configured through templates.

Rate Limits

See Rate Limits for API rate limiting information.

Common Patterns

Pool Pattern

class SandboxPool { constructor(size) { this.pool = [] this.size = size } async init() { for (let i = 0; i < this.size; i++) { const sandbox = await Sandbox.create() this.pool.push(sandbox) } } async acquire() { if (this.pool.length === 0) { return await Sandbox.create() } return this.pool.pop() } release(sandbox) { this.pool.push(sandbox) } async cleanup() { await Promise.all(this.pool.map(s => s.close())) } }

Retry Pattern

async function createSandboxWithRetry(maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await Sandbox.create() } catch (error) { if (i === maxRetries - 1) throw error await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))) } } }