Design an Online Judge
Understanding the Problem
🧑💻 What is an online judge? An online judge lets people solve programming problems by submitting code. The system compiles and runs the code against hidden test cases, checks the output, and returns a verdict: Accepted, Wrong Answer, Time Limit Exceeded, and so on. LeetCode, Codeforces and HackerRank are the familiar ones. Many also run timed contests where thousands of people compete on the same problems with a live leaderboard.
A related question is "design Replit" or "design GitHub Codespaces": a browser-based environment where users write and run code interactively. It shares the hardest part of this problem, running arbitrary code from strangers without letting it hurt anyone, so we'll cover it as an extension in the last deep dive.
Functional Requirements
Core Requirements
- Users should be able to browse problems and read a problem's statement, examples and constraints.
- Users should be able to submit a solution in one of several languages and get a verdict, and run their code against custom input.
- Users should be able to join a timed contest and see a live leaderboard.
Below the line (out of scope)
- Authoring problems and test data (an admin tool).
- Discussion forums, editorials and social features.
- Plagiarism detection beyond a mention.
Non-Functional Requirements
Ask about scale. We'll assume 1 million submissions on a normal day and weekly contests with 100,000 participants.
Core Requirements
- Security: user code must never be able to read test data, reach the network, affect other submissions or escape onto our infrastructure.
- Fairness: the same code should get the same verdict and roughly the same runtime every time. Time limits mean nothing if one run is on a busy machine and the next isn't.
- Latency: most verdicts within a few seconds, even during a contest.
- Contest spikes: handle the burst at contest start and in the final minutes without falling over.
- Leaderboard updates within a few seconds of an accepted submission.
Below the line (out of scope)
- Multi-region judging. One region, with a CDN in front for static content.
- Sub-millisecond timing precision.
Back-of-the-envelope. On a normal day, 1M submissions ÷ 86,400 ≈ 12 per second, which is nothing. Contests change that. 100,000 participants × 4 problems × ~3 attempts each = 1.2M submissions in 90 minutes, ≈ 220 per second on average, with bursts of perhaps 1,000 per second when easy problems get solved early and when everyone races in the last minutes.
What does a submission cost? A typical problem has around 50 test cases; at an average of 100 ms of CPU each, plus compilation, call it 5 CPU-seconds per submission. At 1,000 submissions per second that's 5,000 CPU-seconds every second: we need about 5,000 cores judging at peak, against roughly 60 on a normal day.
The ratio between normal load and contest peak (here, close to 100×) is the scaling story of this problem. Mention that contests are scheduled in advance, so we can pre-scale the judge fleet instead of hoping autoscaling reacts fast enough.
The Set Up
Planning the Approach
We'll build problem browsing, then the submission and judging path, then contests and the leaderboard. Deep dives cover sandboxing untrusted code, fair and consistent verdicts, contest-start spikes, the real-time leaderboard, and extending the sandbox to Replit-style interactive environments.
Defining the Core Entities
- Problem: the statement, constraints, time and memory limits, and examples. Public.
- Test Case: an input file and its expected output (or a checker program, for problems with many correct answers). Hidden from users, stored in object storage.
- Submission: user, problem, language, source code, status and verdict, with per-test results (time, memory, pass/fail).
- Contest: a set of problems, a start time, a duration and scoring rules.
- Standing: a participant's score in a contest: problems solved, penalty time and attempts per problem.
API or System Interface
GET /problems?tag=&difficulty=&cursor= -> [ProblemSummary]
GET /problems/{slug} -> { statement, examples, limits }
POST /problems/{slug}/submissions { language, code, contestId? } -> 202 { submissionId }
GET /submissions/{id} -> { status: "queued" | "running" | "done", verdict, tests: [...] }
GET /submissions/{id}/events -> SSE stream of progress
POST /problems/{slug}/run { language, code, input } -> 202 { runId }
POST /contests/{id}/register
GET /contests/{id}/leaderboard?page= -> [{ rank, user, solved, penalty }]
GET /contests/{id}/leaderboard/me -> { rank, solved, penalty }
Submissions are asynchronous: POST returns immediately with an ID, and the client follows progress. Judging takes seconds, and we never want a web request thread waiting on it.
High-Level Design
1) Users should be able to browse and read problems
This is a read-heavy, rarely changing catalog. A Problem Service reads from Postgres (problems, tags, limits) and puts statements behind a cache and a CDN. A few thousand problems fit in memory many times over.
The one twist is contests. A contest's problems must not be readable before it starts. The Problem Service checks the contest start time on every request for a contest problem, and the statements are only pushed to the CDN cache at start time (or served with a short TTL and an authorization check until then).
2) Users should be able to submit code and get a verdict
The tempting first version: the API server writes the code to a file, runs gcc and the binary, compares outputs, and returns the verdict.
That's two serious problems in one. Untrusted code is now running on our API server, with its network access, its credentials and its file system. And a slow submission ties up a request thread for seconds, so a contest spike takes the whole site down. So we split submission from judging:
- The Submission Service validates the request (language supported, code under 64 KB, user not rate limited), stores the code and a
QUEUEDsubmission in the database, and publishes the submission ID to a judge queue. - Judge workers pull from the queue. For each submission, a worker fetches the code, gets the problem's test cases (cached on local disk, downloaded from S3 on a miss), compiles the code in a sandbox, and runs it once per test case under time and memory limits.
- The worker compares each output with the expected output (or runs the problem's checker), stops at the first failure for normal submissions, and writes the verdict and per-test results back.
- The client follows progress through SSE (or polls every second). The Submission Service pushes "running test 12 of 50" and the final verdict as they're written.
"Run with custom input" uses the same path with one test case (the user's input) and no expected output. It goes to a separate, lower-priority queue so playground traffic can't slow down real submissions.
Verdicts come from what the sandbox observes:
| Verdict | Meaning |
|---|---|
| Compilation Error | Compiler exited non-zero; return its output |
| Accepted | All tests passed |
| Wrong Answer | Output didn't match on some test |
| Time Limit Exceeded | CPU time over the limit (or wall time far over it) |
| Memory Limit Exceeded | Peak memory over the limit |
| Runtime Error | Non-zero exit or killed by a signal (segfault, uncaught exception) |
3) Users should be able to join contests and see a live leaderboard
A Contest Service handles registration and serves the contest's state. When a judge worker finishes a contest submission, it publishes a verdict event (to Kafka or a simple queue). A Scoring Service consumes those events and updates the participant's standing.
For an ICPC-style contest, the score is "problems solved, then lowest penalty," where penalty is the minutes from contest start to each accepted solution plus 20 minutes for each wrong attempt before it. The Scoring Service keeps standings in Postgres (the source of truth) and a Redis sorted set for ranking, which returns a page of the top N or a user's rank in O(log N).
Potential Deep Dives
1) How do we run untrusted code safely?
Every submission is code written by someone we don't know, and some of them will be actively trying to break out: read the expected outputs, open a reverse shell, mine cryptocurrency, fork-bomb the machine or exploit the kernel.
Bad Solution: Run It as a Normal Process on the Worker
Approach
The judge worker runs the compiled binary directly as a child process, with a timer to kill it.
Challenges
The submission can read anything the worker can, including test data for every problem on the local disk and any credentials in the environment. It can open network connections, spawn thousands of processes, fill the disk and use all the memory. One malicious submission compromises the whole worker, and everything the worker can reach.
Good Solution: Locked-Down Containers
Approach
Run each submission in a fresh, minimal container with the Linux isolation features turned all the way up:
- Namespaces give it its own process tree, file system view and network stack, with no network interface except loopback.
- cgroups cap CPU, memory (a hard limit, so going over triggers the memory verdict) and the number of processes (which stops fork bombs).
- A seccomp filter allows only the system calls a normal program needs, blocking things like
ptrace,mountand raw socket creation. - The container runs as an unprivileged user with a read-only root file system and a small, size-limited writable
/tmp. Only the current test's input is mounted, never the expected output. - Output size is capped, so a program printing forever can't fill the disk.
Tools built for this, like isolate (used by many programming contest judges) and nsjail, package exactly this setup.
Challenges
Every container on a host shares the host's kernel. A kernel vulnerability reachable through the allowed system calls is a path out. For a judge with a tight seccomp policy that risk is small, but it's not zero, and the consequences of an escape are severe.
Great Solution: A Hardened Sandbox Inside a Disposable VM
Approach
Add a second, independent boundary. Run the judge workers themselves inside lightweight VMs (Firecracker microVMs, or containers under gVisor, which intercepts system calls with its own user-space kernel), and keep the locked-down sandbox from the good solution inside them. Now an attacker needs a sandbox escape and a VM escape.
Make the outer layer disposable too: workers have no credentials beyond "pull from the judge queue and write results," live on an isolated network segment, and are recycled periodically (or after anything suspicious, like a sandbox crash). Test data on each worker is limited to the problems it has judged recently.
Challenges
Each layer costs some performance and complexity. gVisor adds overhead on system-call-heavy code, and microVMs need a host that supports virtualization. Since a judge mostly runs CPU-bound code with few system calls, the overhead is usually acceptable, and the security gain is large.
Interviewers like to ask "how would someone cheat?" Have three answers ready: read the expected output (never mount it), detect the test harness and print hard-coded answers (keep tests hidden and varied), and escape the sandbox (layers). A nice touch is the side channel: a submission can leak hidden inputs a bit at a time by choosing its verdict (crash if the first number is even, time out if it's odd), which is one more reason to rate-limit submissions and never show hidden inputs in results.
2) How do we make verdicts fair and consistent?
If the same O(n log n) solution passes once and gets "Time Limit Exceeded" the next time, users lose trust fast. Most of the work here is controlling noise.
- Measure CPU time, not wall time. Read the CPU time the process used from cgroups. A busy neighbor makes wall time longer but barely changes CPU time. Still enforce a generous wall-time limit (say 3× the CPU limit) to catch programs that sleep or block.
- Isolate the measurement. Pin each sandbox to a dedicated CPU core and don't run more sandboxes than cores. Disable frequency boosting, or at least use one instance type for the whole judge fleet so a time limit means the same thing everywhere.
- Run one judge per core. Running tests for one submission in parallel on many cores is tempting for latency, but it adds memory-bandwidth contention; most judges run a submission's tests sequentially on one core and parallelize across submissions.
- Language time multipliers. Python is often 10-50× slower than C++ on the same algorithm. Either set per-language time limits (calibrated by running the reference solution in each language) or accept that some problems are harder in slow languages and say so.
- Checkers. Many problems have more than one right answer (any valid path) or floating-point output. Each problem can provide a checker program that reads the input, the expected output and the contestant's output and decides. It runs in the same sandbox, because problem setters make mistakes too.
- Interactive problems. Some problems require the program to talk to a judge program (guess a number in 30 queries). The worker connects the two sandboxes' stdin and stdout with pipes and enforces limits on both.
- Rejudging. When a test case is found to be wrong, the system must be able to re-run every affected submission. That's just re-enqueueing them, with lower priority.
3) How do we handle the spike at contest start?
At the start, 100,000 people load the problems at once. A few minutes later, the first wave of submissions arrives, and the last ten minutes are another wave.
Bad Solution: Judge Synchronously, Scale on Demand
Approach
Keep the request open until judging finishes, and rely on autoscaling to add workers when CPU is high.
Challenges
Open requests pile up on the API tier and exhaust connections. Autoscaling takes minutes to add capacity, by which time thousands of users have seen timeouts. Retries from impatient users double the load.
Good Solution: Asynchronous Queue and Pre-Scaling
Approach
Use the queue from the high-level design, so a spike becomes a longer queue rather than errors. Since contests are on a calendar, scale the judge fleet up 15 minutes before each start to the size the back-of-the-envelope predicts (about 5,000 cores for our largest contests), and scale down after. Pre-warm workers with each contest problem's test data so the first submissions don't all hit S3 at once.
Challenges
Practice submissions and contest submissions share the queue, so a contest delays practice users (fine) or practice users slow the contest (not fine). A bug or a slow problem can still create a backlog that grows faster than it drains.
Great Solution: Priority Queues, Per-User Limits and Honest Backpressure
Approach
- Separate queues by priority. Contest submissions, then normal submissions, then "run code" and rejudges. Workers always drain higher-priority queues first.
- Rate-limit per user. One submission every 10 seconds per user per problem during a contest stops panic resubmits and scripts. (See rate limiter.)
- Show the queue. If the backlog grows, return "queued, position 4,210" in the progress stream. Users wait patiently when they can see progress, and don't retry.
- Static content at the edge. Problem statements go to the CDN at start time, so the 100,000 page loads in the first second are served by the CDN.
- Fair contest timing. Penalty time is measured from when the submission was accepted by the Submission Service, not when it was judged. A slow queue doesn't cost anyone points.
Challenges
Priority queues can starve low-priority work during long contests, so cap starvation (a share of workers always serves the normal queue). Pre-scaling costs money for the 15 minutes before a contest when nothing is happening yet, which is a reasonable price.
4) How do we keep the leaderboard real-time?
A contest leaderboard has two queries: "show me the top 50" and "show me my rank among 100,000." Both have to be fast while standings change several hundred times a second.
A Redis sorted set per contest does both in O(log N). We need one number that sorts correctly by "more solved, then less penalty." With penalty capped well under a million minutes, encode it as:
score = solved * 1_000_000 - penalty_minutes
ZADD contest:42 <score> <userId>
ZREVRANGE contest:42 0 49 WITHSCORES -- top 50
ZREVRANK contest:42 <userId> -- my rank (0-based)
The Scoring Service updates a participant's row in Postgres (problems solved, penalty, attempts per problem) in a transaction, then writes the new score to Redis. Verdict events are processed idempotently by submission ID, so a redelivered event doesn't add a second solve. If Redis is lost, we rebuild the sorted set from Postgres in seconds; 100,000 rows is small.
Two contest features are worth mentioning:
- Ties. Users with the same solved count and penalty share a rank. Break ties by the time of the last accepted submission if the rules require it, encoded in the lower digits of the score.
- Freezing. Many contests freeze the public leaderboard for the last hour. We keep updating standings internally but serve the leaderboard from a snapshot taken at freeze time, then reveal the final standings after the contest.
The full set of trade-offs for large leaderboards (sharding by score range, approximate ranks for millions of players) is in Design a Leaderboard. At 100,000 participants, one sorted set is plenty.
5) How would we extend this to Replit- or Codespaces-style sandboxes?
An interactive coding environment keeps the security core, but the workload is different: instead of running a 2-second program against test files, a user gets a machine that lives for hours, with a terminal, a file system, package installs and often a web server.
- One sandbox per session. Each workspace runs in its own microVM or gVisor container, from a warm pool so it starts in seconds. The judge's "no network" rule relaxes to "outbound internet through an egress proxy, nothing internal," because people need
npm install. - Persistent workspace storage. The user's files live on a volume backed by block or object storage, separate from the VM. When the session ends or goes idle, the VM is stopped and the workspace is snapshotted; the next session mounts it again, maybe on another host.
- A gateway that routes by session. The browser connects over WebSockets for the terminal, the language server and file sync. A gateway looks up which host runs this session and proxies to it. A user's web app running on port 3000 gets a public preview URL through the same gateway.
- Suspend when idle. Most sessions are idle most of the time. Suspend VMs after a few minutes without activity, and snapshot memory so resume is fast. This is what makes the economics work.
- Abuse controls. Free compute attracts crypto miners and spam bots. Cap CPU and session length on free tiers, watch for mining patterns and outbound abuse, and require verification for more resources.
The scheduling side, placing thousands of long-running sandboxes on hosts and moving them on failure, is a container orchestrator problem.
Final Design
- Problem pages come from the CDN and the Problem Service; contest problems are released at start time.
- A submission goes through the gateway (auth, per-user rate limits) to the Submission Service, which stores it and enqueues it on the contest, normal or run queue.
- Judge workers in disposable microVMs pull by priority, compile and run the code in a locked-down sandbox against cached test data, and write per-test results and the verdict.
- The client follows progress over SSE.
- Contest verdict events go to the Scoring Service, which updates standings in Postgres and the score in a Redis sorted set; the leaderboard reads from Redis.
- Before contests, the judge fleet is pre-scaled and pre-warmed with test data.
What is Expected at Each Level?
Mid-level
You should separate submission from judging with a queue and workers, explain the verdict types, and say that user code must run in an isolated environment with time and memory limits. A Redis sorted set for the leaderboard and polling for verdicts are fine answers. With prompting, you should notice the contest spike and suggest scaling workers.
Senior
You should go deep on sandboxing (namespaces, cgroups, seccomp, no network, read-only file system, process limits) and explain why containers alone share a kernel. Expect to size the judge fleet from contest numbers, propose pre-scaling and priority queues, and discuss fairness: CPU time versus wall time, dedicated cores, checkers. You should design the leaderboard score encoding and idempotent scoring.
Staff+
You should frame security as defense in depth with disposable workers and minimal credentials, and reason about cheating vectors. Expect to discuss the operational side of contests (pre-warming, starvation caps, penalty measured at submission time) and to extend the design cleanly to interactive sandboxes: persistent workspaces, session routing, idle suspension and abuse controls. Knowing when one Redis sorted set is enough is as important as knowing how to shard it.