Build a Live Programming Competition Judge at Scale
System DesignModel answerLast updated
Architect a platform where tens of thousands of contestants submit code during timed contests, with sandboxed grading, fast verdicts and a continuously updated ranking.
Build a Live Programming Competition Judge at Scale
You are asked to design the backend for a service that hosts timed programming competitions. Many people compete at once. Each contestant reads the problem set, writes a solution in a language of their choice, and sends it in. The platform runs that code against test cases the contestant cannot see, reports a verdict, and keeps a ranking table current for everyone.
What the system must do
- Let users sign up for a contest and read its problems.
- Accept solutions in several languages (for example Python, C++ and Java).
- Run every submission inside an isolated environment so that hostile code cannot harm the platform or other users.
- Keep a single, contest-wide ranking that changes as verdicts arrive.
Quality targets
- Cope with a very large simultaneous load at the opening of a contest (think 50,000 active participants).
- Return verdicts with low delay.
- Stay healthy through sudden bursts of traffic.
What to deliver
- A written description of the overall architecture (components and data flow).
- API design covering submitting code and reading the ranking.
- Your approach to safely executing untrusted code.
- A data model for submissions and scoring.
- How you would scale the grading pipeline.
State your assumptions (scoring rules, contest size, submission rate) and justify the numbers you pick.
Hints
Hint 1
Start by fixing a scoring rule and a rough load estimate (participants, submissions per user, peak submissions per second, CPU time per grading run). These numbers decide how big the grading fleet must be.
Hint 2
Separate accepting a submission from judging it. A fast acknowledgement plus a durable queue lets you absorb bursts, and workers can be scaled independently of the web tier.
Hint 3
Treat all submitted code as hostile and layer defenses: a strong isolation boundary, resource caps, syscall filtering, no network, disposable environments. For the ranking, think about a structure that supports ordered insertion and rank lookup without sorting the whole table each time.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model answer
1. Assumptions and sizing
I would confirm these with the interviewer first, since everything downstream depends on them.
- Scoring: ICPC style. Rank by number of problems solved, then by lowest total penalty. Penalty for a solved problem is the minutes elapsed at the accepted submission plus 20 minutes per earlier rejected attempt on that problem.
- Scale: 50k participants, 2 hours, around 5 problems, about 10 submissions each, so roughly 500k submissions per contest.
- Shape of load: Bursty. At the start, 50k people load problem statements simultaneously (read-heavy, cacheable). Near the end, submissions spike. I plan for about 500 submissions/s at peak.
- Grading cost: 10 to 50 tests per problem, 1 to 2 s limit each. Average about 2 CPU-seconds per submission, worst case about 20. At peak that is about 500 x 2 = 1,000 cores, so the judge fleet must autoscale.
- Latency goals: Accept in under 200 ms, verdict in under 10 s at p95, leaderboard reflects the verdict within a few seconds.
2. API
POST /contests/{cid}/problems/{pid}/submissions
Headers: Authorization, Idempotency-Key
Body: { "language": "cpp17", "source": "..." } # size cap, e.g. 64 KB
-> 202 Accepted { "submission_id": "...", "status": "QUEUED" }
GET /submissions/{sid}
-> { "status": "RUNNING|AC|WA|TLE|MLE|RE|CE", "tests_passed": n, "time_ms": ..., "memory_kb": ... }
WS /contests/{cid}/stream # pushes this user's verdicts and ranking changes
GET /contests/{cid}/leaderboard?offset=0&limit=50
GET /contests/{cid}/leaderboard/me
- Return 202 immediately; grading is asynchronous.
- An idempotency key prevents a retry or double click from creating a duplicate, which would otherwise inflate penalties.
- Push verdicts over WebSocket or SSE. 50k clients polling every second would behave like a self-inflicted DoS.
3. Architecture
Client -> CDN (statements, static files)
-> Load balancer -> API gateway (auth, rate limits) -> Submission service
1. store source in object storage
2. insert submission row (QUEUED) in Postgres
3. enqueue {submission id, language, problem, test version}
|
Queue (Kafka/SQS, partitioned by language)
|
Judge workers (autoscaled, one sandbox per run)
|
Verdict topic -> Result service
-> update Postgres (submissions, scores)
-> update Redis sorted set (ranking)
-> notification service (WebSocket fan-out)
Postgres is the source of truth. Redis holds a derived view that can be rebuilt. Messages on the queue carry only IDs; source code lives in object storage.
4. Data model
contests(id, title, start_at, end_at, scoring_type)
problems(id, contest_id, title, time_limit_ms, memory_limit_kb, active_testset_version)
test_sets(problem_id, version, storage_prefix, checksum, created_at)
registrations(contest_id, user_id, registered_at)
submissions(id, contest_id, problem_id, user_id, language, source_key,
submitted_at, -- server time at ingress; used for penalty
status, testset_version, time_ms, memory_kb, judged_at)
-- index (contest_id, user_id, problem_id, submitted_at)
problem_scores(contest_id, user_id, problem_id,
solved, wrong_attempts, accepted_at)
-- PK (contest_id, user_id, problem_id)
500k inserts per contest is easy for Postgres. The per-verdict upsert into problem_scores is keyed by (contest, user, problem), so contention is limited to one user's own rows. Recording testset_version on each submission makes regrading reproducible.
5. Secure execution
Assume every submission is malicious and layer defenses.
- Isolation: gVisor or Firecracker microVMs rather than plain containers, which share the host kernel. Firecracker boots in about 125 ms.
- cgroup limits: pin one CPU core for stable timing, cap memory with swap off, set
pids.max(about 64) against fork bombs, cap output size and disk quota. - Time limits: a CPU-time limit for TLE and a wall-clock limit (about 2x) to catch sleeping or blocked programs; kill with SIGKILL.
- Syscall filtering: a seccomp allowlist that denies
socket,ptrace,mount, and similar. - Network and filesystem: no network, read-only root with tmpfs scratch, non-root user, all capabilities dropped.
- Separate compile and run phases, each with limits, since template bombs and enormous includes are real attacks.
- Ephemeral sandboxes on dedicated nodes with no database credentials. Workers read tests via pre-signed URLs or a local cache and emit results only to the queue.
To hide start-up cost (a JVM alone takes about 300 ms), keep a warm pool of pre-created sandboxes per language.
6. Ranking
Sorting 50k rows in SQL on every verdict is far too expensive. Use one Redis sorted set per contest with a composite score:
score = solved * 10^7 - penalty_seconds
ZADD lb:{cid} score user
ZREVRANGE lb:{cid} offset offset+limit-1 # a page: O(log N + limit)
ZREVRANK lb:{cid} user # a user's rank: O(log N)
Penalty stays under 10^7 seconds, so the value fits exactly in a double. For deterministic tie-breaking, either encode the time of the last accepted submission into the score's low-order digits or resolve ties at read time. Rebuild the set from problem_scores after a Redis failure. Cache the top pages for a second or two to absorb read bursts; per-user rank lookups stay cheap.
7. Scaling the grading pipeline
- Queue as shock absorber: bursts lengthen the queue instead of crashing the system. Autoscale workers on queue depth and oldest-message age, not CPU.
- Priority: separate queues or priorities for contest traffic versus practice or rejudges, so background work cannot starve live contests.
- Pre-warming: scale up before the contest starts and before the final-hour surge; reactive scaling is too slow for VM start-up.
- Test locality: cache test data on workers keyed by checksum.
- Early exit: stop at the first failing test for a non-AC verdict, and run small tests first.
- Fairness: per-user rate limits (for example one submission every few seconds) and per-user queue caps.
- Reliability: at-least-once delivery with idempotent verdict writes keyed by submission ID; a visibility timeout so a crashed worker's job is retried; a dead-letter queue for repeatedly failing jobs; a retry for infrastructure failures that never counts as a wrong attempt.
8. Common mistakes
- Running user code in a plain Docker container on the same hosts as the API.
- Grading synchronously inside the HTTP request.
- Computing rankings with SQL
ORDER BYper update. - Polling for verdicts rather than pushing.
- Using client timestamps for penalty.
- Ignoring duplicate submissions and non-idempotent verdict handling.
- Scaling on CPU instead of queue depth.
Trade-offs
Firecracker gives stronger isolation but slower start and more overhead than gVisor; the warm pool narrows the gap. Redis gives fast ranking but is eventually consistent with Postgres, which is acceptable because the database remains authoritative and the view is rebuildable.