The Problem#
An online code judge such as LeetCode, Codeforces or HackerRank shows you a programming problem, gives you an in-browser editor with a starter function in the language you choose, and lets you press Submit. A few seconds later you see a verdict: Accepted, Wrong Answer on test 17, Time Limit Exceeded, Memory Limit Exceeded, Runtime Error or Compilation Error. During a timed contest, thousands of people do this at once, and a live leaderboard ranks them by how many problems they solved and how quickly.
On the surface this looks like a simple CRUD site with a "run this code" button. The button is the whole problem. When a user presses Submit, you are agreeing to run arbitrary code, written by a stranger on the internet, on your own machines. That code might be a correct solution. It might also be an infinite loop, a fork bomb, a program that allocates 64 GB of memory, a script that tries to read your cloud credentials from the instance metadata endpoint, a crypto-miner, or a carefully crafted kernel exploit. The judge must run it fast, measure its time and memory fairly, compare its output against hidden test cases, and do all of that without the code ever being able to harm the host, other users' submissions, or the rest of your infrastructure.
Then there is the traffic shape. On a normal day submissions trickle in at a steady rate. At the start of a weekly contest, tens of thousands of people open the same problems in the same minute, and in the last ten minutes everyone hammers Submit at once. Each submission is not a cheap database write: it is seconds of CPU time across dozens or hundreds of test cases. The system has to absorb a 10x to 50x burst in compute demand on a schedule you know in advance, while keeping feedback fast enough that contestants do not feel cheated.
Analogy. Think of a driving test centre. Candidates (submissions) arrive and queue at the front desk (the API). Each candidate gets a closed test track (the sandbox): a fenced course with no exits onto public roads (no network), a fixed fuel allowance (CPU and memory limits), and an examiner with a stopwatch who ends the test the moment time runs out (the timeout). The examiner follows a fixed checklist of manoeuvres (the test cases) and writes a pass or fail on a card (the verdict), which the candidate collects from the front desk (result delivery). On exam day, when a hundred candidates show up at once, you open more tracks in advance (pre-scaling) and keep the waiting room orderly (the queue) instead of letting everyone drive onto the same track. And no matter how badly a candidate drives, they can never crash into the building, because the track is fenced.
What makes this a good interview problem is that it sits at the intersection of three areas:
- Security engineering. Isolation layers (containers, seccomp, gVisor, micro-VMs), defence in depth, and the threat model of hostile code.
- Asynchronous processing. A job queue that decouples the web tier from a fleet of execution workers, with retries, idempotency and result delivery back to a browser that is waiting.
- Real-time ranking under bursts. A leaderboard that updates within seconds for 100,000 contestants, and capacity planning for a spike you can see coming.
The scale is modest compared with a social network, which is itself a lesson. A design that is perfectly sized for the problem (a few services, one database, a cache and a worker fleet) beats one that reaches for global sharding to impress the interviewer. Staff-level answers here are judged on getting the isolation model and the burst plan right, not on the number of boxes.
Clarifying Questions#
Before drawing anything, pin down the scope. The answers below are the assumptions this design uses.
| Question | Why it matters | Assumed answer |
|---|---|---|
| Which languages must we support? | Each language needs a runtime image, a compile step (for C++, Java, Rust, Go) and a test harness. | About 10 to 20 mainstream languages: Python, Java, C++, JavaScript, Go, Rust, C#, Kotlin and so on. |
| Is "Run" (custom input, sample tests) different from "Submit" (all hidden tests)? | Runs are cheaper but far more frequent; they can be prioritised differently. | Yes. Run executes on sample or user-provided input; Submit runs the full hidden test suite and is recorded. |
| How fast must feedback be? | Drives worker capacity and whether the request can be synchronous. | Verdict within about 5 seconds for a typical submission, outside extreme bursts. |
| Are there contests? How large? | Contests create the burst and need a live leaderboard. | Yes. Weekly contests of about 90 minutes with up to 100,000 participants. |
| How is a contest scored? | Determines the leaderboard data structure and tie-breaking. | Rank by number of problems solved; ties broken by the earliest time the last accepted solution arrived (plus any penalty rules). |
| How fresh must the leaderboard be? | Real-time push versus periodic refresh. | Within a few seconds is fine. Nobody needs millisecond updates. |
| Do we need to show progress per test case? | Affects result-delivery design (streaming versus a single final result). | Nice to have. A final verdict with the first failing test is required. |
| Is consistency or availability more important? | Shapes database and replication choices. | Availability. Showing a leaderboard that is a few seconds stale is fine; refusing submissions during a contest is not. |
| Do we handle auth, profiles, payments, discussion forums? | Keeps scope manageable. | Out of scope. Assume an existing auth service hands us a verified user identity. |
| What is the scale outside contests? | Sizing of the steady-state fleet. | A few hundred thousand daily active users and a catalogue of roughly 4,000 problems. |
Two answers deserve emphasis. First, availability over consistency: during a contest, a delayed leaderboard is a minor annoyance, but a rejected submission is a fairness incident that gets posted on social media within minutes. Second, the scale is small in data and large in compute. Almost everything about storage fits on one machine; the hard part is CPU for execution during bursts.
Requirements#
Functional Requirements#
- Browse problems. Users can list problems with filters (difficulty, tags) and pagination, and open a problem to see its statement, examples and constraints.
- Code in multiple languages. Opening a problem in a chosen language shows a starter code stub, for example the empty
def maxDepth(self, root)signature in Python, or the equivalent class and method in Java. - Run and submit. Users can run their code against sample or custom input, and submit it against the full hidden test suite. They get a verdict with runtime, memory and, on failure, details of the first failing test (unless it is hidden in a contest).
- Submission history. Users can see their past submissions and verdicts for a problem.
- Contests. Users can register for and take part in timed contests with a fixed set of problems.
- Live leaderboard. During a contest, users can see the top of the leaderboard and their own rank, updated within a few seconds.
Out of scope: authentication and accounts, user profiles, payments and premium plans, analytics dashboards, discussion forums and social features, editorial content authoring workflows. We will touch on plagiarism detection only as an extension.
Non-Functional Requirements#
- Security and isolation (the top priority). User code must never be able to read other users' code or data, reach the network, affect the host, consume unbounded resources, or interfere with other submissions running on the same machine.
- Low latency feedback. A typical submission should get a verdict within about 5 seconds end to end. Runs should be faster, ideally 1 to 2 seconds.
- Fair, repeatable measurement. The same code should get the same verdict and roughly the same reported runtime every time. Noisy neighbours must not push a correct solution over the time limit.
- High availability, especially during contests. Submissions must be accepted even when the execution fleet is saturated (they may queue), and a single worker crashing must not lose a submission.
- Burst handling. Support contests with 100,000 participants, which produce compute spikes of 10x or more over steady state, on a known schedule.
- Leaderboard freshness. The leaderboard reflects new accepted submissions within a few seconds (we will target 5 seconds or less).
- Durability. Accepted submissions and contest results are never lost; they are the record that decides contest rankings and ratings.
A useful way to rank these in an interview: isolation is non-negotiable, burst handling is the scaling story, and latency plus leaderboard freshness are the user-experience story. Everything else is standard web engineering.
Capacity Estimation#
The point of this section is to find out which resource is scarce. For a code judge the answer comes out clearly: storage and request rates are small, and execution CPU during contests is the dominant cost. See Back-of-the-Envelope Estimation for the method.
Steady-state traffic#
- Daily active users: assume 500,000.
- Executions per active user per day: about 10 (a mix of Runs and Submits; people iterate).
- Executions per day: 500,000 × 10 = 5 million.
- Average rate: 5,000,000 / 86,400 s ≈ 58 executions per second.
- Daily peak: traffic follows time zones and work hours, so assume a 3x peak, roughly 175 per second.
Page views are larger in count but trivial in cost. If each active user views 20 problem pages a day, that is 10 million page views, or about 115 per second on average. Problem statements change rarely, so nearly all of these come from a CDN or an in-memory cache.
Cost of one execution#
This is the number that drives the whole design. A submission runs against every hidden test case for that problem.
- Test cases per problem: typically 20 to 200. Assume 100 as a planning number.
- Time per test: most tests finish in a few milliseconds; the largest stress tests run close to the time limit. Planning with 100 ms of CPU per test is deliberately pessimistic and includes per-test harness overhead.
- CPU per submission: 100 tests × 100 ms = 10 CPU-seconds in the pessimistic case.
- Compile step: C++ with optimisations takes 1 to 3 seconds of CPU; Java about 1 second; interpreted languages need none. Assume an average of 1 CPU-second.
A Run is much cheaper: it executes 1 to 3 sample tests, so about 0.3 to 1 CPU-second including startup.
Steady-state compute, assuming half of executions are Submits:
- Submits: 87 per second at peak × 11 CPU-s ≈ 960 CPU-s per second.
- Runs: 87 per second × 1 CPU-s ≈ 87 CPU-s per second.
- Total: about 1,050 busy cores at the daily peak, pessimistically. With realistic test runtimes (most tests take far less than 100 ms) the real figure is likely a third of that. Call it a few hundred cores in steady state.
Contest burst#
Use the contest definition from the clarifying questions: 100,000 participants, 90 minutes.
- If each participant makes 20 executions over the contest (Runs plus Submits), that is 2 million executions in 5,400 seconds, an average of about 370 per second.
- Traffic is not uniform. The first 10 minutes bring a wave of Runs on the easy problem, and the final 10 minutes bring a wave of Submits on the hard problems. Assume the peak minute brings 10,000 Submits (one in ten participants submitting within the same minute).
Now the key calculation:
10,000 submissions × 100 tests × 100 ms = 100,000 CPU-seconds of work
To finish that work within 60 seconds: 100,000 / 60 ≈ 1,667 cores
With 16-vCPU workers: 1,667 / 16 ≈ 105 machines
To keep each verdict under ~5 s, the queue must not build up,
so we need the full ~1,700 cores running before the spike, not after it.That is roughly 2x to 5x the steady-state fleet. If we also count the Runs happening in the same minute, a 3x to 10x multiple over the quiet-hour baseline is realistic. The fact that the spike arrives on a published schedule is the most important property in the whole design: it means we can pre-scale instead of hoping autoscaling reacts in time.
Storage#
| Data | Estimate | Total |
|---|---|---|
| Problem statements and metadata | 4,000 problems × ~10 KB | ~40 MB |
| Code stubs | 4,000 × 15 languages × ~1 KB | ~60 MB |
| Hidden test cases | 4,000 × avg ~1 MB (some stress tests are 10 to 50 MB) | ~4 to 10 GB |
| Submissions (code plus metadata) | 5 M per day × ~3 KB | ~15 GB per day, ~5.5 TB per year |
| Per-test results (optional) | 2.5 M Submits × 100 tests × ~20 bytes | ~5 GB per day if stored in full |
| Contest leaderboard in Redis | 100,000 members × ~60 bytes | ~6 MB per contest |
Problem data and test cases are small enough to replicate to every worker's local disk. Submission history grows steadily but is easy to store in a sharded table or a document store, and older submissions can move to cheaper storage (see Data Lifecycle, Tiering and Retention). The leaderboard is tiny; it fits in a single Redis instance many times over.
Read traffic during a contest#
- Leaderboard polling: 100,000 participants refreshing every 5 seconds is 20,000 requests per second. That is the largest read rate in the system, and it has to come from a cache, not from a database query.
- Result polling: if 10,000 submissions are in flight and each client polls once per second, that is up to 10,000 requests per second of tiny key lookups, again served from a cache or a fast key-value store.
| Resource | Steady state | Contest peak | Scarce? |
|---|---|---|---|
| Execution CPU | a few hundred cores | ~1,700 cores (pessimistic) | Yes, dominant cost |
| API requests | ~300 per second | ~30,000 per second (mostly polling) | Moderate; cacheable |
| Database writes | ~60 per second | ~400 per second | No |
| Storage | ~15 GB per day | same | No |
| Leaderboard memory | none | ~6 MB | No |
The conclusion shapes everything that follows: design the execution fleet and its queue carefully, cache the read paths, and keep the data layer boring.
Core Entities#
Start with the nouns. Five entities carry the whole design; the first three are the ones every interviewer expects.
- Problem. A programming task: title, statement (Markdown), difficulty, tags, time and memory limits, starter code stubs per language, and a set of test cases. Test cases are large and private, so they are stored separately (object storage), and the problem record only points at them.
- Submission. One attempt by a user to solve a problem: the user, problem, language, source code, status (queued, running, done), verdict, runtime, memory, the first failing test, and timestamps. A Run is a lightweight submission that is not recorded on the leaderboard.
- Leaderboard. The ranking of users within a contest. It is not really a stored entity; it is a derived view computed from accepted submissions, which is why it can live in a cache and be rebuilt at any time.
- Contest (Competition). A timed event: start time, end time, the list of problems, scoring rules and registered users.
- TestCase. An input and expected output pair (or an input plus a checker program for problems with many correct answers). Belongs to a problem and has a version so that rejudging is reproducible.
A useful observation for the interview: Problem is read-heavy and nearly static, Submission is write-heavy and append-only, and Leaderboard is derived. Each of those three access patterns gets its own storage choice later.
API Design#
The API is small. Every functional requirement maps to one endpoint. All endpoints sit behind an API Gateway and Backend-for-Frontend that authenticates the request and attaches the verified user identity.
Browse problems#
GET /problems?page=1&limit=100&difficulty=medium&tag=graphs
-> 200 { problems: [ { id, title, difficulty, tags, acceptanceRate } ], nextPage }The list endpoint returns only the fields a list view needs. Shipping full statements, stubs and test-case pointers for 100 problems would make the response 100x larger for no benefit. Pagination can be offset-based here because the catalogue is small and stable; cursor pagination is better for submission history, which grows constantly (see API Design Best Practices).
View one problem#
GET /problems/:id?language=python
-> 200 { id, title, statement, examples, constraints,
timeLimitMs, memoryLimitMb, codeStub }The language parameter selects which starter stub to return. If omitted, return the user's last-used language. Hidden test cases are never returned; only the examples in the statement are public.
Run and submit#
POST /problems/:id/run
body: { language, code, customInput? }
-> 202 { runId }
POST /problems/:id/submit
body: { language, code, contestId? }
headers: Idempotency-Key: <uuid generated by the client>
-> 202 { submissionId }Three design points:
- Return 202 Accepted, not the verdict. Execution takes seconds and, during a burst, may sit in a queue. Holding an HTTP request open for that long ties up a connection per submission and breaks badly when the client's network blips. The server accepts the job, stores it, and returns an id immediately. This is the Pattern: Managing Long-Running Tasks in its simplest form.
- Never trust identity or time from the client. The user id comes from the authenticated session, never from the request body. The submission timestamp is set by the server when the request is accepted. If the client could send
submittedAt, a contestant could backdate their submission and jump the leaderboard. - Idempotency key. A double-click or a retry after a timeout must not create two submissions. The server stores the key with the submission id and returns the same id for a repeat. See Idempotency and Safe Retries.
Check a result#
GET /submissions/:id (often called GET /check/:id)
-> 200 { status: "queued" | "running" | "done",
verdict?, runtimeMs?, memoryKb?, testsPassed?, testsTotal?,
failingTest? }The client polls this endpoint, starting at about once per second, until the status is done. We will compare polling with push in the result-delivery deep dive; polling is the right default here and is what many real judges do.
Leaderboard#
GET /contests/:id/leaderboard?page=1&limit=50
-> 200 { entries: [ { rank, userId, displayName, solved, penaltyTime } ],
me: { rank, solved, penaltyTime }, updatedAt }The response includes the caller's own rank, which is what most contestants actually look at. updatedAt lets the client display "updated 3 s ago" and back off polling when nothing changes.
Submission history#
GET /problems/:id/submissions?cursor=...&limit=20
-> 200 { submissions: [ { id, language, verdict, runtimeMs, createdAt } ], nextCursor }Summary of the API#
| Endpoint | Purpose | Notes |
|---|---|---|
GET /problems | List problems | Partial fields, cacheable |
GET /problems/:id | Statement and stub | Cache per problem and language |
POST /problems/:id/run | Run on sample or custom input | Not recorded, lower priority |
POST /problems/:id/submit | Submit for judging | 202 plus id, idempotent |
GET /submissions/:id | Poll for verdict | Tiny, hot, cache-backed |
GET /contests/:id/leaderboard | Contest ranking | Served from Redis |
GET /problems/:id/submissions | History | Cursor paginated |
High-Level Design#
Build the design one functional requirement at a time, starting from the simplest thing that works and adding components only when a requirement forces them.
1. Browsing and viewing problems#
The read path is a classic cache-fronted service. A Problem Service reads from a Problem Store and returns lists and single problems. Because problems change only when an editor publishes a new version, the responses can be cached aggressively: the CDN caches the public statement, and an in-memory cache inside or beside the service holds the hot problems.
What database for problems? A problem is naturally a document: a statement, a map of language to code stub, a list of examples, limits and a pointer to the test-case bundle. The access pattern is "fetch the whole thing by id" and "list by a few fields". A document store (MongoDB, DynamoDB) fits that shape well, and so does a relational table with a JSON column for the stubs (PostgreSQL's jsonb). At 4,000 rows, either works; pick what the team already runs. See SQL vs NoSQL: How to Choose.
{
"id": "maximum-depth-of-binary-tree",
"title": "Maximum Depth of Binary Tree",
"difficulty": "easy",
"tags": ["tree", "dfs", "bfs"],
"timeLimitMs": 2000,
"memoryLimitMb": 256,
"statement": "Given the root of a binary tree, return its maximum depth...",
"codeStubs": {
"python": "class Solution:\n def maxDepth(self, root: Optional[TreeNode]) -> int:\n ",
"java": "class Solution {\n public int maxDepth(TreeNode root) {\n \n }\n}"
},
"testBundle": { "uri": "s3://judge-tests/max-depth/v7.tar.zst", "version": 7, "sha256": "..." }
}The editor in the browser is a component like Monaco (the editor that powers VS Code) or CodeMirror. It handles syntax highlighting, autocompletion and keybindings entirely on the client; the server only ever sees the final code string.
Code stubs for 15 languages per problem are tedious to write by hand. They can be generated from a language-neutral function signature (name, parameter types, return type), either with a small template generator per language or with a language model followed by human review. The generator is an authoring tool, not a runtime component.
2. Running and submitting code#
The naive design runs the user's code inside the API server process: receive the code, write it to a file, invoke the compiler or interpreter, capture stdout, compare with expected output. This is how a toy judge starts, and it fails on every non-functional requirement at once. A single while True: pass pins a CPU core of the API server; a fork() loop takes the whole machine down; open("/etc/passwd") or a request to the cloud metadata endpoint leaks secrets. Even ignoring security, a 10-CPU-second submission blocks an API worker that should be answering in milliseconds.
The fix has two parts. First, separate execution from the API into a fleet of dedicated Execution Workers. Second, run each submission inside a sandbox on those workers: a container (or a micro-VM) with no network, a read-only root filesystem, strict CPU, memory and process limits, and a hard timeout. Deep Dive 1 compares the options; the short answer is containers per language runtime, hardened with seccomp and optionally a user-space kernel like gVisor, or Firecracker micro-VMs when you need VM-grade isolation.
A first version can have the Submission Service call a worker directly over RPC and wait. That works at low volume but couples the API's availability to the workers' capacity: when every worker is busy, new submissions fail.
3. Decoupling with a queue and delivering results#
To survive bursts, put a Submission Queue between the Submission Service and the workers. The service writes the submission row with status queued, enqueues a small job message (submission id, problem id, language, priority), and returns 202 immediately. Workers pull jobs at their own pace, run them, and write the verdict back to the Submission DB. The client polls GET /submissions/:id until it sees done.
This buys three things:
- Absorbing bursts. When submissions arrive faster than workers can process them, the queue grows instead of requests failing. Users see "Pending" for a few extra seconds rather than an error.
- Retries for free. If a worker crashes mid-execution, the job's lease (visibility timeout) expires and another worker picks it up. No submission is lost.
- Independent scaling. The autoscaler watches queue depth and adds workers; the API tier is sized only for request rates.
The queue can be Amazon SQS, RabbitMQ, a Redis stream or Kafka. Deep Dive 5 discusses the trade-offs; SQS-style per-message leasing fits this workload better than Kafka's partitioned log, because each job is independent and long-running.
4. The contest leaderboard#
Contest scoring is "problems solved, ties broken by time". The obvious implementation is a SQL query over the submissions table each time someone loads the leaderboard:
SELECT user_id,
COUNT(DISTINCT problem_id) AS solved,
MAX(first_ac_at) - :contest_start AS finish_time
FROM (
SELECT user_id, problem_id, MIN(created_at) AS first_ac_at
FROM submissions
WHERE contest_id = :cid AND verdict = 'ACCEPTED'
GROUP BY user_id, problem_id
) per_problem
GROUP BY user_id
ORDER BY solved DESC, finish_time ASC
LIMIT 50;That query is correct and is a fine source of truth, but running it 20,000 times per second while 100,000 users poll is not. Instead, maintain the ranking incrementally: when a worker writes an ACCEPTED verdict for a contest submission, a Leaderboard Updater checks whether this is the user's first accept for that problem and, if so, updates a Redis sorted set keyed by contest. Reads become ZRANGE ... REV WITHSCORES for the top N and ZREVRANK for the caller's own rank, both logarithmic and sub-millisecond. Deep Dive 7 covers the score encoding that turns "solved, then time" into a single sortable number.
The full high-level design#
Putting it together, the system has a read path for problems, a write-then-queue path for submissions, an isolated execution fleet, and a cache-backed leaderboard.
Components:
- CDN. Serves the static web app and caches public problem statements at the edge. See Content Delivery Networks (CDN).
- API Gateway. Terminates TLS, authenticates the user, applies per-user rate limits on Run and Submit, and routes to services.
- Problem Service. Lists and serves problems and stubs from the Problem Store, with an in-memory cache in front. Nearly read-only.
- Submission Service. Validates input (code size, supported language, contest still open), stamps the server time, writes the submission row, enqueues the job and answers polls.
- Submission DB. Durable record of every submission and verdict. Sharded by user or by submission id if it ever outgrows one primary.
- Submission Queue. Buffers jobs between the API and the fleet. Separate queues or priorities for contest Submits, practice Submits and Runs.
- Execution Workers. Machines in a locked-down network segment that lease jobs, fetch the code and cached test cases, run each test in a sandbox, compare outputs and record the verdict.
- Sandboxes. One isolated environment per execution: a hardened container per language runtime, or a micro-VM. No network, read-only filesystem, cgroup limits, seccomp, timeout.
- Test-case object storage. The canonical, versioned test bundles, pulled and cached on each worker's local disk. See Object Storage and Blob Storage.
- Leaderboard Updater. Consumes accepted-verdict events, dedupes repeat accepts and maintains the contest sorted sets.
- Redis. Holds live leaderboards, recent submission statuses for cheap polling and other hot caches. See Redis in Practice.
- Autoscaler and contest pre-scaler. Scales workers on queue depth and age, and raises the fleet's floor before scheduled contests.
At the scale assumed, the four services can be one deployable application with modules, plus the separate worker fleet. Splitting into microservices is justified only for the execution fleet, which has a completely different security boundary, hardware profile and scaling curve. See Monolith vs Microservices.
Key Flows#
Flow 1: Submitting code and getting a verdict#
This is the main flow. Follow one submission from the button press to the green "Accepted".
Step by step:
- Accept. The Submission Service authenticates the user, rejects code larger than a limit (64 KB is generous), checks that the language is supported and, for contest submissions, that the contest is running and the user is registered. It stamps
createdAtwith the server clock. - Persist before enqueue. The row is written first with status
queued. If the enqueue then fails, a sweeper can findqueuedrows older than a minute with no job and re-enqueue them. Writing the job first and the row second risks a worker finishing a job for a row that does not exist yet. A transactional outbox (row plus outbox entry in one transaction, relayed to the queue) makes this airtight; see Distributed Transactions: 2PC, Sagas and Outbox. - Return 202. The client gets an id within tens of milliseconds and starts polling.
- Lease and execute. A worker takes the job with a lease (say 60 seconds). It marks the row
running, compiles the code once if the language needs it, then runs the test cases one by one in the sandbox, stopping at the first failure. - Write the verdict, then acknowledge. The worker writes the verdict before deleting the job. If it crashes between the two, the job reappears and a second worker re-runs it; the verdict write is idempotent because it is keyed by submission id and guarded by "only if status is not already done" (or by the job's attempt number).
- Client sees done. The next poll returns the final result.
Flow 2: Inside the worker, one test at a time#
The worker is where most of the interesting logic lives.
Key details:
- Compile once, run many. Compilation happens once per submission, inside the sandbox, with its own limits (compilers can be attacked too, for example with template-instantiation bombs in C++ that eat gigabytes of memory).
- Fail fast. Stop at the first failing test. This saves CPU on wrong submissions, which are the majority, and the user only needs to see the first failure.
- Per-test isolation choices. The cheapest approach runs all tests in one long-lived process using a harness that loops over inputs. The most robust approach starts a fresh process per test so that global state cannot leak between tests. Most judges run a fresh process per test inside the same sandbox, which costs a few milliseconds per test for native languages and more for the JVM. Deep Dive 4 explores this.
- Clean up. After the submission, the sandbox's writable scratch directory is wiped (or the whole container or VM is discarded) before reuse.
Flow 3: A contest accept updates the leaderboard#
Only the first accepted submission per user per problem counts. Re-submitting a solved problem (people do this to improve their runtime) must not change the score. The updater keeps a small per-user set of solved problems in Redis (SADD returns 1 only when the member is new), and only then recomputes and writes the user's score. Because the event may be delivered twice, this check also makes the updater idempotent.
Flow 4: Contest pre-scaling#
The contest scheduler knows exactly when a contest starts and how many people registered. Thirty minutes before start, it raises the fleet's minimum size, workers boot, pull the contest's test bundles (which are hidden until the start and must never be exposed through any public path) and warm sandbox pools. When the contest begins, the capacity is already there.
Submission lifecycle#
Failed here means System Error, not a user mistake. It is distinct from a Runtime Error verdict. A user should never be penalised for a system error, and contest rules usually say that system errors are rejudged automatically.
Data Model#
Three stores, each matched to its access pattern:
- Problem Store (document DB or a relational table with JSON columns): small, read-mostly, fetched by id.
- Submission DB (relational, e.g. PostgreSQL, or a key-value store like DynamoDB): append-heavy, queried by user and problem, by contest, and by id for polling.
- Redis: derived, rebuildable state: leaderboards, solved sets and hot submission statuses.
Test-case bundles live in object storage and are referenced by version from the problem record.
The first diagram covers problems and submissions; the second covers contests.
| Table or key | Store | Key and indexes | Notes |
|---|---|---|---|
problems | Document DB or PostgreSQL | PK id; index on difficulty, tags | ~4,000 rows; cached in memory and at the CDN |
test_bundles | PostgreSQL plus object storage | PK (problem_id, version) | Immutable bundles; new version on any change |
submissions | PostgreSQL or DynamoDB | PK id; index (user_id, problem_id, created_at); index (contest_id, user_id) | Append-heavy; shard by user_id if ever needed |
test_results | Same as submissions, or skip | PK (submission_id, test_index) | Optional; often only the first failing test is stored |
contests, contest_problems, registrations | PostgreSQL | As shown | Small |
lb:{contestId} | Redis sorted set | member userId, score composite | Rebuildable from submissions |
solved:{contestId}:{userId} | Redis set | members problemId | Dedupes first accepts |
sub:{id} | Redis hash, TTL 10 min | status, verdict | Makes polling cheap |
Design notes:
- Code is stored by reference for large payloads. Most submissions are a few KB and fit in the row. If you allow larger files, store the code in object storage and keep
code_ref. Either way, the code is immutable once submitted. - Each submission records the test version it was judged against. When a problem setter fixes a broken test, you can find and rejudge exactly the submissions judged against the old version.
- DynamoDB variant. If you choose DynamoDB, the main table is keyed by
submissionId, with a global secondary index on (userId,problemId#createdAt) for history and another on (competitionId,userId) to rebuild leaderboards. GSIs are eventually consistent, which is acceptable for history and leaderboard rebuilds. - The leaderboard is never the source of truth. If Redis is lost, the SQL query from the high-level design rebuilds every contest's ranking from the submissions table in seconds.
For the general decision process, see Choosing a Database: A Decision Guide.
Deep Dives#
1. Where should untrusted code run?#
This is the question the interviewer cares most about. Every option is a trade-off between isolation strength, startup time, per-execution overhead and operational complexity.
Bad: run it in the API server. The API process writes the code to a temp file and shells out to python3 solution.py. It is the fastest to build and the worst on every axis that matters:
- Security. The code runs with the API server's permissions: it can read environment variables (database passwords, cloud credentials), the filesystem, other users' submissions, and the network, including the cloud metadata endpoint that hands out instance credentials.
- Performance isolation. An infinite loop or a 10 GB allocation degrades or crashes the API server for everyone.
- Scaling. API servers are sized for millisecond requests; one CPU-heavy submission blocks a worker thread for seconds.
Good: a virtual machine per submission. A full VM gives hardware-enforced isolation: the guest has its own kernel, so a kernel exploit inside the guest compromises only the guest. That is strong. But a conventional cloud VM takes tens of seconds to a minute to boot, needs hundreds of MB to GB of memory for its OS, and is billed with a minimum period. Booting a VM to run 50 ms of user code wastes almost all of the time and money. You can keep VMs running and reuse them across submissions, but then a submission could leave behind state (files, processes) that affects or spies on the next one, which undoes much of the benefit unless you reset the VM between uses.
Great: containers per language runtime, reused and hardened. A container is a normal Linux process with a restricted view of the system, built from two kernel features:
- Namespaces give the process its own view of process ids (
pid), mounts (mnt), network interfaces (net), users (user), hostname (uts) and IPC. Inside a fresh network namespace there is no interface except loopback, so there is literally no route to the internet. - Control groups (cgroups) cap and account resources: CPU time (
cpu.max), memory (memory.max), number of processes (pids.max) and I/O.
A container starts in tens to hundreds of milliseconds (most of it is the runtime setting up namespaces and mounts), and a pre-started "warm" container starts a new process in single-digit milliseconds. The worker keeps one or more warm containers per language image (Python, Java, C++ toolchains) and uses the container runtime's API, the equivalent of docker exec, to run each submission synchronously, reading the result from stdout or from a file in a mounted output directory. Between submissions, the scratch directory is wiped; for stronger hygiene, the container is discarded after each submission and replaced from the warm pool.
The weakness of containers is the shared host kernel. Every container on the machine talks to the same Linux kernel through system calls, so a kernel vulnerability reachable from inside the container can become a host compromise. That is why containers for hostile code must be hardened (Deep Dive 2) and, for higher assurance, combined with a user-space kernel or a micro-VM.
Great alternative: serverless functions. Package each language runtime as a function (for example on AWS Lambda) and invoke it per submission. The provider handles isolation (Lambda runs functions inside Firecracker micro-VMs), scaling and patching. The trade-offs:
- Cold starts. A function that has not run recently takes hundreds of ms to a few seconds to start, longer for JVM runtimes. Contest bursts hit exactly this.
- Limits. Concurrency quotas per account and region (AWS's default is 1,000 concurrent executions per region, raisable on request), payload sizes, memory and CPU tied together, and limited control over the kernel and syscalls.
- Measurement noise. You do not control the hardware or co-tenants, so runtime measurements vary more, which hurts fairness.
- Cost at steady load. Per-invocation pricing is attractive when idle and expensive under constant heavy use.
Serverless is a strong choice for a small team or a product where code execution is a side feature. A dedicated judge with predictable heavy load usually ends up running its own fleet.
Best when isolation must be VM-grade: micro-VMs. A micro-VM is a virtual machine with almost everything removed. Firecracker, open-sourced by AWS in 2018 and described in "Firecracker: Lightweight Virtualization for Serverless Applications" (Agache et al., NSDI 2020), emulates only a handful of devices (virtio network and block, a serial console, vsock for host communication, and a minimal keyboard controller used only to stop the VM) and boots a minimal Linux guest in roughly 125 ms with a memory overhead of a few MB per VM. It gives each submission its own guest kernel, behind the hardware virtualisation boundary, at close to container speed. Firecracker powers AWS Lambda and Fargate. Kata Containers offers a similar model behind a standard container interface, so Kubernetes can schedule micro-VMs like pods. The cost is operational: micro-VMs need KVM, which means bare-metal instances or cloud instances that support nested virtualisation, plus more tooling to build guest images and manage networking.
| Option | Isolation boundary | Startup | Overhead per execution | Ops complexity | Fit |
|---|---|---|---|---|---|
| API server process | None | ~0 | None | Trivial | Never |
| Full VM per submission | Hardware, separate kernel | 20 to 60 s | Hundreds of MB | Medium | Too slow |
| Hardened container, warm pool | Namespaces, cgroups, seccomp; shared kernel | ~5 ms warm, 100 to 500 ms cold | A few MB | Medium | Default choice |
| Container plus gVisor | Plus a user-space kernel | Similar to containers | Extra cost on syscall-heavy code | Medium | High-risk tenants |
| Firecracker micro-VM | Hardware, separate guest kernel | ~125 ms boot, faster from snapshot | A few MB | High | VM-grade isolation at scale |
| Serverless function | Provider managed (micro-VM on Lambda) | Cold start 0.2 to several s | Provider pricing | Low | Small teams, spiky load |
What to say in the interview. "I'll run each submission in a container from a per-language image, on a dedicated worker fleet in an isolated network. The containers are hardened: no network, read-only root, cgroup limits, seccomp allowlist, non-root user and a timeout. If we need stronger isolation, for example because we also run arbitrary user packages, I'd swap the runtime for gVisor or Firecracker without changing the rest of the design."
2. Hardening the sandbox: defence in depth#
No single layer is trusted. Each layer assumes the one inside it has been broken. The layers, from the code outwards:
Layer 1: what the program can see. The submission runs as an unprivileged user (for example uid 65534, "nobody"), inside a user namespace so that even "root" inside the container maps to an unprivileged uid on the host. All Linux capabilities are dropped (no CAP_SYS_ADMIN, no CAP_NET_RAW, and so on), and the no_new_privs flag stops set-uid binaries from regaining privileges.
Layer 2: the filesystem. The root filesystem is read-only. The only writable places are a small tmpfs scratch directory (in memory, capped at, say, 64 MB) and, if used, an output directory. The test inputs are fed through stdin or a read-only mount containing only the current test. The expected outputs are never inside the sandbox: the worker compares output outside. Otherwise, a submission could simply read the expected answer file and print it.
Layer 3: resources. cgroups v2 enforce:
memory.max(the memory limit, with swap disabled so memory cannot spill to disk),pids.max(stops fork bombs, for example 64 processes),cpu.max(CPU quota, for example one core),- plus classic
setrlimitlimits: file size (RLIMIT_FSIZE), open files (RLIMIT_NOFILE), stack size.
A wall-clock timer in the worker kills the entire cgroup if the program runs past its limit, which catches programs that sleep or block rather than burn CPU.
Layer 4: system calls. A seccomp-bpf filter (merged in Linux 3.5, 2012) is a small BPF program the kernel runs on every system call; it allows, denies or kills based on the syscall number and arguments. Docker's default profile already blocks a few dozen dangerous calls such as mount, reboot, kexec_load and most namespace manipulation. A judge can go much further, because a solution needs very little: read, write, memory mapping, exit, a few time and signal calls, and for some runtimes threads. Blocking socket, ptrace, bpf, keyctl, userfaultfd and io_uring removes large parts of the kernel's attack surface, and many historical container escapes went through exactly those subsystems.
Layer 5: the kernel boundary. For stronger isolation, add a layer between the program and the host kernel:
- gVisor (Google, open-sourced in 2018) runs a user-space kernel called the Sentry, written in Go, which implements the Linux system-call interface itself. The sandboxed program's syscalls are intercepted and handled by the Sentry, which in turn uses only a small, filtered set of host syscalls. A kernel bug that a user program could reach is now usually a Sentry bug, inside a process that is itself sandboxed. The cost is extra overhead on syscall-heavy and I/O-heavy workloads; CPU-bound algorithmic code, which is most of what a judge runs, is affected much less.
- Micro-VMs (Firecracker, Kata) put a hardware virtualisation boundary in the way: the guest has its own kernel, and the host exposes only a tiny device model.
Layer 6: the network. Inside the sandbox there is no network interface (--network none). Outside it, the worker fleet sits in its own private subnet with security groups and network ACLs that deny all egress except to the queue, the submission database API and the test-bundle bucket. The instance metadata endpoint (169.254.169.254 on the major clouds) must be unreachable from sandboxes; on AWS, requiring IMDSv2 with a hop limit of 1 ensures that even a container that somehow had network access could not fetch the instance's credentials.
Layer 7: the host and fleet. Workers hold no secrets beyond a narrowly scoped role: lease jobs, read code, write verdicts, read test bundles. They run in a separate cloud account or project. Hosts are immutable and recycled frequently (for example every day, or after any anomaly), so a persistent compromise cannot survive long. Kernel and runtime patches roll out quickly. Unusual syscalls, OOM storms and sandbox crashes feed alerts.
A typical hardened invocation with Docker and the gVisor runtime looks like this:
docker run --rm \
--runtime=runsc \
--network none \
--read-only \
--tmpfs /work:rw,size=64m \
--memory 256m --memory-swap 256m \
--cpus 1 --pids-limit 64 \
--ulimit fsize=16777216 --ulimit nofile=64 \
--cap-drop ALL \
--security-opt no-new-privileges \
--security-opt seccomp=/etc/judge/seccomp-strict.json \
--user 65534:65534 \
-v /var/cache/judge/tests/p42/v7/input:/tests:ro \
judge-python:3.12 /harness/run --test /tests/017.inIn production you would not call the Docker CLI per test; the worker talks to the container runtime directly or to a purpose-built sandbox tool. Two well-known ones: nsjail (from Google) wraps a process in namespaces, cgroups, rlimits and a seccomp policy from a single config file; isolate, written for programming olympiads and used by the CMS contest system used at the IOI, does the same with a focus on accurate time and memory measurement. Judge0, a popular open-source code-execution service, builds on isolate.
| Attack | What it looks like | Defence |
|---|---|---|
| Infinite loop | while True: pass | CPU-time limit plus wall-clock kill |
| Sleep or block forever | time.sleep(10**9), reading stdin forever | Wall-clock timeout, stdin closed after input |
| Fork bomb | while True: os.fork() | pids.max |
| Memory bomb | Allocate 50 GB | memory.max, no swap; report Memory Limit Exceeded |
| Disk fill | Write until disk is full | Read-only root, small tmpfs, RLIMIT_FSIZE |
| Output flood | Print 10 GB | Cap captured stdout (e.g. 64 MB), Output Limit Exceeded |
| Read expected answers | Open the expected-output file | Expected outputs never mounted; compare outside |
| Exfiltrate tests | Send hidden inputs to the internet | No network namespace, egress deny |
| Steal cloud credentials | HTTP to metadata endpoint | No network; IMDSv2 hop limit; scoped roles |
| Spy on other submissions | Read other users' files or processes | Per-sandbox mount and PID namespaces, fresh scratch |
| Kernel exploit | Trigger a bug via a rare syscall | seccomp allowlist, gVisor or micro-VM, fast patching |
| Compiler abuse | Include /dev/random; template bombs | Compile inside sandbox with limits; truncate error output |
The last row is often forgotten: the compiler is also running attacker-controlled input. A C++ program can #include "/etc/passwd" and the compiler will helpfully print parts of the file in its error message. Compile in the same sandbox as execution, with its own time and memory limits, and truncate compiler output before showing it to the user.
3. Fair limits, accurate measurement and verdicts#
A judge is only trusted if its verdicts are correct and repeatable. Two people submitting the same solution must get the same verdict, and the same person submitting twice must not see Accepted once and Time Limit Exceeded the next time. That is harder than it sounds.
CPU time versus wall-clock time. There are two different clocks:
- CPU time counts only the time the process was actually running on a CPU (user plus system time), read from the cgroup's
cpu.stator fromgetrusage. It is insensitive to the process being descheduled, so it is the fairer measure of algorithmic cost. - Wall-clock time is real elapsed time. It catches programs that sleep, block or spin waiting on I/O, which use little CPU but never finish.
Most judges enforce both: the verdict uses CPU time against the problem's limit (say 2 s), and a looser wall-clock limit (say 2x the CPU limit plus a second) kills stuck programs. Multi-threaded programs complicate this, because CPU time across four threads can exceed wall time; judges either restrict solutions to one CPU via the cgroup quota or sum CPU across threads and compare against the limit.
Noisy neighbours. If 16 submissions run on a 16-core machine and share caches, memory bandwidth and turbo-boost budget, a solution can run 20 to 50 percent slower than on an idle machine. Mitigations, from cheap to expensive:
- Pin each sandbox to a dedicated core (cgroup
cpuset) instead of letting the scheduler move it around, and leave one or two cores for the worker itself. - Avoid hyper-threading siblings for judge processes, or disable SMT on judge hosts, because two hyper-threads share one physical core's execution units.
- Disable frequency scaling and turbo on judge hosts, or at least use the same instance type for the whole fleet, so that "1 second" means the same amount of work everywhere.
- Use generous limits relative to the reference solution (for example, the limit is 2x to 3x the slowest accepted reference solution in the slowest supported language).
- Re-run borderline results. If a submission exceeds the limit by less than, say, 10 percent, run it again on a different core before giving TLE.
Per-language time limits. A Python solution to the same algorithm can be 10x to 50x slower than C++. Judges handle this in different ways: one shared limit sized for the slowest language (simple, but lets slow algorithms pass in C++), per-language multipliers (common), or per-language limits calibrated by running reference solutions in each language. A useful principle is to set limits so that the intended complexity passes in every supported language and the next-worse complexity fails in every language, for example O(n log n) passes and O(n squared) fails at n = 100,000.
Memory measurement. Memory is the peak resident set of the process tree, read from the cgroup (memory.peak in cgroups v2, available in recent kernels) or from getrusage's max RSS. Runtimes complicate it: the JVM reserves heap up front, so judges typically pass -Xmx equal to the problem's limit and report the actual used heap, and garbage-collected runtimes may hold memory they no longer need. When the cgroup limit is hit, the kernel's OOM killer kills the process; the worker sees the OOM event in the cgroup and reports Memory Limit Exceeded rather than Runtime Error.
Startup overhead. The JVM takes 50 to 100 ms to start; a Python interpreter about 20 ms; a native binary under 1 ms. Over 100 tests, starting a fresh JVM per test costs 5 to 10 seconds. Options: subtract a measured baseline startup time, run all tests in one process via a harness loop (Deep Dive 4), or use a pre-warmed process that forks per test. The important thing is consistency: whatever is chosen, every submission in that language is measured the same way.
The verdict taxonomy. Each verdict maps to a specific signal the worker observes:
| Verdict | Detected by | Shown to user |
|---|---|---|
| Accepted (AC) | All tests passed | Runtime, memory, percentile vs others |
| Wrong Answer (WA) | Output differs from expected (per comparator) | Failing input, expected, actual (unless hidden) |
| Time Limit Exceeded (TLE) | CPU time over limit, or wall-clock kill | Last test reached |
| Memory Limit Exceeded (MLE) | cgroup OOM event | Peak memory |
| Runtime Error (RE) | Non-zero exit, signal (SIGSEGV, SIGFPE), uncaught exception | Truncated stderr |
| Compilation Error (CE) | Compiler non-zero exit | Truncated compiler output |
| Output Limit Exceeded (OLE) | Captured output over cap | Size |
| System Error | Sandbox crash, infrastructure failure | "Please retry"; auto-rejudge |
Two subtleties. First, a System Error must never be shown as a user's fault. If the sandbox itself failed (container runtime crashed, worker out of disk), the job is retried on another worker, and if it keeps failing, the submission is marked as a system error and excluded from penalties. Second, the order of checks matters: a program killed by the OOM killer also exits with a signal; check the OOM counter before declaring a Runtime Error.
4. One set of test cases, many languages: the test harness#
LeetCode-style problems ask you to implement a function, not a whole program. In Python you write def maxDepth(self, root), in Java public int maxDepth(TreeNode root). The judge must call that function with test inputs, which may be integers, arrays, strings, linked lists, trees or graphs, and compare the return value. Writing separate test cases for each of 15 languages would be a maintenance nightmare. The standard solution has two parts.
Part 1: language-neutral serialised test cases. Every input and output is stored once, in a simple text format, typically JSON-like. A binary tree is stored as its level-order traversal with null for missing children:
input: root = [3,9,20,null,null,15,7]
output: 3That array describes the tree whose root is 3, with children 9 and 20; 9 has no children (the two nulls), and 20 has children 15 and 7. Its maximum depth is 3. Linked lists are arrays, graphs are adjacency lists, and design problems ("implement an LRU cache") are a list of method calls with arguments and a list of expected return values.
Part 2: a per-language harness. For each language there is a small, trusted wrapper program that:
- reads the serialised input from stdin,
- deserialises it into the language's native types (building actual
TreeNodeobjects from the level-order array), - calls the user's function,
- serialises the return value back to the canonical text form and prints it on stdout.
The harness is generated from the problem's function signature, so a new problem gets harnesses in every language automatically. The user's code and the harness are compiled together inside the sandbox.
# Python harness, generated for "maxDepth(root: TreeNode) -> int"
import sys, json
from collections import deque
from judge_types import TreeNode
from solution import Solution # the user's code
def build_tree(vals):
if not vals: return None
it = iter(vals); root = TreeNode(next(it)); q = deque([root])
while q:
node = q.popleft()
for side in ("left", "right"):
v = next(it, None)
if v is not None:
child = TreeNode(v); setattr(node, side, child); q.append(child)
return root
for line in sys.stdin: # one test per line
args = json.loads(line)
result = Solution().maxDepth(build_tree(args["root"]))
print(json.dumps(result), flush=True)(The loop above shows the "many tests, one process" mode. For the "fresh process per test" mode, the worker invokes the harness once per test with a single line.)
Comparators. Comparing output is not always byte equality:
- Exact match after trimming trailing whitespace: most problems.
- Floating point: accept if absolute or relative error is within, say, 1e-6.
- Unordered output: "return all subsets in any order". Canonicalise (sort) both sides before comparing.
- Multiple valid answers: "return any valid topological order". A checker (also called a special judge) is a trusted program written by the problem setter that reads the input and the contestant's output and verifies validity. It runs on the worker, outside the user's sandbox, or in its own sandbox because it processes untrusted output.
- Interactive problems: the contestant's program converses with an interactor over pipes ("guess the number" with feedback). The interactor runs in a separate sandbox, and the worker wires their stdin and stdout together and enforces limits on both.
Running many tests: one process or one per test?
| Approach | Pros | Cons |
|---|---|---|
| One process, harness loops over all tests | Pays startup once (big win for the JVM); fastest | Global state can leak between tests (a static cache that makes later tests faster or wrong); a crash in test 40 hides which test |
| Fresh process per test, same sandbox | Clean state per test; precise per-test time and memory | Startup cost per test; more syscalls |
| Fresh sandbox per test | Strongest isolation | Too slow for 100 tests unless sandboxes are snapshots |
A pragmatic hybrid: fresh process per test for native languages (startup is under a millisecond), and a single process per batch of tests for the JVM and .NET, with the harness resetting known static state. Whichever mode is chosen, define the reported runtime explicitly (total across all tests, or the maximum single test) and apply the definition identically to every submission in that language.
Test-case authoring quality. Most incorrect verdicts in a real judge come not from infrastructure but from bad tests: a missing edge case lets a wrong solution pass, or a mistaken expected output fails correct ones. Good practice is to generate tests with a random generator plus a brute-force reference solution, include edge cases (empty input, maximum size, all equal values, degenerate trees like a linked list), validate every input against the constraints with a validator program, and run several reference solutions in different languages to cross-check expected outputs. Test bundles are versioned and immutable; a fix is a new version plus a targeted rejudge.
5. The submission job queue#
The queue is the shock absorber between a bursty front end and a fixed-rate back end. The design questions are which queue technology, what goes into a message, how leasing and retries work, and how priorities keep contests fast.
Why a queue at all? Without one, the Submission Service must find a free worker synchronously. During a burst there is none, so it either fails the request or holds it open, and neither is acceptable during a contest. With a queue, the only synchronous work is a database insert and an enqueue, both of which take milliseconds and scale easily. The trade-off is that the client no longer gets the verdict in the response, so we need result delivery (Deep Dive 6). Some designers argue a queue is overkill at LeetCode's scale and that horizontally scaled workers behind a load balancer are enough. That works for steady load, but the contest burst and the retry-on-crash behaviour are exactly what a queue gives for free, so for this problem the queue earns its place. See Asynchronous Processing and Message Queues.
Which queue?
| Option | Model | Strengths | Weaknesses for this workload |
|---|---|---|---|
| Amazon SQS (standard) | Per-message lease (visibility timeout) | Fully managed, scales without partitions, built-in dead-letter queue | No strict ordering (not needed), no native priorities, so use separate queues |
| RabbitMQ | Broker with per-message ack | Priority queues, flexible routing, low latency | You operate it; cluster sizing during bursts |
| Redis Streams with consumer groups | Log with pending-entries list per consumer | Very low latency, already in the stack | Durability depends on Redis persistence; you build claim and retry logic |
| Kafka | Partitioned log, offset per partition | Huge throughput, replay | Head-of-line blocking: one slow 10 s job stalls every message behind it in the partition; parallelism capped by partition count |
The Kafka row is the important one to explain. Kafka assigns each partition to exactly one consumer in a group and tracks progress as a single offset. If one submission takes 10 seconds, the consumer cannot commit past it, and other jobs in that partition wait or must be tracked out of order by hand. Judge jobs are independent, uneven in duration and long-running, which is the textbook fit for a per-message lease queue like SQS or RabbitMQ rather than a log. (Kafka is still a fine choice for the verdict events that feed the leaderboard and analytics.) See Apache Kafka in Practice.
What goes in the message. Keep it small and let the worker fetch details:
{ "submissionId": "9f1c...", "problemId": "max-depth", "testVersion": 7,
"language": "python3.12", "priority": "contest", "attempt": 1,
"enqueuedAt": "2026-12-03T14:31:05Z" }Code can go inline if it is small (SQS messages can carry hundreds of KB), which saves a database read per job. Test cases never go in the message; they are cached on the worker.
Leases, retries and idempotency. A worker receives a message, which makes it invisible to other workers for the visibility timeout (say 60 seconds, comfortably longer than the slowest submission). The worker extends the lease if needed, writes the verdict and then deletes the message. If the worker crashes, the message becomes visible again and another worker retries it. This is at-least-once delivery, so the same submission can occasionally be judged twice. That is harmless as long as:
- the verdict write is conditional (
UPDATE submissions SET ... WHERE id = :id AND status != 'done', or compare-and-set on an attempt number), - the leaderboard update deduplicates first accepts (Flow 3),
- and nothing else has side effects on "verdict written".
After a few attempts (say 3), the message moves to a dead-letter queue, and the submission is marked System Error with an alert. A submission that crashes every worker that touches it (a "poison pill", for example one that triggers a sandbox runtime bug) must not cycle forever, and must not take workers down repeatedly. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
Priorities. Not all jobs are equal:
- Contest Submits affect rankings and must be fastest.
- Contest Runs are frequent and help contestants debug.
- Practice Submits.
- Practice Runs.
- Rejudges and background jobs (re-running old submissions after a test fix, computing runtime percentiles).
With SQS, use one queue per class and have workers poll in weighted order (for example, take from the contest queue first, but every tenth poll take from practice to avoid starving it). RabbitMQ supports priorities natively. Strict priority starves lower classes during long bursts; weighted fair polling prevents that while still favouring contests.
Fairness between users. A single user submitting 50 times in a minute (or a script doing it) should not delay everyone else. Rate limit at the gateway (for example, at most one Submit every 5 seconds per user, and a token bucket for Runs; see Rate Limiting and Throttling), and, for extra protection, cap the number of in-flight jobs per user: a new submission from a user who already has two queued may wait or replace the older one.
Alternative: no broker, the database is the queue. At this scale, a PostgreSQL table with SELECT ... FOR UPDATE SKIP LOCKED is a legitimate queue: workers claim the oldest queued row, skip rows locked by others, and update status in the same transaction. It removes one moving part and makes "persist then enqueue" atomic. It falls over at tens of thousands of claims per second, which a code judge does not need, so it is a defensible simplification for a small team.
-- Worker claims one job; concurrent workers skip rows others have locked
UPDATE submissions SET status = 'running', worker_id = :me, lease_until = now() + interval '60 seconds'
WHERE id = (
SELECT id FROM submissions
WHERE status = 'queued' OR (status = 'running' AND lease_until < now())
ORDER BY priority, created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, problem_id, language;6. Delivering the result back to the browser#
The client submitted and got an id. How does it learn the verdict? Four options, from simplest:
Good: short polling. The client calls GET /submissions/:id every second until it sees done. Simple, stateless, works through every proxy and corporate firewall, and trivially load-balanced. The cost is wasted requests: a 5 second judge with 1 s polling makes about 5 requests per submission, which at 10,000 in-flight submissions is 10,000 requests per second of tiny reads. Make them cheap by serving the status from Redis (sub:{id}, written by the worker alongside the database) rather than the primary database. Many production judges use polling for exactly these reasons.
Better: progressive polling. Poll quickly at first, when the result is likely to land soon, then back off: for example after 0.5 s, 1 s, 1 s, 2 s, 2 s, 4 s. If the response includes the queue position or an estimated wait ("you are number 2,300 in the queue"), the client can schedule its next poll intelligently and show the user honest progress. This cuts polling load by half or more with no extra infrastructure.
Better: long polling. The client sends a request that the server holds open until the result is ready or 20 to 30 seconds pass. Each submission costs one or two requests instead of five, and latency is immediate. It requires the API tier to hold many open connections and to be notified when a verdict lands (via Redis pub/sub on the submission id), so it adds a moving part.
Overkill here: Server-Sent Events or WebSockets. A push channel gives the lowest latency and enables streaming per-test progress ("test 37 of 100 passed"). But it means stateful connections, a routing layer that knows which server holds which user's connection, and reconnection logic. For a result that arrives once, a few seconds after submission, that complexity is not justified unless you also want live per-test progress or are already running WebSockets for something else (a collaborative interview pad, for example). See Polling, Long Polling, SSE, WebSockets and Webhooks and Pattern: Pushing Realtime Updates.
| Option | Requests per submission | Latency after verdict | Server state | Verdict |
|---|---|---|---|---|
| Short polling at 1 s | ~5 | up to 1 s | None | Good default |
| Progressive polling | ~3 | up to the current interval | None | Recommended |
| Long polling | 1 to 2 | immediate | Open requests plus pub/sub | Good if latency matters |
| SSE or WebSocket | 1 connection | immediate, can stream progress | Connection registry | Only with streaming needs |
Queue position is a cheap, valuable feature. With SQS you only have approximate total depth, but the Submission Service can maintain a per-priority counter in Redis (increment on enqueue, increment a "served" counter on dequeue) and report position = myTicket - served. During a contest burst, "position 1,200, about 20 seconds" feels very different from an unexplained spinner.
7. The contest leaderboard#
Requirements: up to 100,000 participants, rank by problems solved and then by time, show the top of the board and each user's own rank, fresh within about 5 seconds, and absorb about 20,000 reads per second.
Bad: query the database on every request. The aggregate query from the high-level design scans every accepted submission in the contest, groups by user and problem, then by user, and sorts. With a good index on (contest_id, verdict, user_id, problem_id) it might take 50 to 500 ms for a big contest. Multiply by 20,000 requests per second and the database melts at exactly the moment you need it most.
Good: compute periodically and cache. Run the query every 10 to 30 seconds in a background job and store the result (top 1,000 plus a user-to-rank map) in a cache. Reads are cheap and the database sees one query per interval. The downsides are staleness (a contestant who just solved a problem does not move for up to 30 seconds, which feels broken) and the cost of re-running a full aggregate even when nothing changed. For small contests or a first version, this is perfectly adequate.
Great: an incrementally maintained Redis sorted set. A sorted set (ZSET) stores members with numeric scores, ordered by score, implemented as a skip list plus a hash map. Insert or update is O(log n), reading the top N is O(log n + N), and finding one member's rank is O(log n). For 100,000 members, each operation takes microseconds.
The leaderboard needs two keys to sort by, solved count (descending) and time (ascending), but a sorted set has one score. The trick is a composite score that encodes both:
score = solved × 10^7 - finishSeconds
where finishSeconds = seconds from contest start to the user's last first-accept
(plus penalty seconds, if the rules have penalties)
Example, 90-minute contest (5,400 s max, well under 10^7):
Alice: 4 solved, finished at 3,100 s -> 40,000,000 - 3,100 = 39,996,900
Bob: 4 solved, finished at 2,800 s -> 40,000,000 - 2,800 = 39,997,200 (ranks above Alice)
Cara: 3 solved, finished at 1,200 s -> 30,000,000 - 1,200 = 29,998,800Higher is better, so read in descending order. Redis scores are IEEE 754 doubles, which represent integers exactly up to 2^53 (about 9 × 10^15), so this encoding is exact with lots of room. Ties on identical scores are broken by member name lexicographically, which is arbitrary; if exact ties must be broken by an explicit rule (earlier registration, for example), fold that into lower-order digits.
On each first accept, the Leaderboard Updater recomputes the user's score and writes it:
SADD solved:{cid}:{uid} {pid} -> 1 if new, 0 if already solved
if new:
HINCRBY stats:{cid}:{uid} solved 1
HSET stats:{cid}:{uid} finish {secondsFromStart + penalty}
ZADD lb:{cid} {solved*10^7 - finish} {uid}In practice those steps run as one Lua script (or a MULTI transaction) so the read-modify-write is atomic per user. Reads:
ZRANGE lb:{cid} 0 49 REV WITHSCORES -> top 50 (Redis 6.2+; ZREVRANGE is the older, deprecated form)
ZREVRANK lb:{cid} {uid} -> my 0-based rank
ZCARD lb:{cid} -> number of ranked participantsScoring rule variants. Real contests differ, and the encoding adapts:
- Penalty for wrong attempts. ICPC-style rules rank by problems solved, then by total penalty time: the sum, over solved problems, of the minutes until acceptance plus 20 penalty minutes for each rejected attempt before it. LeetCode-style weekly contests have used a similar rule of finish time plus a penalty (5 minutes) per wrong submission. Either way, the updater tracks wrong attempts per (user, problem) and adds the penalty only when the problem is eventually solved.
- Points per problem. Harder problems are worth more (for example 3, 4, 5 and 6 points). Replace
solvedwith total points. - Time-decaying points. Codeforces-style rules give each problem a value that decreases over the contest. The score is the sum of the earned values, which is still one number.
Pagination and "my rank". Users mostly care about the top 50 and their own position. ZREVRANK gives the latter directly. To show "you and the people around you", ZRANGE lb:{cid} (rank-5) (rank+5) REV. Deep pages (rank 40,000 to 40,050) are equally cheap: Redis skip lists support rank-based access in O(log n).
Serving 20,000 reads per second. One Redis primary can handle around 100,000 simple operations per second, so a single instance would cope, but it is wasteful to recompute the same top-50 page for every request. Two cheap layers:
- Micro-cache the top page. The Leaderboard Service caches the serialized top 50 for 1 to 2 seconds in process memory. 20,000 requests per second become a few Redis calls per second per server, and only the
ZREVRANKfor "me" goes to Redis (or to read replicas). - CDN cache for the public board. The top-N page is identical for everyone, so it can be cached at the CDN with a few seconds of TTL. The personal "my rank" call is separate and small.
Polling, not WebSockets. Clients poll every 5 seconds, back off when the tab is hidden or when updatedAt has not changed, and speed up slightly near the end of the contest. Pushing every rank change to 100,000 clients would mean far more messages than polling, since each accept shifts many people's ranks.
Freezing and final results. Many contests freeze the public board in the final period (ICPC freezes it for the last hour) to keep suspense. Implementation: stop copying updates from the live sorted set into the public one at freeze time, while still maintaining the live set internally. After the contest, final rankings are recomputed from the database with the authoritative query, after rejudges and plagiarism checks, and only then published and used for ratings. Redis is for the live view; the database is for the record.
Sharding is not needed. 100,000 members is about 6 MB. Even a million-person contest would be 60 MB. Running a primary with a replica for failover and a rebuild path from the database is the whole story. If you need a leaderboard for hundreds of millions of members (a global game ranking), see the approaches in the Top-K case study, which partition by score range.
8. Handling contest bursts#
The burst is predictable in time (the contest schedule is published days ahead) and in size (registration counts are known). That changes the strategy from "react fast" to "be ready, then react".
Bad: vertical scaling. Run the judge on a few very large machines and buy bigger ones before contests. There is a ceiling on machine size, a single big machine is a single failure domain, and you pay for peak capacity all week. It also does nothing for the API tier's connection count.
Great: horizontal autoscaling on the right signal. The worker fleet is a set of identical, stateless machines (or containers on ECS, Kubernetes or Nomad). An autoscaler adds and removes workers. The crucial choice is the signal:
- CPU utilisation is a poor signal. Workers deliberately run at high CPU, and CPU does not tell you how much work is waiting.
- Queue depth is better: scale to
desired = backlog / (jobs per worker per minute × target drain minutes). - Age of the oldest message (SQS exposes
ApproximateAgeOfOldestMessage) is the best user-facing signal: it is literally how long the unluckiest user is waiting. Alert and scale aggressively if it passes, say, 10 seconds during a contest.
The catch is reaction time. Launching a cloud instance, booting it, pulling multi-GB language images and warming sandboxes takes 1 to 5 minutes. A contest burst arrives in seconds. Reactive autoscaling alone means the first few minutes of every contest are slow, which is exactly when everyone is watching.
Great: queue plus pre-scaling plus warm pools. Combine three mechanisms:
- Scheduled pre-scaling. The contest scheduler raises the fleet's minimum size about 30 minutes before the start, sized from the number of registrants using the capacity math (100,000 registrants, about 1,700 cores at the pessimistic peak). Scale-down is delayed until the queue drains after the end.
- Warm pools and pre-baked images. Machine images already contain every language runtime image, so a new worker does not pull gigabytes from a registry. On boot, workers prefetch the contest's test bundles and start a pool of warm sandboxes per language weighted by expected language mix (Python and C++ dominate in many contests).
- The queue absorbs the remainder. If the burst still exceeds capacity, the queue buffers it and users see a queue position, not an error. Reactive autoscaling on queue age then adds more.
Load shedding and graceful degradation. Even with pre-scaling, plan for the burst being bigger than expected or for a region losing capacity. Decide in advance what to degrade, in order:
- Pause background work. Stop rejudges, percentile recomputation, plagiarism scanning and practice-mode analytics.
- Deprioritise practice traffic. Practice Submits and Runs go to lower-priority queues; during a contest, the global site can show "judging may be slower during the contest".
- Reduce Run costs. Runs on sample input are cheap per execution but frequent. Rate limit them more tightly per contestant, and cache results for identical (code, input) pairs.
- Fail fast on wrong answers. Already the default: stop at the first failing test. Since most submissions are wrong, this alone cuts work substantially.
- Shed only as a last resort. If queues exceed a hard bound (say, a predicted wait of 2 minutes), reject new practice submissions with "try again later" (HTTP 503 with
Retry-After), but never reject a contest submission. Contest submissions can wait in the queue; their server timestamp was recorded at acceptance, so waiting does not hurt their ranking.
That last point is subtle and important: the leaderboard time is the acceptance time stamped by the API, not the time the verdict was computed. A contestant whose submission waited 30 seconds in the queue is not penalised for our capacity problem. That decoupling is what makes "accept everything, judge when possible" fair.
Burst writes beyond the judge. The other write paths also spike: submission inserts (about 400 per second at peak, trivial for one PostgreSQL primary), Redis leaderboard updates (one per accept, a few hundred per second) and verdict events. None needs special handling at this scale, but if submission inserts ever became a bottleneck, the same pattern applies: write to a durable queue or log first, persist in batches, and return the id immediately. See Pattern: Scaling Writes.
Cost control after the contest. Scale down gradually (draining in-flight work, honouring leases), and use spot or preemptible instances for the extra contest capacity and for practice traffic. A preempted worker simply loses its lease, and the job is retried elsewhere, so the at-least-once design handles spot interruptions for free. Keep the contest floor on on-demand instances if a mass spot reclamation during a contest would be unacceptable.
9. The worker fleet: images, warm pools and placement#
A worker is a machine that runs a small agent: lease a job, prepare a sandbox, run, report, repeat. The design choices inside the fleet determine both latency and cost.
Language images. Each language gets an immutable image containing the compiler or interpreter, the standard library, any allowed libraries (many judges allow common ones such as Python's collections or a specific version of a C++ standard library), the trusted harness generator output and nothing else: no shell utilities that are not needed, no package manager, no network tools. Images are versioned (judge-cpp:gcc13-v4), and each submission records the image version so verdicts are reproducible. Upgrading a compiler is a deliberate event, because a compiler change can alter runtimes and even verdicts (undefined behaviour in C++ that happened to work with one version may crash with another).
One worker, many slots. A 16-vCPU worker runs, say, 12 to 14 concurrent sandboxes, each pinned to its own core, leaving cores for the agent, the container runtime and the comparator. Memory is the other constraint: 14 sandboxes at a 256 MB limit plus JVM overheads need around 8 GB, so compute-optimised instances with 2 GB per vCPU fit well. Problems with larger memory limits (1 GB) consume multiple slots' worth of memory, so the agent tracks memory as well as cores when accepting jobs.
Warm pools. Cold-starting a container for every submission costs 100 to 500 ms, and a micro-VM roughly 125 ms plus guest userspace. The agent keeps a small pool of pre-created sandboxes per language, sized by recent demand. When a job arrives, it takes a warm sandbox, injects the code and runs it. After use, the sandbox is destroyed (strongest hygiene) and a replacement is created in the background, or, if the policy allows reuse, its scratch area is wiped and its processes are killed. Firecracker supports snapshot and restore: boot a guest once, start the language runtime inside it, snapshot the memory, and restore fresh copies from the snapshot in a few milliseconds to tens of milliseconds. That gives each submission a pristine VM with a warm runtime, which is close to ideal.
Language-specific or general workers? Two layouts:
- General workers: every worker has every language image and pools for each. Simple scheduling and good utilisation, but more disk and memory per worker for idle pools.
- Language pools: separate worker groups or queues per language (or per family, such as JVM languages). Better warm-pool hit rates and image caching, and a JVM-heavy surge cannot starve Python. The cost is fragmentation: one language's pool may be idle while another's is overloaded.
A good compromise: general workers with all images, a shared queue, and per-language warm-pool sizes adjusted by an exponentially weighted moving average of recent demand. Add dedicated pools only if one language's behaviour (memory, startup) is very different.
Test-case distribution. Test bundles total a few GB, so every worker can hold all of them on local SSD. A worker checks its local cache for the bundle version named in the job (verified by SHA-256); on a miss, it downloads it from object storage, which takes well under a second for typical bundles. Before a contest, pre-fetch. Because bundles are immutable and versioned, cache invalidation is trivial: a new version is a new key. The contest's hidden tests must be readable only by the fleet's role, never by public endpoints, and ideally only from the contest start.
Placement and the agent loop. In pseudo-code:
loop:
if free_slots == 0: wait
job = queue.receive(visibility = 60 s, prefer = [contest, practice] weighted)
if job is None: sleep(backoff); continue
start lease-extender for job
sub = db.get_submission(job.submissionId)
if sub.status == DONE: queue.delete(job); continue # duplicate delivery
bundle = cache.ensure(job.problemId, job.testVersion)
box = pools[job.language].take() or create_sandbox(job.language)
result = judge(box, sub.code, bundle, limits) # compile, run, compare
db.write_verdict_if_not_done(sub.id, result, attempt = job.attempt)
redis.set("sub:" + sub.id, result, ttl = 600 s)
events.publish(result) # leaderboard, analytics
queue.delete(job); destroy_or_recycle(box)The ordering is deliberate: record the verdict, publish the event, then acknowledge. Any crash before the acknowledgement causes a retry, and every step after the first is idempotent.
Health and quarantine. A worker whose sandboxes keep failing (disk full, runtime bug, kernel issue) should stop leasing jobs, mark itself unhealthy and be replaced. Track per-worker error rates: one bad worker that returns System Error on every job can otherwise poison hundreds of submissions in a minute. Also periodically run canary submissions (known accepted, known TLE, known MLE solutions) through each worker to detect drift in timing or behaviour.
10. Caching: problems, results and the query-cache pattern#
Caching appears in four places. The general pattern each time is cache-aside: check the cache, fall back to the source of truth, populate the cache. See Caching Fundamentals and Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.
1. Problem pages. 4,000 problems × 15 languages is small enough to keep the whole catalogue in every Problem Service instance's memory. Statements are also cached at the CDN. Invalidate by versioning: publishing a new problem version changes the URL or cache key, so stale entries simply expire.
2. Submission status for polling. Workers write sub:{id} into Redis with a 10-minute TTL as well as to the database. Polls read Redis first; on a miss (for example, an old submission), they fall back to the database. This takes 10,000 polls per second off the primary.
3. Leaderboards. The sorted set is itself a cache of the authoritative query; the top-page micro-cache sits in front of it.
4. Result deduplication. Identical code is submitted surprisingly often (copied template solutions, repeated clicks, a user resubmitting unchanged code). Key a result cache by hash(problemId, testVersion, language, imageVersion, normalisedCode); if the same tuple was judged recently, reuse the verdict. Two cautions: never reuse results for verdicts that depend on timing near the limit (TLE, or AC within 10 percent of the limit), and never share across contest boundaries in a way that leaks information (another user's verdict on identical code tells you nothing you did not know, but logs and timing could). For Runs with custom input, the key also includes the input.
The query-cache pattern in detail. The fourth cache is an instance of a classic design: caching the results of expensive queries (here, "judge this code") so that repeats are served from memory. The standard building block is an LRU (least recently used) cache built from a hash map plus a doubly linked list:
- The hash map maps a key to a node in the list, giving O(1) lookup.
- The doubly linked list keeps entries in order of recency: the head is the most recently used, the tail the least.
- Get: look up the node; if present, move it to the head and return its value.
- Set: if the key exists, update it and move it to the head. Otherwise insert a new node at the head; if the cache is over capacity, remove the tail node and delete its key from the map.
Every operation is O(1). A TypeScript sketch:
class LRU<K, V> {
private map = new Map<K, V>(); // JS Map preserves insertion order
constructor(private capacity: number) {}
get(key: K): V | undefined {
if (!this.map.has(key)) return undefined;
const v = this.map.get(key)!;
this.map.delete(key); this.map.set(key, v); // move to most-recent end
return v;
}
set(key: K, value: V): void {
if (this.map.has(key)) this.map.delete(key);
this.map.set(key, value);
if (this.map.size > this.capacity) {
const oldest = this.map.keys().next().value as K; // least recent
this.map.delete(oldest);
}
}
}(JavaScript's Map iterates in insertion order, so deleting and re-inserting a key moves it to the end. This gives the same behaviour as the hash map plus linked list without writing the list. In Java, LinkedHashMap with access order does the same.)
When to update the cache. Results can go stale when test cases change. Three approaches: put the test version in the key (preferred: a new version is a new key, nothing to invalidate), set a TTL so entries expire, or delete affected entries explicitly when a problem is republished. See Cache Eviction and Invalidation.
Scaling the cache beyond one machine. A single process's LRU holds only what fits in its memory, and each API server has its own copy. If the result cache needs to be shared and large, options are:
- Each server has its own cache: simple, but low hit rates because repeats land on different servers.
- A copy of the cache on every server: high hit rate, but memory-wasteful and expensive to keep consistent.
- A sharded cache: each key lives on one cache node chosen by hashing. Use Consistent Hashing so that adding or removing a node remaps only about 1/n of the keys instead of almost all of them. Redis Cluster (hash slots) or a Memcached client with consistent hashing does this for you. See Distributed Caching with Redis and Memcached.
At code-judge scale, a single Redis instance with a replica holds every hot structure comfortably, and a sharded cache is a "how would this grow" answer, not a day-one requirement.
11. Correctness, rejudging and contest integrity#
A judge's reputation rests on verdicts people trust and rankings nobody can game. Five mechanisms protect that.
Versioned, immutable test bundles. Every change to a problem's tests creates a new version; each submission stores the version it was judged against. When a setter discovers that a test was wrong, or that weak tests let wrong solutions pass, the fix is a new version plus a rejudge: select the affected submissions (WHERE problem_id = :p AND test_version = :old, optionally only within a contest), enqueue them at background priority (or at high priority right after a contest, before standings are final), and recompute the leaderboard. Because jobs are idempotent and keyed by submission id plus attempt, a rejudge is just another batch of jobs.
Determinism. Two runs of the same code should get the same verdict. Sources of non-determinism, and fixes:
- Timing noise near the limit: core pinning, fixed CPU frequency, borderline re-runs (Deep Dive 3).
- Randomness: programs that use random seeds behave differently each run. This is legitimate (randomised algorithms), but problems should be designed so that correct randomised solutions pass with overwhelming probability.
- Hash-table ordering: languages that randomise hash seeds (Python's string hashing, for example) can change iteration order; a solution that depends on it is wrong, and the judge should not accidentally fix it by pinning seeds in some languages but not others.
- Environment: the same image version, the same limits and the same harness for everyone.
Hidden tests and information leaks. In a contest, contestants see only "Wrong Answer on test 12", not the input, so they cannot extract the hidden tests by printing them. Outside contests, showing the failing input is a feature. Even in a contest, side channels exist: a contestant can encode bits of the hidden input in which verdict they get (crash deliberately if the first number is even, exceed the time limit if odd) and reconstruct inputs over many submissions. Defences are rate limits on submissions, penalties for wrong attempts, and large inputs that would take too many submissions to extract.
Plagiarism and cheating. After a contest, compare accepted solutions pairwise for suspicious similarity. Simple text diff is easily defeated by renaming variables, so tools normalise code first (strip comments and whitespace, rename identifiers, tokenise) and then compare fingerprints. The classic approach is winnowing, from "Winnowing: Local Algorithms for Document Fingerprinting" (Schleimer, Wilkerson and Aiken, SIGMOD 2003), the algorithm behind the MOSS plagiarism detector: hash every k-gram of the token stream, slide a window over the hashes and keep the minimum hash in each window as a fingerprint. Two documents that share a long enough substring are guaranteed to share at least one fingerprint, and the fingerprint set is much smaller than the set of all k-grams. Pairs with high fingerprint overlap are flagged for human review. Checking all pairs among 50,000 accepted solutions to one problem is about 1.25 billion pairs, so index fingerprints in an inverted index (fingerprint to list of submissions) and compare only pairs that share fingerprints. This runs as a batch job after the contest, not in the hot path. Contests now also contend with solutions written by AI assistants, which do not look copied from each other; platforms respond with rules, behavioural signals and manual review rather than with a purely technical detector.
Server-side time, always. Every timestamp that affects ranking (submission accepted, contest start and end) comes from the server. The contest end is enforced at the API: a submission received at 16:00:00.300 for a contest ending at 16:00:00 is rejected, regardless of what the client clock says. If the API tier spans multiple machines, their clocks are kept in sync with NTP or a cloud time service to within milliseconds, which is far tighter than any contest rule needs. See Time, Clocks and Ordering.
Ratings after the contest. Platforms compute ratings (Elo-like systems) from final standings. This is an offline job over the authoritative standings and must run only after rejudges and plagiarism decisions, since reversing a rating change is far more painful than delaying it by an hour.
12. Right-sizing the architecture: availability, data and regions#
The last deep dive is about restraint. The non-functional requirements are availability, security and burst handling, not planetary scale, so the right architecture is simpler than it first appears.
A modular monolith plus a judge fleet. The problem catalogue, submissions, contests and leaderboard reads are one web application, deployed as a stateless, horizontally scaled service behind a load balancer (see Load Balancing and Vertical vs Horizontal Scaling and Stateless Design). The execution fleet is a separate system because it has a different trust boundary (it runs hostile code), a different scaling curve (CPU bursts) and different hardware (compute-optimised, perhaps bare metal for micro-VMs). That one split is justified; splitting the web app into a dozen microservices is not.
Availability over consistency. Concretely:
- The leaderboard may be a few seconds stale; that is by design.
- Submission status reads come from Redis or a replica and can lag the primary by a moment.
- The submission write path must be highly available: a PostgreSQL primary with a synchronous or semi-synchronous standby in another availability zone and automatic failover (managed services such as Amazon RDS or Aurora do this in under a minute or so), plus the queue as a buffer. See Database Replication and Designing for High Availability.
- If the database is briefly unavailable during a failover, the Submission Service can still accept submissions by writing them durably to the queue (or a log) first and persisting rows when the database returns. This is the write-ahead buffering idea from scaling-writes, and it is what keeps "never reject a contest submission" true through a primary failover.
Sharding, maybe never. Submissions grow by about 5 TB a year. A single well-tuned PostgreSQL primary with partitioning by month (declarative partitioning) handles that for years, with old partitions moved to cheaper storage. If you must shard, shard by user_id: history queries are per user, and contest rebuilds can go through a separate index table or the event stream. See Partitioning and Sharding.
Regions. Users are global, but code execution is not latency sensitive at the 100 ms level; a verdict that takes 4.1 seconds instead of 3.9 is imperceptible. So:
- Serve the static app and problem statements from a CDN everywhere.
- Run the API, database and judge fleet in one primary region with multiple availability zones.
- Keep a warm standby region for disaster recovery (database replica, images, test bundles), and a runbook to fail over. See Disaster Recovery and Backups.
- A contest is a single global event with a single ranking, which argues against multi-primary data: one region owns contest state.
Some judges place execution workers in several regions to use spare capacity. That is fine because workers are stateless: a job in a queue can be leased by any region's workers as long as they can reach the queue, the code and the test bundles.
Security boundaries in the architecture. Draw the trust zones explicitly in the interview:
The judge zone can talk to the queue, a narrow verdict-writing endpoint and the test bucket, and nothing else. It has no route to the database directly, no route to the internet and no credentials beyond its role. If the worst happens and a sandbox escape gives an attacker control of a worker host, the blast radius is that worker and the jobs it could see, not the user database. See Security Fundamentals for System Design.
Cost picture. At steady state, a few hundred cores; at contest peak, around 1,700 for an hour or two a week. On-demand compute-optimised instances cost roughly a few cents per vCPU-hour, so even the peak costs tens of dollars per hour, and pre-scaling an hour early is cheap insurance compared with a botched contest. Spot capacity, scale-down after the contest and fail-fast judging keep the bill modest. The expensive mistakes in this system are security incidents and unfair contests, not compute.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Contest-start burst exceeds fleet capacity | Queue age grows; verdicts take minutes; contestants complain of unfairness | Scheduled pre-scaling from registration counts, warm pools, pre-baked images; queue position shown to users; acceptance-time ranking so waiting does not hurt scores |
| Sandbox escape via kernel bug | Attacker controls a worker host; possible lateral movement | seccomp allowlist, gVisor or Firecracker, judge zone in separate account and VPC, no secrets on workers, frequent host recycling, fast patching |
| Worker crashes mid-judge | Submission stuck in "running" | Lease (visibility timeout) expires and job is retried; idempotent verdict write; sweeper for stale "running" rows |
| Poison-pill submission crashes every worker | Repeated worker failures, wasted capacity | Max attempts then dead-letter queue; mark System Error; quarantine and alert; add regression test to sandbox |
| Noisy neighbours skew runtimes | Correct solutions get TLE; non-reproducible verdicts | Core pinning, SMT off, fixed CPU frequency, uniform instance types, generous limits, borderline re-runs |
| Leaderboard read storm | 20,000 reads per second hit Redis or the DB | Redis sorted set, 1 to 2 s micro-cache of the top page, CDN for the public board, client backoff |
| Redis leaderboard lost | Live board empty during contest | Replica with failover; rebuild from the submissions table with the aggregate query; final standings always from the DB |
| Duplicate verdict events | Score double-counted | SADD first-accept check; atomic Lua update; conditional verdict writes |
| Submission DB primary failover | Brief write unavailability | Multi-AZ standby with automatic failover; accept submissions into the durable queue first and persist on recovery |
| Result-polling load | Thousands of polls per second on the primary | Status in Redis with TTL; progressive polling; long polling if needed |
| Wrong or weak test cases | Wrong verdicts, contest disputes | Generators plus brute-force references, validators, multi-language reference solutions, versioned bundles, targeted rejudge |
| Practice traffic starves contests (or vice versa) | Contest latency spikes; practice users see endless pending | Separate queues per class, weighted fair polling, per-user rate limits and in-flight caps, shed practice first with 503 and Retry-After |
What Interviewers Expect#
Mid-level#
- Gathers the core functional requirements (browse, code, submit, leaderboard) and states the key non-functional ones: security, about 5 s feedback, 100,000-user contests.
- Defines Problem, Submission and Leaderboard entities and a clean API, including returning a submission id and polling for the result.
- Recognises that user code must not run in the API server and proposes containers with basic limits (CPU, memory, timeout, no network).
- Proposes a working leaderboard, possibly the periodic-query-plus-cache version, and can explain its staleness.
- Covers the breadth of the design end to end; depth in one or two areas is a bonus.
Senior#
- Compares execution options with real trade-offs: VM versus container versus serverless, with startup times, isolation boundaries and when each fits.
- Lists the sandbox hardening layers: read-only filesystem, tmpfs scratch, cgroup limits, pids limit, seccomp, dropped capabilities, no network at both the namespace and the VPC level.
- Explains how test cases are run: language-neutral serialised inputs, per-language harnesses, comparators and checkers, fail-fast.
- Introduces a queue to absorb bursts and handle worker crashes, and explains at-least-once delivery and idempotent verdict writes.
- Uses a Redis sorted set with a composite score for the leaderboard and does the capacity math for the contest burst (about 1,700 cores).
Staff+#
- Keeps the architecture simple and right-sized (a modular monolith plus an isolated judge fleet), and justifies why the scale does not need sharding or multi-region writes.
- Treats isolation as defence in depth with an explicit threat model (expected outputs never in the sandbox, compiler as an attack surface, metadata endpoint, blast radius of a host compromise) and knows where gVisor or Firecracker change the picture.
- Designs for fairness: CPU versus wall time, noisy neighbours, per-language limits, server-side timestamps, acceptance time as the ranking time, rejudges with versioned tests.
- Plans for the burst as a scheduled event: pre-scaling sized from registrations, warm pools, priority classes and an explicit degradation order that never sheds contest submissions.
- Describes operational guardrails: canary submissions, worker quarantine, dead-letter handling, queue-age alerting, and a path to scale each component further if the product grows.
Deep Dive: how Linux sandboxes, gVisor and Firecracker work underneathShow
Namespaces. A namespace wraps a global kernel resource so that processes inside see their own instance. A sandbox launcher creates them with clone() or unshare() flags:
CLONE_NEWPID: the sandboxed program is pid 1 in its own process tree and cannot see or signal host processes. When pid 1 exits, the kernel kills every other process in the namespace, which is a convenient way to clean up forked children.CLONE_NEWNS: a private mount table. The launcher builds a minimal root (the language image, read-only), mounts a size-limitedtmpfsfor scratch, bind-mounts the current test input read-only, and callspivot_rootso the old host root is unreachable.CLONE_NEWNET: a fresh network stack with only a loopback interface, which is down unless brought up. No routes, no DNS, nothing to connect to.CLONE_NEWUSER: maps uids inside to an unprivileged range outside. Even if the program gained "root" inside, the kernel treats it as an unprivileged host user for anything outside the namespace.CLONE_NEWIPCandCLONE_NEWUTS: private System V IPC objects and hostname, so sandboxes cannot talk through shared memory segments.
One caution: user namespaces have themselves been a rich source of kernel vulnerabilities, because they let unprivileged code reach kernel paths that used to require root. Judges commonly let the trusted launcher use user namespaces while the seccomp filter forbids the untrusted program from creating any further namespaces.
cgroups v2. A control group is a directory in the cgroup2 filesystem. The launcher creates one per sandbox, writes limits into files, and moves the sandbox's first process into it. Children inherit membership, so a fork bomb stays inside.
/sys/fs/cgroup/judge/sub-9f1c/
cpu.max "100000 100000" # 100 ms quota per 100 ms period = 1 CPU
cpuset.cpus "7" # pin to core 7
memory.max "268435456" # 256 MB hard limit
memory.swap.max "0" # no swap
pids.max "64" # fork-bomb guard
cpu.stat -> usage_usec # CPU time used, read after the run
memory.peak -> peak bytes # peak memory (recent kernels)
memory.events -> oom_kill count # did the OOM killer fire?
cgroup.kill "1" # write to kill every process at onceThe worker reads cpu.stat for CPU time, memory.peak (or samples memory.current) for peak memory and memory.events to distinguish MLE from a crash. Writing 1 to cgroup.kill (Linux 5.14 and later) terminates every process in the group atomically, which is cleaner than chasing pids.
seccomp-bpf. After setting up namespaces and limits, and immediately before execve of the user program, the launcher sets no_new_privs and installs a seccomp filter. The filter is a tiny classic-BPF program evaluated on every syscall, with access to the syscall number, architecture and argument registers (not memory it points to, which is why filters cannot safely inspect path strings). An allowlist for a CPU-bound solution is short: read, write, exit_group, brk, mmap, munmap, mprotect, rt_sigaction, rt_sigreturn, clock_gettime, futex (for runtimes with threads), fstat, lseek, openat (restricted to read-only flags if argument filtering is used), and a handful of others the language runtime needs at startup. Everything else returns EPERM or kills the process. Different runtimes need different lists: the JVM and Go runtime use threads, madvise and signals heavily, so profiles are per language and are built by tracing the runtime with strace over a test suite, then reviewed.
gVisor. gVisor's main component, the Sentry, is a user-space program that implements the Linux system-call API: its own virtual filesystem layer, memory management, signals, and network stack (netstack). The sandboxed application's syscalls are redirected to the Sentry instead of the host kernel. Earlier versions offered a ptrace platform (slow) and a KVM platform; the newer systrap platform uses seccomp's trap mechanism to redirect syscalls efficiently, and it is now the default. File access goes through a separate helper process (historically called the Gofer) or through direct host file descriptors set up at start, so the Sentry itself runs with a very restrictive host seccomp policy. The security argument is about attack surface: the Sentry exposes the full Linux API to the guest but uses only a small subset of host syscalls itself, and it is written in a memory-safe language. The performance cost depends on syscall frequency: CPU-bound loops run at native speed, while code making millions of small syscalls (unbuffered I/O, for example) slows down noticeably, which is one more reason harnesses should buffer output.
Firecracker. Firecracker is a virtual machine monitor written in Rust that uses Linux KVM. Each micro-VM is one Firecracker process with an API socket for configuration. The design choices that make it fast and small:
- Minimal device model. virtio-net, virtio-block, virtio-vsock, a serial console and a stub keyboard controller. No PCI enumeration, no USB, no graphics, no BIOS: the guest kernel boots directly.
- Jailer. In production, each Firecracker process is started by a companion "jailer" that places it in its own namespaces and cgroup, drops privileges and applies a seccomp filter. So even a bug in the VMM itself is contained by a container-style sandbox: two layers, not one.
- Snapshots. A running micro-VM's memory and device state can be snapshotted and restored. Restoring many copies from one snapshot gives fresh VMs with a pre-initialised runtime (a started JVM, an imported Python interpreter) quickly; pages are loaded lazily from the snapshot file. Restoring identical snapshots duplicates any randomness state (random seeds, entropy pools) across clones, which matters for security-sensitive workloads and is a known caveat to handle.
Putting the layers in order. A judge launcher with defence in depth does, in sequence: create cgroup and write limits, clone with new namespaces, set up mounts and pivot_root, drop capabilities, switch to the unprivileged uid, set rlimits, set no_new_privs, install seccomp, then execve the harness. Outside, the worker starts a wall-clock timer and waits. Inside a micro-VM, the same sequence runs within the guest, so an attacker must escape the seccomp-restricted process, then the guest kernel, then the VMM (itself jailed), then the host's network policy, to get anywhere interesting.
Deep Dive: numbers worked throughShow
A more realistic per-submission cost. The planning figure of 100 ms per test is pessimistic. A typical medium problem has 60 tests: 50 small ones that take about 2 ms each in C++ (30 ms each in Python including per-test harness work) and 10 large ones close to the reference solution's runtime, say 150 ms in C++ and 1 s in Python.
C++ submission: compile 1.5 s + 50 × 2 ms + 10 × 150 ms ≈ 3.1 CPU-s
Python submission: 50 × 30 ms + 10 × 1,000 ms ≈ 11.5 CPU-s
Wrong answer on test 3 (most common case): ≈ 0.1 to 1.6 CPU-sWith fail-fast and the fact that more than half of submissions are rejected, the average lands around 3 to 5 CPU-s, a factor of 2 to 3 below the pessimistic planning number. Pre-scale for the pessimistic number anyway: under-provisioning a contest is costly, over-provisioning for 90 minutes is not.
Queueing intuition. Little's law says the average number in the system equals arrival rate times average time in the system: L = λ × W. If 170 submissions per second arrive and each spends 4 s being judged, about 680 are in progress at once, which needs 680 busy slots. Waiting time explodes as utilisation approaches 100 percent: for a pool of many servers, waits stay near zero up to roughly 80 to 90 percent utilisation and then rise steeply. So size the contest fleet so that peak utilisation is around 70 to 80 percent. For 1,700 busy cores at the pessimistic peak, that means about 2,100 to 2,400 cores, or about 150 sixteen-core workers with 14 slots each.
Drain time after a spike. Suppose a burst puts 30,000 submissions in the queue (a bad minute) and the fleet clears 400 per second beyond new arrivals. The backlog drains in 75 seconds. The last submission waits 75 seconds plus its own judging time. Showing a queue position makes this tolerable; recording acceptance time keeps it fair.
Leaderboard updates. 100,000 participants solving an average of 2.5 problems is 250,000 first-accepts in 90 minutes, about 46 per second on average, with peaks of a few hundred. Each update is a Lua script of five commands, so even 500 updates per second is 2,500 Redis operations per second, a small fraction of one instance's capacity.
Polling. 100,000 contestants polling the leaderboard every 5 s is 20,000 requests per second; with a 1 s micro-cache per API server and 20 API servers, Redis sees about 20 top-page reads per second plus 20,000 ZREVRANK calls per second (or fewer if "my rank" is also micro-cached for a couple of seconds). Each ZREVRANK is O(log n), about 17 steps for 100,000 members.
Storage of results. Storing per-test outcomes for every Submit (2.5 million Submits a day × 60 tests × 20 bytes) is 3 GB a day, about 1 TB a year. Most platforms store only the summary and first failing test, keeping per-test rows only for recent submissions or contests.
Image sizes. A full set of language images (GCC, Clang, JDK, Python, Node, Go, Rust, .NET and others) is often 5 to 15 GB. Pulling that from a registry at, say, 200 MB/s on a fresh instance takes 25 to 75 s, which is why images are baked into the machine image or pre-pulled.
Deep Dive: how real judges are builtShow
Several public systems show the same architecture from different angles. Details below are limited to what these projects document publicly; internal specifics of commercial platforms are not public.
- isolate and CMS. isolate is a small sandbox written for programming olympiads. It uses namespaces and cgroups and focuses on precise, repeatable time and memory measurement. The Contest Management System (CMS), used to run the International Olympiad in Informatics, runs submissions with isolate on a set of worker machines coordinated by central services. The olympiad world cares intensely about fairness, so it pioneered many of the measurement practices in Deep Dive 3.
- Judge0. An open-source code-execution service with an HTTP API. You submit source code, language and stdin, and get back a token; you then fetch the result by token, or ask for a synchronous wait on small jobs. Internally it queues submissions and runs them with isolate on workers. Its API shape (submit, get token, poll) is the same one this design arrives at.
- DOMjudge. An open-source system used for ICPC-style contests. Judging machines ("judgehosts") pull work from the central server over a REST API, run submissions under a resource-limiting wrapper, and report results back. The pull model is the same as our queue-leasing workers: the server never pushes work to judgehosts, which makes adding judgehosts mid-contest trivial.
- Codeforces and Polygon. Codeforces runs large rated contests with tens of thousands of participants. Its problem-preparation system, Polygon, formalises the test-authoring practices from Deep Dive 4: generators, validators, checkers and multiple reference solutions with expected verdicts (a solution tagged "should TLE" that passes is a flag that tests are weak).
- LeetCode-style platforms. The browser submits code, receives an id and polls a check endpoint until the result is ready, which is the polling model from Deep Dive 6.
- Serverless code execution. Products that execute user code at the edge or in functions (for example, sandboxes behind AI coding assistants) use micro-VMs or gVisor-style isolation, because they run arbitrary code with arbitrary libraries, often with some network access. Those requirements are stricter than a judge's, which can lean on its narrow workload (no network, fixed runtimes).
The recurring lessons: pull-based workers, an id-plus-poll API, a dedicated sandbox tool with careful measurement, and disciplined test authoring. None of them depend on exotic infrastructure.
Deep Dive: failure walkthroughsShow
1. The contest starts and the cloud cannot supply instances. Pre-scaling asked for 150 workers; the region had capacity for 90 of that instance type. Detection: the pre-scaler compares requested and running capacity at T minus 20 minutes and pages. Response, in order: request alternative instance types from a diversified list (any compute-optimised family with the same per-core performance, ideally already benchmarked so limits stay fair); borrow capacity from a second region whose workers can lease from the same queues; shrink practice traffic to the minimum. If capacity is still short, the queue absorbs the burst, users see queue positions, and acceptance-time ranking keeps the contest fair. As a last resort the organisers extend the contest or make it unrated, which is a product decision, not an engineering one, but engineering must supply the data (queue age over time) for it.
2. A sandbox escape is suspected. A host-level monitor sees an unexpected process outside any sandbox cgroup on worker 37. Response: the worker is automatically cordoned (stops leasing), its network access is cut and it is preserved for forensics, not rebooted. Its leased jobs time out and are retried on other workers. Because the judge zone is a separate account with a role that can only lease jobs, read code and write verdicts, the attacker's reach is limited to submissions that passed through that host recently and the ability to forge verdicts for them. Forged verdicts are caught by rejudging every submission that host judged in the window. Then: identify the exploit path (often a syscall that should not have been allowed), tighten the seccomp profile, patch, and recycle the whole fleet from clean images.
3. Redis fails over mid-contest. The leaderboard primary dies; a replica is promoted in seconds. Replication is asynchronous, so the last few hundred milliseconds of ZADDs may be missing. The fix is cheap: the Leaderboard Updater can replay accepted-verdict events from the last minute (they are in the durable event stream), and because updates are idempotent (first-accept check plus recompute), replaying is safe. Alternatively, a background reconciler recomputes the board from the database every few minutes during a contest and corrects any drift. Users at worst see a rank flicker.
4. A wrong test case is found 30 minutes into the contest. Contestants report that a clearly correct approach fails on test 23. The setter confirms the expected output is wrong. Response: publish a corrected bundle as a new version; workers pick it up because jobs name the version (new jobs get the new version once the contest problem record is updated); select all contest submissions on that problem judged against the old version and enqueue them for rejudge at high priority; the leaderboard updates as verdicts change; penalties for attempts that failed only because of the bad test are removed by recomputing from the database. Announce it to contestants. Versioned bundles and idempotent rejudges turn a crisis into a routine operation.
5. A poison-pill submission. A particular program triggers a bug in the container runtime that crashes the worker agent. Without protection, the job's lease expires and the next worker crashes too, and the job walks through the fleet. With a maximum receive count (say 3), the message goes to the dead-letter queue after three crashes, the submission is marked System Error, and an alert fires with the job id. Track "worker crashed while holding job X" separately from "job X failed": three crashes from one job is a strong poison signal.
6. The database primary fails over during the final minutes. Failover takes 30 to 60 seconds. During that window, the Submission Service writes accepted submissions to the queue with their server timestamp and a flag "row pending"; workers can judge directly from the message payload (code inline); verdicts are buffered and written when the database returns. The contest end time is enforced at the API using the server clock, so the failover does not let late submissions slip in or reject on-time ones.
Deep Dive: a 45-minute interview plan and common variantsShow
A time budget that works:
| Minutes | What to do |
|---|---|
| 0 to 5 | Requirements: browse, code in languages, submit, leaderboard. Non-functional: isolation, about 5 s feedback, 100,000-user contests, availability over consistency. Out of scope list. |
| 5 to 8 | Entities and API: Problem, Submission, Leaderboard; submit returns an id; poll for the result; server-side identity and time. |
| 8 to 18 | High-level design: problem read path with cache; submission path through a queue to an isolated worker fleet; Redis leaderboard. |
| 18 to 28 | Deep dive 1: where code runs (API server, VM, container, serverless, micro-VM) and the hardening layers. |
| 28 to 36 | Deep dive 2: contest burst math (10,000 × 100 × 100 ms), pre-scaling, queue, priorities, shedding order. |
| 36 to 42 | Deep dive 3: leaderboard with sorted set and composite score; polling versus push. |
| 42 to 45 | Wrap up: failure modes, what you would build next (rejudges, plagiarism, test harness). |
If the interviewer steers elsewhere (often to the test harness or to fairness), follow them; the plan is a default, not a script.
Variants and how the design changes:
- Live coding interview pad (CoderPad-style). Two people edit the same code and run it on demand. Execution is the same sandbox, but with lower volume and no contest. The new part is collaborative editing, which brings in operational transformation or CRDTs and WebSockets, as covered in the Collaborative Editor case study.
- Online IDE with persistent workspaces (Replit-style). Users install packages, run servers and keep files between sessions. The sandbox now needs network access (egress through a filtering proxy), persistent storage per user and long-lived sessions, which pushes strongly towards micro-VMs or gVisor and makes the scheduling problem about placing long-running workspaces, not short jobs.
- Code execution for an AI assistant. A model writes code and runs it to answer a question. Same isolation needs, but sessions are stateful (a notebook-like kernel) and must be cheap to start. Snapshotted micro-VMs fit well.
- CI system (build and test runner). Jobs are long (minutes), need network for dependencies, and produce artefacts. The queue and worker-fleet shape is the same, with caching of dependencies as the main performance lever.
- "Design the leaderboard only." Focus on Deep Dive 7: sorted sets, composite scores, rank queries, freeze, and, for very large boards, partitioning by score range, as in the Top-K case study.
- "Support 10 million concurrent contestants." Now the leaderboard read path needs a CDN and heavy micro-caching, the queue needs partitioning (multiple SQS queues or a sharded broker), the fleet spans regions, and submission storage shards by user. The architecture stays the same; each component scales horizontally.
Deep Dive: observability and SLOsShow
Service level objectives worth writing down:
- 99 percent of contest Submits get a verdict within 10 seconds of acceptance; 95 percent within 5 seconds.
- 99.9 percent of submission requests are accepted (202) during contests; zero contest submissions rejected for capacity reasons.
- Leaderboard staleness under 5 seconds at the 99th percentile.
- System Error rate below 0.1 percent of executions.
Metrics to emit (see Observability: Logs, Metrics and Traces):
- Queue: depth and age of oldest message per priority class; enqueue and dequeue rates; dead-letter count.
- Judge latency: time from acceptance to verdict, split into queue wait, sandbox acquisition, compile, run and report. Splitting is what tells you whether to add workers (queue wait) or fix the pool (acquisition).
- Sandbox health: cold versus warm start counts, start time percentiles, sandbox creation failures, OOM kills, seccomp violations (a sudden spike in violations is an attack or a broken profile).
- Verdict mix per language and per problem. A problem whose TLE rate jumps after a worker image change indicates a performance regression in the image; a problem with 0 percent acceptance after a test update suggests a broken test.
- Fairness: runtime variance of canary submissions across workers; any worker whose canary runtime drifts above the fleet median by more than 10 percent is quarantined.
- Leaderboard: updater lag (event time to
ZADDtime), Redis latency, micro-cache hit rate.
Tracing. Attach a trace id at the API and carry it through the queue message into the worker, so a single submission's journey (accept, enqueue, wait, lease, compile, each test, verdict, leaderboard update) appears as one trace. This is invaluable when a contestant reports "my submission took 3 minutes".
Logs. Workers log structured events per submission (never the full code in shared logs; code is user content and may be sensitive) and keep sandbox stderr only in truncated form.
Capacity tests. Before major contests, replay a recorded contest's submission stream at 2x speed against a staging fleet. That validates pre-scaling numbers, autoscaling reaction and queue behaviour under realistic language mixes. See Capacity Planning and Load Testing.
Key Takeaways#
- The core problem is running hostile code safely. Never run it in the API tier. Use a dedicated worker fleet and isolate every execution with a hardened container (no network, read-only root, tmpfs scratch, cgroup CPU, memory and pid limits, seccomp, no capabilities, non-root, timeout), and move to gVisor or Firecracker micro-VMs when you need a stronger kernel boundary.
- Keep the expected answers outside the sandbox. Feed inputs in, capture outputs, compare outside. Treat the compiler as attacker-facing too.
- Decouple with a queue. Submit returns 202 and an id; workers lease jobs with visibility timeouts; at-least-once delivery plus idempotent verdict writes; dead-letter queues for poison pills; priority classes so contests stay fast.
- Poll for results, progressively. Polling the check endpoint with backoff and a queue position is simple, robust and good enough; push channels are for streaming progress.
- Rank with a Redis sorted set and a composite score (solved count scaled up, minus finish time and penalties). Micro-cache the top page, compute "my rank" with
ZREVRANK, and always recompute final standings from the database. - The contest burst is scheduled, so pre-scale. Size from registrations (10,000 Submits × 100 tests × 100 ms means about 1,700 cores), bake images, warm sandbox pools, and let the queue absorb the remainder. Shed practice and background work first, never contest submissions.
- Fairness is a requirement. CPU time plus wall-clock limits, pinned cores, uniform hardware, calibrated per-language limits, server-side timestamps, acceptance time as ranking time, versioned tests and rejudges.
- Right-size it. A modular monolith, one relational database, a Redis instance and an isolated judge fleet cover LeetCode-scale traffic. The scarce resource is CPU during contests, not storage or request rate.