Build a Secure Remote Code Grading Service for Contests
System DesignModel answerLast updated
Design a distributed service that safely runs untrusted submissions against hidden tests, returns verdicts reliably, and stays responsive during contest traffic bursts.
Scenario
You are asked to design a platform where programmers write a solution to a problem, submit it in one of many languages, and get an automatic verdict after the code is run against a private set of tests. Think of the grading backend of a competitive programming site.
What the system must do
- Accept a submission (source code, language, target problem, optional contest).
- Compile it if the language requires it, run it against the hidden tests, and report one of:
Accepted,Wrong Answer,Time Limit Exceeded,Runtime Error, orCompilation Error. - Let users look up their past submissions.
Quality requirements
- Security: the submitted code is hostile by assumption. It must not be able to read files, reach the network, or harm the host or other users.
- Speed: verdicts should arrive quickly, and the platform must survive the surges that happen at the start and end of a contest.
- Scale: thousands of submissions in flight at once.
- Durability and consistency: an accepted submission is never lost, and its verdict is stable and stored reliably.
What to cover in your answer
- A text description of the high-level architecture.
- The API for submitting code and retrieving results.
- Your sandboxing approach for running untrusted programs.
- The data model and storage choices.
- How you keep the system healthy under peak load.
State your assumptions about scale (users, submissions per second, work per submission) and justify your choices with rough capacity math and trade-offs.
Hints
Hint 1
Start with numbers: estimate peak submissions per second times average CPU-seconds per submission to get the size of the worker fleet. This tells you the design must be asynchronous and elastic.
Hint 2
Separate accepting a submission from judging it. Persist the submission first, then enqueue it, and let workers pull jobs so that load shows up as queue depth rather than errors.
Hint 3
Assume any single isolation layer can be broken. Think in layers: a stronger boundary than a plain container, no network, restricted syscalls, cgroup limits, and output caps. Then map each verdict to a concrete signal the sandbox can report.
Hint 4
Queues deliver at least once. Think about what happens when a worker crashes mid-run or two workers finish the same job, and how a conditional state update plus retries and a dead-letter queue handle it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and capacity
- About 10M registered users; a big contest has around 50K participants online.
- Steady state is roughly 50 submissions/s; contest peaks reach about 1,000/s, clustered at the start and in the last minutes.
- Each submission runs 20-100 tests with a 1-2 s limit per test, but most fail early or finish quickly, so assume about 2 CPU-seconds on average.
- Peak load is 1,000/s x 2 CPU-s, or about 2,000 busy cores. That means a few hundred worker machines that must scale elastically.
- Targets: p50 verdict in about 5 s normally; during contests tens of seconds of queueing is acceptable, but a lost submission is not.
- Roughly 10-20 languages, code at most 64 KB, test data private.
2. API
POST /v1/problems/{problemId}/submissions
Idempotency-Key: <client-generated>
{ "language": "cpp17", "code": "...", "contestId": "optional" }
-> 202 { "submissionId": "...", "status": "QUEUED" }
GET /v1/submissions/{id}
-> { status: QUEUED|COMPILING|RUNNING|DONE,
verdict: AC|WA|TLE|MLE|RE|CE|null,
runtimeMs, memoryKb, testsPassed, testsTotal, compileOutput }
GET /v1/users/me/submissions?problemId=&cursor=&limit=20
- Return 202 right away because judging is asynchronous.
- An idempotency key prevents duplicates from double clicks and client retries.
- Clients poll with backoff (500 ms, 1 s, 2 s...) or subscribe over WebSocket/SSE. Push cuts polling load noticeably during contests.
- History uses cursor pagination, not offsets.
3. Architecture
Client -> CDN/LB -> API gateway (auth, rate limit)
-> Submission service -- write PENDING --> Submissions DB
\-- enqueue --> Queue (per language, per priority)
| pull
Judge workers (sandboxes, local test cache)
| verdict
Result service -> DB + Pub/Sub -> WebSocket gateway
Object store (versioned test data)
- The queue absorbs spikes: bursts become depth, not failures.
- Queues are split by language so workers keep the right toolchain warm, with a contest lane at higher priority than practice.
- Workers pull work only when they have a free slot, which gives natural backpressure.
- Test data lives in object storage, versioned, and is cached on worker disks by
(problemId, testVersion).
4. Sandboxing (the core)
Use defense in depth and assume each layer can fail.
- Boundary: plain Docker shares the host kernel, so prefer gVisor (user-space kernel) or Firecracker microVMs (hardware virtualization, about 125 ms boot).
- Namespaces: separate PID, mount, network, IPC, and user namespaces; no network interface; non-root UID.
- Filesystem: read-only root with only the toolchain, a size-capped tmpfs for binaries and scratch, read-only test input.
- seccomp allowlist: deny
ptrace,mount, raw sockets, and limitfork/clone. - cgroups v2:
cpu.maxfor one core,memory.maxwith swap disabled,pids.max(e.g. 32) against fork bombs. - rlimits: cap output file size, open files, and CPU time to stop disk and log flooding.
- Compile separately with its own limits (e.g. 10 s, 512 MB) to contain template bombs and giant includes.
Verdict detection
| Verdict | Signal |
|---|---|
| CE | Compiler exits non-zero; return truncated stderr |
| TLE | CPU time from cpu.stat over limit, plus a wall-clock watchdog (about 2x) for sleeping or blocked programs |
| MLE | oom_kill in memory.events |
| RE | Non-zero exit or fatal signal (SIGSEGV, SIGFPE) |
| WA/AC | Compare with expected output (exact or token-based); special checkers for float tolerance or multiple valid answers, also sandboxed |
Stop at the first failing test to save compute.
Timing consistency: pin each sandbox to a dedicated core, disable SMT and turbo (or normalize), avoid noisy neighbors, and re-run tests that land within about 5% of the limit before declaring TLE.
5. Data model
- Submissions, sharded by
user_idfor history, with a global index onsubmission_id: id, user, problem, contest, language, code reference, status, verdict, runtime, memory, tests passed, attempt count, timestamps. A relational store (Postgres with Vitess, or Spanner) fits because state transitions need transactions. Inline code up to 64 KB; larger goes to the object store. - Problems: per-language limits, test version, checker reference.
- Test cases: immutable per version in a private bucket, never exposed to clients.
- Leaderboard: Redis sorted set fed by verdict events, persisted to the database.
6. Reliability
Delivery is at least once, so design for duplicates and crashes:
- Write the DB row before enqueueing, so a submission is never lost. A sweeper re-enqueues rows stuck in
PENDING. - Workers write results with a conditional update (
WHERE status != 'DONE'), making duplicate completions harmless. - Use a visibility timeout so a crashed worker's job is redelivered.
- After N failed attempts, route to a dead-letter queue and alert.
7. Handling peaks
- Autoscale workers on queue depth and age of the oldest message, with a pre-warmed pool before scheduled contests.
- Priority lanes so contest traffic is not starved by practice submissions.
- Per-user rate limits and a cap on in-flight submissions per user.
- Early exit on first failure, and optionally cache verdicts for identical code plus problem plus test version.
- Push results instead of heavy polling; serve history from read replicas.
- Shed load gracefully: pause practice judging before degrading contest judging.
Trade-offs and common mistakes
- gVisor is lighter but slower on syscall-heavy code; Firecracker is stronger but costs more memory and startup. Many teams use microVMs for strongest isolation and warm pools to hide the boot cost.
- Mistakes: running code in plain containers, judging synchronously in the API request, relying only on wall-clock time, forgetting output limits, leaking test data to workers' logs or clients, and ignoring duplicate deliveries.