Design an Online Judge
How to design an online judge: running untrusted code safely, queueing submissions, keeping a live leaderboard and handling the contest start.
On this page
An online judge is a site where users submit source code for a problem and receive a verdict such as Accepted, Wrong Answer or Time Limit Exceeded, which the site produces by running the code against hidden tests.
The design is hard for three reasons. The site runs programs written by strangers, so every submission has to be treated as an attack. Judging takes seconds, so it cannot happen inside the web request. And a contest starts at a known second, when tens of thousands of users arrive together. The steps below follow A Framework for Any Design.
Clarify the problem
Design an online judge for coding problems, with contests.
Users submit code in several languages and get a verdict from hidden tests. Contests have a fixed start and end and a live leaderboard. Do we need a "run" button for sample tests, discussions or plagiarism checks?
The run button on sample tests, yes. No discussions and no plagiarism checks.
What is the load on a normal day, and what is the biggest contest?
About a million submissions a day. The biggest contest has 50,000 people, 4 problems and lasts 90 minutes.
Then the contest is the design problem, because the load arrives all at once. I will require that no submission can harm the system or read other users' data, that a verdict is repeatable, and that it arrives within 10 seconds normally and 30 seconds during a contest. The leaderboard may lag a few seconds, but no accepted submission may be lost.
- Functional: users can view problems, submit code in several languages, run sample tests and receive a verdict (accepted, wrong answer, time limit, memory limit, runtime error or compile error). Contests have a live leaderboard.
- Non-functional: untrusted code is fully isolated, verdicts are deterministic, the verdict arrives within 10 seconds at p95 (30 seconds in a contest), no accepted submission is lost, the leaderboard is at most a few seconds stale, and problem pages load instantly when a contest starts.
- Out of scope: discussions, plagiarism detection and tools for writing problems.
Estimate the scale
The estimates assume that judging a submission takes about 2 seconds of CPU, which covers compiling it and running about 50 hidden tests. A day has 86,400 seconds.
- Normal day: 1 million submissions ÷ 86,400 is about 12 submissions a second. At 2 CPU-seconds each, that keeps about 24 cores busy.
- Contest: 50,000 users send about 8 submissions or runs each, which is 400,000 in 90 minutes (5,400 seconds), or about 74 a second. Submissions come in bursts, so we plan for 3 times the average, which is 220 a second.
- Problem pages: 50,000 users opening the problems within 10 seconds is 5,000 page loads a second.
- Storage: 1 million submissions a day at 2 KB of code each is 2 GB a day, or about 730 GB a year. The test data for 3,000 problems at 10 MB each is 30 GB, small enough to keep on every judge machine.
How many CPU cores must be judging at the contest peak to keep up?
- 220 submissions a second at the peak
- About 2 seconds of CPU per submission
- One submission per core at a time
Show the working
- Each second brings 220 × 2 = 440 core-seconds of work
- That needs 440 busy cores; plan about 600 for headroom
Estimate 440 (anything from 150 to 1500 is a good answer)
A normal day needs only 24 cores, so the contest needs about 18 times as many.
Write the endpoints for submitting code, getting the verdict and reading the leaderboard. Decide whether the submit call waits for the verdict.
Compare with a model answer
Submit does not wait. It returns 202 Accepted with a submission id right away, and the client polls for the verdict. The leaderboard is a paged read plus a "my rank" read.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
GET /v1/problems/{slug} static page, served by the CDN
403 Forbidden contest problem before the contest starts
POST /v1/submissions Idempotency-Key: (client-generated)
body: { "problem": "two-ferries", "language": "cpp", "code": "...", "contest": "w214"? }
202 { "submission_id": "s88123", "status": "queued" }
413 Payload Too Large code over 64 KB
429 Too Many Requests more than 1 submission per 5 s per user
GET /v1/submissions/{id} poll; the server suggests Retry-After: 1
200 { "status": "judging", "tests_done": 31, "tests_total": 50 }
200 { "status": "done", "verdict": "accepted", "time_ms": 48, "memory_kb": 9216 }
GET /v1/contests/{id}/standings?page=1 top 50 per page, cached for 5 s
GET /v1/contests/{id}/standings/me { "rank": 812, "solved": 1, "penalty": 760 }The API decision worth arguing is whether the client polls for the verdict or the server pushes it. Polling is an ordinary read that works through any proxy and is trivial to retry, and at the peak it costs only about 2,200 reads a second: 220 submissions a second, each waiting about 10 seconds, are 2,200 waiting submissions (Little's law), and each polls once a second. Pushing the verdict, for example over WebSockets (see Realtime Communication), saves those reads, but it needs about 50,000 open connections and a way to route each verdict to the right server. Polling is the simpler choice, and Retry-After lets an overloaded server slow the clients down.
Sketch the records for problems, submissions and contest standings. Decide what the source of truth for the leaderboard is.
Compare with a model answer
Problems point to versioned test files, each submission is one row, and contest results are stored per user and per problem. The submissions are the source of truth, and the leaderboard is derived from them and can be rebuilt.
Model the data
problems (problem_id PK, slug, statement_html, time_limit_ms, memory_mb,
tests_version INT) -- tests live in object storage, by version
submissions (submission_id PK, user_id, problem_id, contest_id NULL,
language, code_key, -- code in object storage, about 2 KB
status, -- queued | judging | done
verdict NULL, time_ms, memory_kb, tests_version,
created_at, judged_at)
INDEX (user_id, problem_id, created_at)
contest_results (contest_id, user_id, problem_id, PK (contest_id, user_id, problem_id)
wrong_before_accept INT, accepted_at TIMESTAMP NULL)The write volume is small: about 12 rows a second on a normal day and a few hundred in a contest. Scoring also needs a small transaction of the form "record this accept only if it is the first one". A relational database fits both needs, and it can be partitioned by user if one primary ever becomes too small. Code and tests go in object storage. Each submission records the tests_version it was judged with, which makes a verdict repeatable: a rejudge uses new tests only when someone decides it should.
Decide where a submission waits, where the code runs, and how the verdict reaches the user and the leaderboard.
Compare with a model answer
The API stores the submission and puts its id on a queue. Sandboxed judge workers take it from the queue, run it against cached tests and write the verdict, which the client polls for. When the submission is a contest accept, the worker also updates an in-memory leaderboard.
High-level design
request and replyasynchronous message
1At 10:00:00 the pre-built problem pages go live on the CDN. 50,000 users load them within about 10 seconds, and the API servers are not involved.
2Zoe submits C++ for problem A. The API saves a row with status
queued, putss88123on the queue and answers 202 within milliseconds.3A worker takes the job with a 15-second lease, which it renews every 5 seconds, and marks the row
judging.- attempt
- 2
4The worker's machine dies after 31 of 50 tests. Its lease expires after 15 seconds and the queue gives
s88123to another worker.- attempt
- 2
5The new worker runs all 50 tests in a fresh sandbox with no network, 256 MB of memory and the problem's time limit per test. Every test passes, and the slowest takes 48 ms.
- attempt
- 2
6In one transaction the worker writes the verdict, but only if the row is not already
done, and recomputes Zoe's result for problem A.7This is her first accept on problem A, so the worker sets her score on the leaderboard (1 problem solved, 760 seconds of penalty) and then acknowledges the job. Her rank is 812.
8Her next poll returns Accepted, 48 ms.
9A different submission opens a network socket and then forks processes in a loop. The sandbox has no network and caps processes at 64, so it gets a Runtime Error and the host machine is unaffected.
Deep dives
Running untrusted code
The site must assume that every submission is an attack, and each kind of attack needs its own defence. A program that loops forever is stopped by a CPU-time limit per test, plus a wall-clock limit of about twice that for programs that sleep or block. A program that allocates memory, forks or prints gigabytes of output is stopped by caps of 256 MB, 64 processes and a few MB of output, enforced by the kernel through resource controls such as Linux cgroups. A program that tries to read the expected answers finds only a read-only system image and receives only its input, because the judge compares outputs outside the sandbox. One that tries to send data out finds an empty network namespace. Attacks on the kernel are limited by a system-call filter and a non-root user. Compilation also runs inside the sandbox, because a hostile source file can make a compiler use unlimited memory or time.
The remaining question is where the sandbox boundary goes, and there are four common choices.
A plain process with limits is the simplest choice and starts in milliseconds. It shares the file system and the kernel with the judge worker, so a single forgotten rule gives the submission access to the whole machine.
A container per submission gives the program its own file system, process list and network view, together with the resource limits above, and it starts quickly. Its weakness is that all containers on a host share one kernel. A kernel vulnerability lets a submission break out of its container and reach the host and other submissions. It suits trusted users, and stronger designs use it as the inner layer.
A container inside a micro-VM gives each sandbox its own small kernel behind a hardware virtualisation boundary. A kernel exploit then only compromises a virtual machine that is deleted after the run. It costs more memory and starts more slowly, which a pool of pre-started micro-VMs hides.
A full virtual machine separates best but takes seconds to boot, which is too heavy for a two-second job.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Plain process with limits | It starts in milliseconds. | It shares the file system and kernel with the judge. | Never use it for code from strangers. |
| Container per submission | It isolates the file system, processes and network, and starts quickly. | Containers share the host kernel, so a kernel bug allows an escape. | Use it for trusted users or as the inner layer. |
| Container inside a micro-VM Usual default | Each sandbox has its own kernel behind a hardware boundary. | It needs more memory and starts more slowly. | Use it to run code from anyone on the internet. |
| Full virtual machine | It gives the strongest separation. | It is slow to boot and heavy. | Use it for long jobs or a host per tenant. |
The choice is a container inside a micro-VM from a warm pool, destroyed after one submission. Each sandbox is pinned to its own CPU core so that timings are repeatable.
The submission queue, retries and returning results
Judging stays out of the HTTP request because it is slow and may need a retry. The API writes the submission row first and then enqueues its id. If the enqueue fails, a sweeper job re-enqueues every row that is still queued after one minute, so an accepted submission is never lost.
The queue (see Message Queues and Streams) delivers each job at least once. A worker takes a job with a 15-second lease and renews it every 5 seconds while it runs. It acknowledges the job only after it has written the verdict and the score. If the worker dies, the lease expires and another worker judges the job again within 15 seconds. The lease is short because a 60-second lease would break the 30-second contest target.
Judging a submission twice is harmless because the writes are idempotent: the verdict write only succeeds if the row is not yet done, and the leaderboard counts only the first accept for each user and problem.
Contest, practice and "run on samples" requests go to separate queues, and workers take from the contest queue first, so practice traffic never delays a contest verdict. The limit of one submission per user every 5 seconds caps the worst case at 10,000 submissions a second.
The contest leaderboard
Contestants are ranked by the number of problems solved, where more is better, and then by penalty, where less is better. The penalty is the sum, over the solved problems, of the seconds between the contest start and the accept, plus 300 seconds for each wrong submission before the accept. Zoe solved problem A at 460 seconds after one wrong attempt, so her penalty is 760 seconds.
To rank with one number, the score is solved × 10,000,000 − penalty. A penalty never reaches 10 million seconds, which is about 115 days, so a contestant with more problems solved always ranks higher. The scores are kept in an in-memory sorted set, such as the one Redis provides. Updating a score and finding a rank are O(log n), the top 50 is a range read, and 50,000 entries take about 5 MB.
Submissions can finish judging out of order. A wrong answer submitted at 400 seconds can be judged after an accept submitted at 460 seconds. For this reason the verdict transaction recomputes the user's contest_results row by ordering their submissions by submit time, not by judge time. The worker then sets the score to the recomputed value instead of adding to it, so a redelivered job writes the same score again.
The load is mostly reads: about 28 accepts a second against about 1,700 standings reads a second, if 50,000 contestants refresh every 30 seconds and solve 3 of the 4 problems on average. Each standings page is rendered once every 5 seconds and served from a cache or the CDN, so only "my rank" reaches the sorted set. The leaderboard case study covers much larger scales.
Handling the load spike at contest start
The start of a contest is known in advance, so the system prepares for it instead of reacting to it. The problem pages are rendered ahead of time and published to the CDN at the start time, so the 5,000 loads a second never reach the API. The judge fleet is scaled from 24 busy cores to about 600 fifteen minutes early, with warm sandboxes and test data on every worker.
The queue absorbs whatever burst remains. If 3,000 jobs are waiting and the fleet finishes 300 a second (600 cores at 2 CPU-seconds each), the newest job waits about 10 seconds, which is within the target. Alert on the age of the oldest queued job.
Bottlenecks and failures
At 10 times the scale, a 500,000-person contest needs about 4,400 busy cores at the peak, which are reserved only for contest hours. The submissions database sees about 2,200 new rows a second plus about as many verdict updates, so it is partitioned by user.
| When this fails | What happens | What you do |
|---|---|---|
| A judge worker | Its jobs stop partway. | Leases expire and other workers rejudge; conditional writes make this harmless. |
| The queue | New submissions are saved but are not judged. | The sweeper re-enqueues queued rows. After a long outage, extend the contest. |
| The submissions DB primary | Submissions and verdict writes fail. | Fail over to a synchronous replica, and clients retry with the same idempotency key. |
| The leaderboard node | The standings stop updating. | Rebuild the sorted set from contest_results in seconds. Verdicts are not affected. |
| A sandbox escape | One micro-VM is compromised. | The micro-VM is destroyed and the host is protected. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Runs the code with a timeout and adds a queue only when asked about load. |
| Mid | Uses limited containers without network, an asynchronous queue with polling, and a sorted set. |
| Senior | Lists attacks and defences, argues for a VM boundary, makes retries safe, scales ahead of the known start, and caches the standings. |
How do you run users' code safely?
I treat every submission as an attack. Each one runs in a fresh container with no network, a read-only file system and limits on memory, processes and time. Only the input goes in, and I compare the output outside the sandbox. Containers share a kernel, so I put each container inside a micro-VM from a warm pool and throw it away after the run. An escape then lands in a VM that is about to be deleted.
Follow-up questions
A test case was wrong. How do you rejudge a contest?
You publish a new tests_version and enqueue the affected submissions on a low-priority queue, so they do not delay new submissions. Then you recompute contest_results and the leaderboard.
How do you support interactive problems?
In an interactive problem the program and the judge exchange messages while it runs. A trusted interactor process runs outside the sandbox and talks to the submission over pipes. The interactor decides the verdict.
How do you make time limits fair across languages?
A fixed limit favours fast languages. You can time reference solutions in each language on the judge hardware and set a limit per language, or multiply a base limit by a per-language factor.
How would you freeze the leaderboard for the last 15 minutes?
The system keeps updating the sorted set, but the standings pages serve a snapshot taken at the moment of the freeze, so contestants cannot see rankings change. Users still see their own verdicts. After the contest ends the live standings are shown.
What if a problem accepts more than one correct output?
Comparing output text exactly only works when there is a single correct answer. For problems with many valid answers, or with floating-point results, the problem author supplies a checker program. The checker runs outside the submission's sandbox, reads the input, the submission's output and the reference output, and returns the verdict.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".