Video in progress

How do you design an online judge (like LeetCode) that runs code submitted by users: isolation, queueing and scale?

The code never runs on the API server: a submission goes into a queue, and workers run it in a sandbox (such as gVisor or Firecracker) with no network and limits on CPU, memory and time. The result comes back asynchronously, and for contest peaks the queue and the workers scale separately.

📖 Answer

The central risk of this system is that you're running arbitrary code from strangers on your own servers. while(true), a fork bomb, 10 GB of memory, attacks on internal services over the network, reading the file system: all of it shows up in the first week.

The flow:

  1. POST /submissions takes the code, language and problem ID. The server only saves it (QUEUED), puts it on the queue and returns a submissionId.
  2. A worker takes it from the queue, compiles and runs the tests in a sandbox, and updates the state with the result (ACCEPTED, WRONG_ANSWER, TLE, MLE, RE).
  3. The client gets the result through SSE/WebSocket or polling.

Isolation, in layers:

  • a plain container isn't enough, since the kernel is shared. gVisor or a Firecracker microVM gives a stronger boundary;
  • cgroups limit CPU, memory and process count; the file system is read-only, with only a small tmpfs;
  • no network at all, and seccomp blocks dangerous syscalls;
  • two kinds of time limit: CPU time and wall-clock time (for ones that hang on sleep), and the process is killed if either is exceeded;
  • a clean environment for each submission, and the worker machines are themselves recreated from time to time.

Fair measurement. Parallel tests on one machine affect each other's timing: give each sandbox a dedicated CPU core, and re-measure the slow ones. JVM languages like Java have a startup cost, so use separate time limits per language.

Scale. On a normal day there are few submissions, and when a contest starts there are 50 times more. Autoscale on queue length and keep a pool of pre-warmed sandboxes, because bringing up an environment takes time. Contest submissions go in a higher-priority queue than practice.

Data. Big test files sit in object storage with a local cache on the workers. When the tests change, store which version an old result was checked against.

Cheating. For plagiarism, a background job analyzes code similarity; against hardcoded answers, hidden tests.

The main idea is a three-way separation: the API answers fast, heavy work goes in the queue, and dangerous work goes in the sandbox.