MemoryLimitExceededError
e2b.sandbox.errors.MemoryLimitExceededError
Stack trace
e2b.sandbox.errors.MemoryLimitExceededError: Sandbox memory limit exceeded (limit: 512MB)
File "/app/e2b/sandbox/runner.py", line 87, in run_code
raise MemoryLimitExceededError("Sandbox memory limit exceeded (limit: 512MB)")
File "/app/e2b/sandbox/runner.py", line 45, in execute
self.run_code()
File "/app/main.py", line 22, in main
sandbox.execute(user_code)
MemoryLimitExceededError: Sandbox memory limit exceeded (limit: 512MB) Why it happens
The E2B sandbox enforces strict memory limits to isolate user code execution. When the executed code allocates more memory than the configured limit, the sandbox forcibly terminates the process and raises this error to prevent resource exhaustion and maintain system stability.
Detection
Monitor sandbox execution logs for MemoryLimitExceededError exceptions and track memory usage metrics to detect when user code approaches or exceeds the memory limit before termination.
Causes & fixes
User code creates large in-memory data structures exceeding the sandbox memory limit.
Optimize the code to use memory-efficient data structures or process data in smaller batches to reduce peak memory usage.
Infinite loops or recursive calls causing uncontrolled memory growth.
Add loop termination conditions and limit recursion depth to prevent runaway memory consumption.
Sandbox memory limit is set too low for the workload requirements.
Increase the sandbox memory limit configuration if the workload legitimately requires more memory.
Code: broken vs fixed
from e2b.sandbox import Sandbox
sandbox = Sandbox(memory_limit_mb=512)
user_code = 'a = [0] * (10**8) # This will exceed memory limit'
sandbox.execute(user_code) # Raises MemoryLimitExceededError here import os
from e2b.sandbox import Sandbox
sandbox = Sandbox(memory_limit_mb=1024) # Increased memory limit
user_code = 'a = [0] * (5 * 10**7) # Reduced memory usage'
sandbox.execute(user_code) # Runs without error
print('Code executed within memory limits') Workaround
Catch MemoryLimitExceededError in your application, then refactor the user code to reduce memory usage or split tasks into smaller chunks to run sequentially within limits.
Prevention
Design user workloads to operate within known memory constraints and implement monitoring with alerts on memory usage to proactively adjust sandbox limits or optimize code before hitting limits.