Skip to content

Commit 6642d71

Browse files
per user sandbox example
1 parent 3dcfa22 commit 6642d71

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

docs/sandbox/auto-resume.mdx

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,62 @@ print(run_tool_task('python -c "print(2 + 2)"'))
153153
```
154154
</CodeGroup>
155155

156+
### Per-user sandboxes
157+
158+
For multi-tenant apps, keep a map of sandbox IDs by user. On each request, connect to the user's existing sandbox (which auto-resumes if paused) or create a new one.
159+
160+
<CodeGroup>
161+
```js JavaScript & TypeScript
162+
import { Sandbox } from 'e2b'
163+
164+
const userSandboxes = new Map() // userId → Sandbox
165+
166+
async function getSandbox(userId) {
167+
let sandbox = userSandboxes.get(userId)
168+
169+
if (!sandbox) {
170+
sandbox = await Sandbox.create({
171+
timeoutMs: 5 * 60 * 1000,
172+
lifecycle: {
173+
onTimeout: 'pause',
174+
resumeOn: 'any',
175+
},
176+
})
177+
userSandboxes.set(userId, sandbox)
178+
}
179+
180+
return sandbox
181+
}
182+
183+
// On each user request — auto-resumes if paused
184+
const sandbox = await getSandbox('user-123')
185+
const result = await sandbox.commands.run('echo "Hello from your sandbox"')
186+
console.log(result.stdout)
187+
```
188+
```python Python
189+
from e2b import Sandbox
190+
191+
user_sandboxes: dict[str, Sandbox] = {} # user_id → Sandbox
192+
193+
def get_sandbox(user_id: str) -> Sandbox:
194+
if user_id not in user_sandboxes:
195+
user_sandboxes[user_id] = Sandbox.create(
196+
timeout=5 * 60,
197+
lifecycle={
198+
"on_timeout": "pause",
199+
"resume_on": "any",
200+
},
201+
)
202+
203+
return user_sandboxes[user_id]
204+
205+
# On each user request — auto-resumes if paused
206+
sandbox = get_sandbox("user-123")
207+
result = sandbox.commands.run('echo "Hello from your sandbox"')
208+
print(result.stdout)
209+
```
210+
</CodeGroup>
211+
156212
## Cleanup
157213
Auto-resume is persistent, meaning if your sandbox resumes and later times out again, it will pause again.
158214

0 commit comments

Comments
 (0)