Design a Coding Playground – Frontend System Design

We’ll walk through the frontend system design for a coding playground like LeetCode or CodePen: a Monaco editor, a Run button that must not crash the tab, a preview that cannot steal the user’s cookies, and a Submit button that talks to a judge and streams a verdict. You’ll see why user code never runs on the app origin, how a Web Worker you can terminate is different from an iframe you cannot, why in-browser runtimes (esbuild-wasm, Pyodide) sit behind that boundary, and how an idempotent submit plus SSE keeps a refresh from double-charging a run.
This is not the VS Code for the web question. A browser IDE is about a text buffer, language servers, and a virtual file system. A playground is about executing untrusted code and showing a result. The editor is the easy part. The isolation boundary is the product.
Problem Statement
Design the frontend for a coding playground used for algorithm problems and front-end sandboxes.
Requirements:
- Edit JavaScript, TypeScript, Python, and HTML/CSS in a split pane
- Run code in the browser for instant feedback, with a Stop button that actually stops
- Submit to a server judge that runs hidden tests and streams a verdict
- Show a live preview for HTML/CSS/JS problems without letting that preview read the session
- Persist drafts locally, restore them after a refresh, and keep a history of submissions
- Survive a user who pastes an infinite loop, fetches the app origin, or opens 20 tabs and mashes Submit
Describe the client architecture, the sandbox, the submit protocol, and how verdicts reach the UI.
Interviewers are checking three things. Do you treat user code as hostile? Can you stop a runaway loop without reloading the page? And do you know that a judge result is a stream, not a single JSON response you await for thirty seconds?
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Which languages on day one? | JavaScript and TypeScript in the browser. Python in the browser via Pyodide, and on the server for submit. HTML/CSS/JS previews for UI problems. |
| 2 | Is Run the same as Submit? | No. Run uses the sample tests the problem ships. Submit hits the judge and the hidden tests. Run never leaves the machine if we can help it. |
| 3 | How long can a submit take? | Up to 30 seconds of CPU on the judge, plus queue time. The UI must stay interactive and survive a refresh in the middle. |
| 4 | Do we need to support native addons or fs? |
No. The in-browser runtimes get a virtual FS. The judge has a real sandbox with no network. |
| 5 | Can users install packages? | A small allow-list of ESM imports from a CDN we control. Arbitrary npm install is out of scope. |
| 6 | Auth? | Signed-in users. Submissions count toward a rate limit. Anonymous visitors can run locally, not submit. |
| 7 | Browser support? | Evergreen Chrome, Edge, Firefox, and Safari 16+. SharedArrayBuffer is nice-to-have for Pyodide, not required for JS. |
Question 2 splits the architecture in half. Local run is a sandbox you own. Submit is a job you do not own, so the protocol is enqueue-and-subscribe, not request-and-wait. Question 3 means the submit button cannot block the editor, and a dropped SSE must resume. Question 5 is how you keep the preview from becoming a malware host.
Requirements
Functional
- A problem statement pane, an editor, a test results pane, and an optional preview pane.
- Run executes against the sample tests and prints stdout, stderr, runtime, and pass/fail per case.
- Stop kills the current run within one animation frame of the click, even if the code is in a tight loop.
- Submit enqueues a job, streams status (queued, compiling, running, per-test events), and ends on a verdict.
- Drafts autosave locally. A refresh restores the last editor state, not the last accepted submission.
- A submissions list shows previous verdicts. Opening one loads that source read-only, with a button to copy it into the editor.
Non-Functional
- User code cannot read cookies, localStorage, or tokens on the app origin.
- User code cannot navigate the parent, install service workers on the app origin, or make credentialed requests to it.
- A local run starts in under 200ms after the runtime is warm. First Python run may take a few seconds to fetch the wheel.
- The editor stays at 60fps while a run or a submit is in flight.
- A double-click on Submit creates one job. A refresh mid-stream reconnects to the same job.
- Hidden test inputs never reach the client, including in error messages and stack traces.
Architecture
Three origins, three jobs.
The app origin (app.example.com) holds the session cookie, the problem text, the editor, and the view-model. It never evals user code. It never mounts a preview as a same-origin iframe. It talks to the API with credentials and to the sandbox with postMessage.
The sandbox origin (sandbox.example.com, a different site) is a static host with no cookies and no access to the API. It serves a runner page and a preview page. The runner page starts a Worker, loads esbuild-wasm or Pyodide, executes the payload, and posts results back. The preview page is an opaque-origin iframe (sandbox="allow-scripts" without allow-same-origin) that renders HTML. Both are replaceable: killing a run means tearing down the iframe or terminating the worker, not asking the user code to stop.
The judge is a server pipeline. The app POSTs a submission, gets a job id, and subscribes over SSE. A worker leases the job, compiles, runs hidden tests, and emits events. The client never sees the hidden inputs. It sees per-test pass/fail, timings, and a final verdict.
Keep those three apart in the code, not just in the diagram. A helper that “just evals in a worker on the app origin for speed” is how you leak the session. A preview iframe pointed at a blob: URL on the app origin is the same leak with extra steps: a blob inherits the creator’s origin.
Data Model
The server owns problems, tests, submissions, and the leaderboard. The client owns the draft.
type Language = "javascript" | "typescript" | "python" | "html";
interface Problem {
id: string;
title: string;
statementHtml: string;
languages: Language[];
timeLimitMs: number;
memoryLimitMb: number;
sampleTests: SampleTest[];
}
interface SampleTest {
id: string;
input: string;
expected: string;
}
interface HiddenTest {
id: string;
input: string;
expected: string;
}
interface Draft {
problemId: string;
language: Language;
files: Record<string, string>;
updatedAt: number;
revision: number;
}
type Verdict =
| "accepted"
| "wrong_answer"
| "time_limit_exceeded"
| "memory_limit_exceeded"
| "runtime_error"
| "compile_error";
type SubmissionStatus =
| { kind: "queued" }
| { kind: "compiling" }
| { kind: "running"; passed: number; total: number }
| { kind: "done"; verdict: Verdict }
| { kind: "system_error"; retryable: true };
interface Submission {
id: string;
problemId: string;
language: Language;
source: Record<string, string>;
createdAt: string;
status: SubmissionStatus;
results: TestResult[];
}
interface TestResult {
testId: string;
hidden: boolean;
passed: boolean;
timeMs?: number;
message?: string;
}
A few rules that keep this from rotting.
- Sample tests ship. Hidden tests do not. The client can run samples locally because the problem already published them. A hidden test’s input and expected output never appear in GraphQL, in SSE payloads, or in a
wrong_answermessage. The UI shows “Hidden test 3 failed” and a sanitized stderr, not the input that would let someone reverse the solution. - The draft is not a submission. Autosave writes
Draftto IndexedDB keyed byproblemId. Submit snapshots the files into aSubmission. Editing after submit must not mutate the snapshot you just sent. - Revision is for conflict-free autosave, not for the judge. Two tabs increment
revisionand last-write-wins locally. The judge keys jobs by an idempotency key the client generates per click, not by revision. - System error is not a verdict. A crashed worker or a 503 is retryable. It must not land on the leaderboard or consume the user’s “wrong answer” mental model.
The Origin Boundary
This is the part most candidates wave at and get wrong. Same-origin is not a sandbox.
What the user code will try
| Attempt | If you ran it on the app origin | What actually stops it |
|---|---|---|
document.cookie / localStorage |
Reads the session | Different site, or an opaque origin (sandbox without allow-same-origin) |
fetch("/api/me") |
Sends cookies | Cross-site request with no credentials; API CORS does not allow the sandbox origin |
window.parent.location = ... |
Navigates the app | Cross-origin frame cannot assign parent location in modern browsers; also sandbox without allow-top-navigation |
| Register a service worker | Intercepts the app forever | Opaque origin cannot register a worker against the app; the sandbox site has none to steal |
| Infinite loop | Freezes the tab, including the Stop button | The loop runs in a Worker or a child iframe. The parent terminates it. |
Two isolation tools, two jobs
A Web Worker you create from the sandbox page is the right home for JS/TS/Python execution. You can worker.terminate() and the loop is gone. You can give it a timeout with setTimeout in the parent and kill it if the result has not arrived. Workers do not have a DOM, which is what you want for algorithm problems.
An iframe is the right home for an HTML preview, because the user wants a document. Use a child iframe with:
<iframe
sandbox="allow-scripts"
src="https://sandbox.example.com/preview"
referrerpolicy="no-referrer"
></iframe>
Leaving off allow-same-origin gives the frame an opaque origin. It can run scripts. It cannot read or write storage, and it cannot talk to the app origin as itself. Do not load the preview from a blob: or srcdoc on the app origin. Those inherit the app origin and the session comes with them.
The app talks to both through postMessage with an explicit event.origin check. The payload is a structured clone: files, language, sample tests, a run id. The response is stdout, stderr, pass/fail, or a crash. Never include tokens in that message.
Content Security Policy on the sandbox
The sandbox response is static, so you can lock it down hard:
default-src 'none'script-src 'self' 'wasm-unsafe-eval'(Pyodide and esbuild-wasm need WebAssembly)connect-srconly your package CDNframe-ancestors https://app.example.com- No
allow-same-origin, noallow-top-navigation, noallow-popups
The app origin’s CSP does the opposite: it frames only https://sandbox.example.com, and its own scripts never use eval.
Local Run
Run is the path the user hits every few seconds. It has to feel like a REPL, not like a deploy.
JavaScript and TypeScript
The sandbox runner loads esbuild-wasm once and keeps it. A run message looks like this:
type RunRequest = {
runId: string;
language: Language;
files: Record<string, string>;
tests: SampleTest[];
timeLimitMs: number;
};
type RunEvent =
| { kind: "compile_error"; runId: string; message: string }
| { kind: "test"; runId: string; testId: string; passed: boolean; stdout: string; timeMs: number }
| { kind: "done"; runId: string }
| { kind: "crash"; runId: string; message: string };
The worker bundles the user files to a single IIFE, injects a tiny harness that reads stdin for each sample, and importScripts or evals the bundle inside the worker. The harness posts one test event per case. If esbuild throws, you get compile_error and you never start the loop.
A few things that bite people in interviews:
- Stop is
terminate(), not a flag. User code will not check yourshouldStopboolean. Kill the worker. Create a new one for the next run. Warm esbuild on the new worker in the background so the next Run is fast. - Time limits live in the parent. The worker cannot be trusted to honor
timeLimitMs. The parent starts a timer when it sends the request and terminates on expiry. That becomestime_limit_exceededin the UI. - Memory is best-effort in the browser. You cannot set a 64MB cgroup on a Worker. You can watch for the tab’s
memorypressure events and kill the run. Honest about this in the interview. The real memory limit is a judge property. - Do not share one worker across runs. A previous run can leave globals, timers, or a mutated prototype. One worker, one run, then discard.
Python
Pyodide is a CPython compiled to WebAssembly plus a set of wheels. The first load is several megabytes. Cache the downloaded assets in Cache Storage on the sandbox origin, show a one-time “Loading Python” state, and keep the module warm in a parked worker so the second run is instant.
SharedArrayBuffer plus Atomics lets Pyodide interrupt a tight loop without terminate(). That needs cross-origin isolation (Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp) on the sandbox origin. If you cannot ship COOP/COEP, fall back to terminate() the same way you do for JS. Do not block the whole design on SharedArrayBuffer.
HTML preview
The preview iframe receives a srcdoc-equivalent payload via postMessage and writes it with document.open/write/close inside the opaque frame. Rewrite user-supplied <script src> to your allow-listed CDN. Strip <meta http-equiv="refresh">, <base>, and service-worker registration. A new Run replaces the iframe entirely so leftover timers and open IndexedDB connections die with the document.
Console from the preview arrives as postMessage events you append to the results pane. You cannot hook console.log across origins any other reliable way.
Submit: From Click to Streamed Verdict
Submit is a job, not a request. The POST returns in milliseconds. Everything after that is a stream.
// POST /problems/:id/submissions
// Idempotency-Key: <uuid generated on click>
// body: { language, files }
type EnqueueResponse = {
submissionId: string;
streamUrl: string;
};
The client opens EventSource(streamUrl). Events look like this:
type StreamEvent =
| { id: string; type: "status"; data: SubmissionStatus }
| { id: string; type: "test"; data: TestResult }
| { id: string; type: "verdict"; data: { verdict: Verdict; results: TestResult[] } }
| { id: string; type: "error"; data: { retryable: boolean; message: string } };
Why this shape:
- Idempotency-Key is generated once per click, stored on the pending submission, and sent on every retry. A timeout, a double-click, or a React Strict Mode remount must not enqueue two jobs. If the POST fails, retry with the same key. If it still fails,
GET /submissions?key=before telling the user it failed. The job may exist. - The stream is resumable.
EventSourcesendsLast-Event-IDon reconnect. The server replays from that id. A refresh mid-run opens the samestreamUrlfrom the submission id in the URL or in sessionStorage. The user sees “running, 4/10 passed” instead of a blank page they have to guess about. - Per-test events exist so the UI can animate. Waiting 20 seconds for one JSON blob feels broken even when the judge is working. A running count is the difference between “is this hung?” and “it is working.”
- The client acks the verdict. Once
verdictarrives, POST/submissions/:id/ackso the server can drop the buffer. Until then it keeps a short replay log.
Do not await fetch('/submit') for the whole job. Proxies, browsers, and your own load balancer will time out a 30-second request. SSE (or a WebSocket) is the API. Long polling is the fallback if a corporate proxy eats EventSource.
Submission State Machine
Three working states, six final verdicts, one retryable error. The UI is a function of this machine. Do not invent a parallel “isSubmitting” boolean in React.
type SubmissionEvent =
| { type: "ENQUEUED"; id: string }
| { type: "STATUS"; status: SubmissionStatus }
| { type: "TEST"; result: TestResult }
| { type: "VERDICT"; verdict: Verdict; results: TestResult[] }
| { type: "SYSTEM_ERROR" }
| { type: "RETRY" };
A pure reducer maps each event onto the submission. STATUS updates the working state unless the submission is already done, so a replayed “running” after the verdict can’t move it backward. TEST appends a result for the live count. VERDICT moves to done and replaces the partial results with the server’s final list, which is the source of truth. SYSTEM_ERROR moves to a retryable error state. Anything else leaves the state unchanged.
A few transitions people miss:
- Queued can last a long time. Show position if the server sends it. A spinner with no number looks stuck at minute two of a contest.
- Compiling is not running. A TypeScript or C++ compile can take longer than the tests. Keep the label honest so users do not hit Stop thinking the tests hung.
- Wrong answer, TLE, MLE, runtime error, and compile error are terminal. They write to history. The editor stays editable. The user can edit and submit again. That is a new job with a new idempotency key.
- Accepted is terminal and sticky. The submissions list marks it. The leaderboard row is a server-side write the client only reads.
- System error does not consume the attempt. Offer Retry, reuse the same source, generate a new key or reuse the old one if the original job never started. Do not tell the user their algorithm failed.
- A late event after
doneis ignored. Reconnects can replay. The reducer must be idempotent on submission id plus event id.
Stop on a local run tears down the worker. Stop on a submit is a POST /submissions/:id/cancel. The judge may already be on test 9 of 10. The UI goes to a cancelled state only after the server confirms. Do not pretend a cancel that has not landed is a verdict.
State and Data Flow
The editor is a Monaco instance you mount once. The view-model around it is small.
- Draft store. Files, language, revision. Writes to IndexedDB on a debounce (500ms, or on blur). This is the only client state that survives a refresh without a network.
- Run store. The current
runId, events, and a handle to the sandbox iframe. A new Run incrementsrunIdand the sandbox drops events from the previous id. This is how you ignore a result that arrives after Stop. - Submission store. The active job plus the history list. History is server state, cached. The active job is a reducer over the SSE.
- Problem store. Statement, samples, limits. Immutable for the life of the page. Switching problems tears down run and draft (after a save) and loads the new ones.
Monaco talks to the draft store through a thin adapter, not through React on every keystroke. You subscribe to onDidChangeModelContent, write the file into the store, and let React re-render the results pane, not the editor. Putting the whole model in React state is how the typing latency shows up.
The sandbox iframe is created by a layout effect and stored in a ref. React does not own its document. Sending a run is a method call, not a prop change. A prop change is how you accidentally reload the iframe mid-run and lose the warm Pyodide heap.
API
| Method | Path | Purpose |
|---|---|---|
| GET | /problems/:id |
Statement, languages, samples, limits. No hidden tests. |
| POST | /problems/:id/submissions |
Enqueue. Requires Idempotency-Key. Returns submissionId and streamUrl. |
| GET | /submissions/:id/stream |
SSE. Supports Last-Event-ID. |
| POST | /submissions/:id/ack |
Client got the verdict. Server may drop replay. |
| POST | /submissions/:id/cancel |
Best-effort cancel of a running job. |
| GET | /problems/:id/submissions |
History for the current user. Source included. Hidden inputs never. |
| GET | /problems/:id/draft |
Optional server copy of the draft for signed-in users, merged with IndexedDB by updatedAt. |
Rate limit Submit on the server by user and by problem. The client disables the button while a job is not terminal, but that is not the real limit. Twenty tabs will bypass it. Show the 429 as a quota, not as a system error, so the user knows they should wait, not retry-spam.
Autosave and Multi-Tab Drafts
IndexedDB holds the draft. A BroadcastChannel("draft:" + problemId) tells other tabs a write landed. The receiving tab compares revision and either applies the files or ignores them if the local editor is dirty with a higher revision.
Do not put the full source in localStorage. Problems get large, and the quota is small. IndexedDB also stays off the main thread if you wrap writes in a worker, which keeps typing smooth during a save.
Signed-in users get a server copy so a new device is not empty. Merge is last-write-wins on updatedAt, shown as a toast if the server copy is newer than the local one when the page opens. Do not silently clobber a local draft the user has been editing offline.
The URL is /problems/:id for the live editor and /problems/:id/submissions/:sid for a historical snapshot. Sharing the second link to another user 404s unless the problem is public and you explicitly support solution sharing. Default to private.
Optimizations
- Warm the sandbox on problem load, not on first Run. The iframe, esbuild-wasm, and the Pyodide download can start while the user reads the statement. First Run then feels instant.
- Cache runtimes on the sandbox origin. Service worker or Cache Storage. The app origin must not cache them; they are not its files, and a SW on the app origin is a privilege you do not want near user code.
- Prefetch the next problem’s statement on the list page. Do not prefetch Pyodide for a JS-only problem.
- Virtualize the submissions list and the test results. A problem with 200 hidden tests should not mount 200 rows if you only show a summary plus the first failure.
- Keep Monaco’s model alive across layout changes. Moving the pane is a CSS change. Destroying the editor to re-mount it is a hitch and a lost undo stack.
- Do not re-render the problem statement on every keystroke. It is static HTML. Memoize it. The results pane subscribes to the run store; the statement does not.
Handling Edge Cases
- Infinite loop. Parent timeout plus
terminate(). Ifterminate()itself hangs (it should not, but people ask), reload the sandbox iframe. That is the bigger hammer and it costs the warm runtime. - Alert / prompt / confirm in the preview. The opaque iframe can still call them in some browsers. You cannot disable them from the parent. Document it. Do not promise you can.
- Huge stdout. Cap the captured output at a few hundred KB in the worker before posting it. A
while(1) console.logshould not lock the results pane or blow memory in the app. - Emoji, RTL, and unusual Unicode in source. Monaco handles it. The judge must receive the same bytes you hashed for idempotency. Normalize to NFC once, on submit, and show the user if you changed anything.
- The user switches problems while a job is running. The old SSE stays open in the store keyed by submission id. The new problem has its own draft. Do not cancel the old job unless they ask. They will want that verdict when they come back.
- The user logs out mid-stream. Close the EventSource. The job keeps running server-side. History will show it on next login.
- Clock skew on time limits. The client timer is a UX hint. The judge’s clock is the verdict. Never mark TLE locally for a submit.
- Safari and
EventSourcewith auth headers. EventSource cannot set Authorization. Put a short-lived stream token in the query string or use a cookie on the API host. Do not put the session cookie on the sandbox host.
Accessibility and Security
Accessibility
- The editor, the problem statement, and the results are three landmarks. A skip link jumps from the statement to the editor and from the editor to the first failed test.
- Run and Submit are real buttons with a busy state (
aria-busyon the results region). A live region announces “3 of 10 tests passed” and the final verdict. Do not announce every keystroke. - Stop is reachable from the keyboard and is not the same control as Submit. After a long run, focus moves to the first failed test, not back to the editor, so a screen-reader user does not have to hunt.
- Monaco has its own accessibility mode. Turn it on when
prefers-reduced-motionor a documented shortcut says so, and do not override its aria labels. - The preview iframe needs a title (“Live preview”) and a way to skip it. An empty preview is still a frame in the tab order if you forget
tabindex="-1"when it is idle.
Security
- Treat every file as untrusted text. The problem statement is the only HTML you render from the server, and it is sanitized on write, not on read.
- Hidden tests stay on the server. Sanitize judge stderr so a Python
print(open("/secret").read())on the judge (which should fail anyway) cannot become a side channel in the UI. - The sandbox origin has no cookies. If you ever put a cookie there, start over.
- Package imports resolve through your CDN, not through the public internet from the worker. An allow-list is a security control, not a convenience.
- CSP on both origins, COOP/COEP on the sandbox if you want SharedArrayBuffer, and
X-Frame-Options/frame-ancestorsso a third-party site cannot embed your editor and overlay a fake Submit.
What a Strong Answer Sounds Like
| Topic | Junior answer | Senior answer |
|---|---|---|
| Where code runs | eval in a worker on the app origin |
A different site, plus an opaque preview iframe; the app origin never executes user code |
| Stop | Set a cancelled flag the loop will read |
worker.terminate() or tear down the iframe; user code will not cooperate |
| Submit | await fetch('/submit') for 30 seconds |
Idempotent enqueue, SSE with Last-Event-ID, ack, cancel as a separate call |
| Hidden tests | Send them to the client so Run can use them | They never leave the judge; the client sees counts and sanitized errors |
| Drafts | localStorage.setItem on each keystroke |
IndexedDB, revision, BroadcastChannel, optional server merge by updatedAt |
For the editor internals themselves, see Design VS Code for the Web. For a judge-less live preview of other people’s pages, the same origin rules show up in sandboxed UI work: never give untrusted markup your origin.
Conclusion: How to Design a Coding Playground
Start with the boundary. The app origin holds the session and never runs user code. A second site runs it, in a worker you can kill for algorithms and in an opaque iframe for previews. If you cannot explain why a blob: URL on the app origin is a session leak, you are not done.
Then split Run from Submit. Run is local, warm, and disposable. Submit is a job: one idempotency key, a stream you can resume, a state machine with six real verdicts and a retryable system error that is not a verdict. Hidden tests stay hidden. The editor stays out of React’s render loop. Stop means terminate, not please-exit.
If you can walk through a double-click on Submit, a refresh mid-job, and an infinite loop without reloading the tab, you have the design. Everything else is Monaco chrome.
