You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/docs/sandbox/api/sessions.mdx
+62-20Lines changed: 62 additions & 20 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -13,6 +13,44 @@ Create isolated execution contexts within a sandbox. Each session maintains its
13
13
Every sandbox has a default session that automatically maintains shell state. Create additional sessions when you need isolated shell contexts for different environments or parallel workflows.
14
14
:::
15
15
16
+
## Sandbox options
17
+
18
+
When creating a sandbox with `getSandbox()`, you can configure its lifecycle behavior:
-`keepAlive` (boolean) - Keep the container alive indefinitely by preventing automatic shutdown. When `true`, the container will never auto-timeout and must be explicitly destroyed using `destroy()`. Default: `false`
29
+
30
+
<TypeScriptExample>
31
+
```
32
+
// For long-running processes that need the container to stay alive
await sandbox.destroy(); // Required to prevent resource leaks
45
+
}
46
+
47
+
````
48
+
</TypeScriptExample>
49
+
50
+
:::caution[Resource management with keepAlive]
51
+
When `keepAlive: true` is set, containers will not automatically timeout and must be explicitly destroyed using `destroy()` to prevent resource leaks and avoid counting toward account limits indefinitely.
Containers automatically sleep after 3 minutes of inactivity, but still count toward account limits. Use `destroy()` to immediately free up resources.
161
+
Containers automatically sleep after 10 minutes of inactivity, but still count toward account limits. Use `destroy()` to immediately free up resources.
162
+
163
+
**Important**: When using `keepAlive: true`, containers will not automatically timeout, so calling `destroy()` is **required** to prevent resource leaks.
124
164
:::
125
165
126
166
<TypeScriptExample>
127
167
```
128
168
async function executeCode(code: string): Promise<string> {
awaitsandbox.exec('echo "Hello"'); // First request creates sandbox
25
25
```
26
26
27
-
**Duration**: 100-300ms (cold start) or \<10ms (if warm)
28
-
29
27
### Active
30
28
31
29
The sandbox container is running and processing requests. All state remains available: files, running processes, shell sessions, and environment variables.
32
30
33
31
### Idle
34
32
35
-
After a period of inactivity, the container stops to free resources. When the next request arrives, a fresh container starts. All previous state is lost and the environment resets to its initial state.
33
+
After a period of inactivity (10 minutes by default), the container stops to free resources. When the next request arrives, a fresh container starts. All previous state is lost and the environment resets to its initial state.
36
34
37
35
### Destruction
38
36
@@ -48,12 +46,14 @@ await sandbox.destroy();
48
46
Sandbox state exists only while the container is active. Understanding this is critical for building reliable applications.
49
47
50
48
**While the container is active** (typically minutes to hours of activity):
49
+
51
50
- Files written to `/workspace`, `/tmp`, `/home` remain available
52
51
- Background processes continue running
53
52
- Shell sessions maintain their working directory and environment
54
53
- Code interpreter contexts retain variables and imports
55
54
56
55
**When the container stops** (due to inactivity or explicit destruction):
56
+
57
57
- All files are deleted
58
58
- All processes terminate
59
59
- All shell state resets
@@ -95,6 +95,7 @@ Idempotent operations with clear task-to-sandbox mapping. Good for builds, pipel
95
95
The first request to a sandbox determines its geographic location. Subsequent requests route to the same location.
96
96
97
97
**For global apps**:
98
+
98
99
- Option 1: Multiple sandboxes per user with region suffix (`user-123-us`, `user-123-eu`)
99
100
- Option 2: Single sandbox per user (simpler, but some users see higher latency)
100
101
@@ -104,10 +105,10 @@ The first request to a sandbox determines its geographic location. Subsequent re
## Keep containers alive for long-running processes
163
+
164
+
By default, containers automatically shut down after 3 minutes of inactivity. For long-running processes that may have idle periods (like CI/CD pipelines, batch jobs, or monitoring tasks), use the `keepAlive` option:
165
+
166
+
<TypeScriptExample>
167
+
```
168
+
import { getSandbox, parseSSEStream, type LogEvent } from '@cloudflare/sandbox';
// Process can run indefinitely without container shutdown
185
+
for await (const log of parseSSEStream<LogEvent>(logs)) {
186
+
console.log(log.data);
187
+
if (log.data.includes('Build complete')) {
188
+
break;
189
+
}
190
+
}
191
+
192
+
return new Response('Build completed');
193
+
} finally {
194
+
// Important: Must explicitly destroy when done
195
+
await sandbox.destroy();
196
+
}
197
+
}
198
+
};
199
+
```
200
+
</TypeScriptExample>
201
+
202
+
:::caution[Always destroy with keepAlive]
203
+
When using `keepAlive: true`, containers will not automatically timeout. You **must** call `sandbox.destroy()` when finished to prevent resource leaks and avoid counting containers toward your account limits indefinitely.
204
+
:::
205
+
162
206
## Best practices
163
207
164
208
-**Wait for readiness** - Stream logs to detect when services are ready
165
209
-**Clean up** - Always stop processes when done
166
210
-**Handle failures** - Monitor logs for errors and restart if needed
167
211
-**Use try/finally** - Ensure cleanup happens even on errors
212
+
-**Use keepAlive for long-running tasks** - Prevent container shutdown during processes with idle periods
168
213
169
214
## Troubleshooting
170
215
@@ -199,6 +244,7 @@ const server = await sandbox.startProcess('node server.js');
199
244
## Related resources
200
245
201
246
-[Commands API reference](/sandbox/api/commands/) - Complete process management API
247
+
-[Sessions API reference](/sandbox/api/sessions/) - Container lifecycle and keepAlive option
0 commit comments