Designing an isolated notebook execution platform
System DesignModel answerLast updated
Design a multi-tenant cloud notebook platform that runs untrusted user code in isolated sandboxes and streams output, with focus on isolation, lifecycle, persistence and observability.
Design a sandboxed cloud notebook platform
You are designing a browser-based, multi-tenant notebook/IDE service where users write code, execute it in a remote isolated environment, and watch the results appear live.
What users do
- Open a workspace (project or notebook), edit code in the editor, and run individual cells or shell commands.
- See results in the UI: stdout, stderr, rich outputs (plots, HTML, images).
- Watch log output streaming while the code is still running.
Requirements
Functional
- Spin up an isolated compute environment for each workspace/session.
- Execute arbitrary user-supplied code without harming the platform or other tenants.
- Stream execution output and logs to the browser with low latency.
- Support file upload/download and persistent workspace state between sessions.
- Collaboration is optional — if you include it, say so explicitly and keep it simple.
Non-functional
- Tenant isolation is the top priority; security failures are unacceptable.
- New sessions should start quickly enough to feel interactive.
- The platform must autoscale and share resources fairly across tenants.
- Observability: metrics, tracing, and audit logging.
What to cover
- How you pick and manage the compute substrate (plain VMs vs. containers vs. microVMs).
- The isolation model: filesystem, network, process, credentials.
- The architecture for streaming output/logs.
- Lifecycle management: create, run, go idle, suspend/resume, terminate.
- How workspace data is persisted (files, snapshots/checkpoints).
State your assumptions, sketch the API, and describe the high-level architecture.
Hints
Hint 1
Start by anchoring the design on security: arbitrary code is hostile by default, so argue explicitly why containers sharing a kernel are or aren't acceptable before drawing anything else.
Hint 2
Separate the control plane (session state machine, scheduler, quotas) from the data plane (the hosts that actually run code), and decide who is allowed to touch what.
Hint 3
Think about streaming as a durable, sequenced log rather than a raw socket into the sandbox: how does a browser reconnect without losing or duplicating output?
Hint 4
Don't forget the boring parts that break sandboxes: the cloud metadata endpoint, east-west traffic between tenants, and long-lived credentials leaking into a guest.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
A strong answer starts by pinning down scope and numbers, then argues that security dominates every other trade-off, then fills in the boxes.
1. Assumptions and sizing
- 10M registered users, ~500K daily actives, ~100K concurrent sessions at peak.
- Default sandbox: 2 vCPU, 4–8 GB RAM, 20 GB disk. GPU tier exists but is quota-gated and scheduled onto dedicated nodes.
- Median session length ~45 min; idle-suspend after 15 min; hard-terminate after 24 h.
- Startup targets: p50 < 2 s (warm), p95 < 10 s (cold), resume from snapshot < 5 s.
- End-to-end output latency < 300 ms; output rate-limited above ~1 MB/s per session.
- Collaboration: read-only sharing plus last-writer-wins file saves only. Real-time co-editing (CRDT) is an explicit non-goal.
Capacity: 100K × 2 vCPU = 200K vCPU. On 96-vCPU hosts at ~1.5× oversubscription (notebooks are bursty), that's ~1,400 hosts, plus ~10% warm-pool headroom.
2. API sketch
POST /v1/workspaces -> {workspace_id}
POST /v1/workspaces/{id}/sessions {machine_type, image} -> {session_id, state}
GET /v1/sessions/{sid} -> {state: PROVISIONING|RUNNING|IDLE|SUSPENDED|TERMINATED}
POST /v1/sessions/{sid}/executions {code|command, cell_id} -> {execution_id}
POST /v1/executions/{eid}:cancel
WS /v1/sessions/{sid}/stream?cursor=N // multiplexed channels, resumable
GET/PUT /v1/workspaces/{id}/files/{path} // presigned URLs for large transfers
POST /v1/sessions/{sid}:suspend | :resume | :terminate
Every streamed event carries (execution_id, seq, channel, payload) so a reconnecting client resumes from cursor with no loss or duplication.
3. Data model
Workspace (id, owner, org, image, quota tier, storage pointer), Session (id, workspace_id, host_id, sandbox_id, state, timestamps, snapshot_ref), Execution (id, session_id, cell_id, status, exit code, log_object_ref), AuditEvent (append-only: actor, action, resource, time, source IP). Metadata in Postgres/Spanner; logs and snapshots in object storage; hot output buffers in Kafka or Redis Streams.
4. Architecture
- Browser → API gateway (authn, rate limiting, WebSocket termination) via CDN.
- Control plane: workspace/session service owning the state machine; scheduler that bin-packs sandboxes by quotas, fair share, and image locality; warm-pool manager; quota/billing. The control plane never executes user code.
- Data plane: bare-metal hosts, each running a host agent plus N Firecracker microVMs; inside each VM a tiny supervisor runs processes and captures output. The data plane never holds credentials beyond one session's scope.
- Streaming tier: supervisor → vsock → host agent → per-session durable log partition → stream-gateway nodes fanning out over WebSockets.
- Storage: per-workspace volume on block storage, snapshots in object storage, content-addressed base images with lazy layer loading.
- Egress proxy/NAT for all sandbox traffic; observability via metrics, tracing across control plane and agents, and an immutable audit sink.
5. Deep dives
Substrate. Containers (runc) share a kernel — one kernel CVE is a tenant breakout, so they're out for hostile code. Full VMs boot in 30–60 s: too slow and too expensive per session. gVisor gives a user-space kernel with good isolation but pays syscall overhead and has compatibility gaps. Firecracker microVMs are the fit: KVM-based hardware virtualization, tiny device model, ~125 ms boot, ~5 MB overhead. Kata Containers is a fine alternative if you want OCI image compatibility. Defense in depth: jail the VMM with seccomp, cgroups, and a dedicated user. For GPUs, use dedicated nodes or full passthrough VMs — microVM device support is limited, and the GPU tier should never co-locate two orgs on one host.
Isolation model.
- Process: user code is non-root inside the guest; the guest kernel is boundary one, the VMM is boundary two.
- Filesystem: read-only shared base image plus a per-session writable overlay; the workspace volume mounts only into its own VM; nothing from the host is exposed.
- Network: one tap device per VM in its own namespace. Deny all east-west traffic, block the metadata endpoint (169.254.169.254) and internal CIDRs, and force egress through a proxy with allow/deny lists, bandwidth caps, and abuse detection (mining, spam, scanning).
- Credentials: no long-lived secrets in the guest; user secrets are minted as short-lived tokens scoped to one workspace at session start; platform credentials stay on the host agent.
- Resources: cgroup CPU/memory limits on the VMM, disk quotas, PID limits, output rate limits — these double as the fairness mechanism.
Streaming. The supervisor chunks stdout/stderr (and Jupyter-style rich messages) at 4–16 KB or every 50 ms, stamps a monotonic seq, and sends over vsock. The host agent publishes to a durable per-session stream, decoupling producers from slow browsers and enabling replay. The stream gateway applies backpressure: when a client lags, coalesce or drop intermediate progress frames but never drop final output; cap total output and write the full log to object storage for later retrieval. Don't wire a WebSocket directly into the VM — it exposes the sandbox to inbound traffic, dies with gateway restarts, and can't fan out.
Lifecycle. PROVISIONING → RUNNING ⇄ IDLE → SUSPENDED → (RESUMING → RUNNING) | TERMINATED. Create claims a warm-pool VM for the image and attaches the workspace volume. Idle detection (no exec, no websocket activity) flushes writes, snapshots memory and disk, and returns the host's resources to the pool. Resume restores from snapshot into a warm host. Terminate revokes tokens, wipes the overlay, and keeps only the persisted workspace. A reaper enforces the 24 h cap.
Persistence. Workspace files live on a volume attached to one VM at a time; on suspend, sync to object storage. Checkpoints are periodic disk snapshots plus an optional VM memory snapshot for fast resume; keep a small rolling set to bound cost.
Observability. Per-session metrics (CPU, memory, boot time, output throughput, idle rate), distributed traces from API to host agent, and audit events for every session start, exec, and credential mint.
Common mistakes. Treating containers as sufficient isolation; leaving the metadata endpoint reachable; injecting long-lived secrets into the guest; streaming over a raw socket with no sequence numbers or replay; forgetting the snapshot-and-reap path so idle sessions hold hosts forever; ignoring noisy-neighbor fairness until it's a production incident.