Skip to content

Design LeetCode

A system design interview walkthrough for LeetCode, covering sandboxed code execution, a judge queue, fair verdicts, contest spikes and standings.

Intermediate24 minUpdated 2 December 2026

Before this: Application Security, Message Queues, Back-of-the-envelope Estimations

"Design LeetCode" is a security question wearing a product costume. The product, a site where people read a problem, submit code and get a verdict, is easy to sketch. The hard part is one sentence: you are going to run strangers' code on your machines.

Anyone can submit a program that reads your environment, opens network connections, forks until the machine dies, allocates all the memory, writes to disk forever or tries to escape to the host. The interviewer wants to see that this is the first thing you worry about, and that your design makes the safe path the default, not a feature.

The second theme is load shape. Traffic is a modest hum most of the week and then a contest starts: tens of thousands of people hit Submit at nearly the same time, and everyone is watching the clock. Because contests are scheduled, you can plan for them, which is the insight that earns credit.

Clarify the requirements

Functional requirements:

  1. Browse problems and read a statement with examples.
  2. Write code in several languages and Run it against the example tests.
  3. Submit code to be judged against hidden tests, and receive a verdict: Accepted, Wrong Answer, Time Limit Exceeded, Memory Limit Exceeded, Runtime Error or Compile Error.
  4. See your submission history, runtime and memory.
  5. Take part in scheduled contests with a live ranking.

Out of scope, said aloud: plagiarism detection, a rich online editor, discussion forums, premium subscriptions and the mock-interview product.

Non-functional requirements:

  • Safety above all. No submission can read secrets, reach the network or internal services, affect another submission, or survive its run.
  • Fast verdicts: about 2 to 5 seconds for a normal submission, longer for heavy problems.
  • Fair, repeatable verdicts. The same code should get the same verdict and a similar runtime, whatever machine it lands on.
  • Survive contest spikes without losing or mis-ordering submissions.
  • Hidden tests stay hidden. Leaking test data ruins a problem.

Estimate the scale

Assume 2 million daily active users, each running or submitting code about 15 times a day. Each execution takes about 3 seconds of wall time on a worker (start the sandbox, compile if needed, run up to 50 test cases). A stored submission (source plus verdict) is about 5 KB.

Executions: 2M × 15 = 30 million a day ÷ 86,400 s ≈ 347 per second.

Contest peak: contests are scheduled, and a large one makes traffic about 5× normal for its hour: 347 × 5 ≈ 1,735 per second.

Sandboxes in flight: by Little's law, rate × time = 347 × 3 ≈ 1,040 sandboxes running on average, and 1,735 × 3 ≈ 5,200 at the contest peak.

Machines: assume a 16-core worker runs about 12 sandboxes at once, leaving cores for the system and keeping timing fair. That is 1,040 ÷ 12 ≈ 87 machines on average and 5,200 ÷ 12 ≈ 433 at contest peak.

Reads: problem pages, submission lists and standings, say 40 a user a day: 80M ÷ 86,400 ≈ 926 per second, almost all cacheable.

Storage: 2M × 15 × 5 KB = 150 GB a day, about 55 TB a year. Problem data is tiny by comparison: 3,000 problems × 50 test cases × 100 KB is about 15 GB, small enough to keep a copy on every worker.

"The web tier is ordinary: about 1,000 reads a second, mostly cacheable. The expensive and dangerous part is execution: 347 a second normally, 1,700 in a contest, each in its own throwaway sandbox. The key moves are strong isolation, a queue between the web tier and the workers, and scaling workers up before a contest begins."

See the numbers move in the capacity estimator.

API and data model

GET  /v1/problems/{slug}                                 -> statement, examples, limits
POST /v1/problems/{slug}/run     { language, code, input? } -> { runId }
POST /v1/problems/{slug}/submit  { language, code }         -> { submissionId }
GET  /v1/submissions/{id}                                  -> { status, verdict, runtimeMs, memoryKb }
GET  /v1/contests/{id}/standings?page=                     -> ranked rows
problem     (slug PK, statement, time_limit_ms, memory_limit_mb, test_manifest_version)
submission  (submission_id PK, user_id, problem_slug, language, code_ref, status,
             verdict, runtime_ms, memory_kb, created_at)
test_data   (problem_slug, version, test_id) -> input, expected_output   // object storage
contest_score (contest_id, user_id) -> solved, penalty, last_accept_at

The submit call returns an id immediately, and the client polls (or listens on a stream) for the verdict. Judging is asynchronous, which is what lets a queue absorb a spike.

High-level design

We simulate the judging path: a gateway, the submission API, a judge queue, a pool of judge workers and the results store.

Submissions pass a gateway to an API that queues them, and a judge worker pool runs each one against test cases and saves the verdict.codersgatewaysubmission apijudge queuejudge workersresults store
Submissions pass a gateway to an API that queues them, and a judge worker pool runs each one against test cases and saves the verdict.
  • The submission API stores the code, returns an id and puts a job on the judge queue.
  • Judge workers lease jobs, run them in sandboxes and write the verdict to the results store.
Describe this diagram

Components

  • coders (Client)
  • gateway (API gateway)
  • submission api (Service)
  • judge queue (SQS queue)
  • judge workers (Service)
  • results store (PostgreSQL)

Connections

  • coders sends to gateway
  • gateway sends to submission api
  • submission api sends to judge queue
  • judge queue sends to judge workers
  • judge workers sends to results store

Run it, then drop the judge workers or raise the load: the submit call stays fast while the queue grows, which is exactly the behavior a contest needs.

The write path: the API validates the language and code size, writes the submission as queued, enqueues a job with a reference to the code, and returns the id. A judge worker leases the job, fetches the code and the problem's tests, runs them in a sandbox, writes the verdict and updates the contest score if there is one.

The read path: clients poll GET /submissions/{id}, which is a primary-key read from the results store. Problem pages and standings come from a cache.

The interesting problem: running untrusted code safely

There are three levels of isolation worth discussing, and the interview is about choosing deliberately.

Approach A: run it in the judge process

Spawn a child process on the worker with a timeout.

Good: it is fast and trivial to build.

Bad: it is unsafe by construction. The code runs with the worker's permissions: it can read the code of other submissions and the hidden tests, call internal services, send your secrets over the network and fork-bomb the host. A timeout is not a security boundary.

Approach B: one container per submission, tightly limited

Run each submission in a fresh container with strict settings.

Good: much better. Namespaces isolate processes and the filesystem; cgroups cap CPU, memory and process count; a read-only root filesystem with a small writable scratch area stops disk abuse; a seccomp profile blocks dangerous system calls; the network is disabled; it runs as an unprivileged user; and the container is destroyed afterwards.

Bad: containers share the host kernel. A kernel bug can let a determined attacker escape, and escape means the judge machine, and from there every other submission and the test data.

Approach C: a stronger boundary, plus defense in depth

Put a second wall between the code and the host kernel: a microVM (such as Firecracker) or a user-space kernel (such as gVisor) per submission, with approach B's limits inside it. Then add layers outside:

  • No secrets on judge machines, and no network route to anything but the queue and the results API, which sit behind an allowlist.
  • A separate account or network for the judge fleet, so a breach cannot reach production data.
  • Ephemeral everything. One sandbox per run, never reused, destroyed on exit, so nothing persists between submissions.
  • Compile inside the sandbox too. Compilers can be abused (include a huge file, expand templates endlessly, run code at compile time), so compilation gets the same limits.
  • Hard limits everywhere: CPU time, wall time, memory, process count, file size, output size (a program that prints gigabytes should be cut off at a few MB).
Conceptual diagramdestroyed after runJudge queueJudge worker agentFresh microVM or gVisor sandboxCompile with limitsRun tests with limitsVerdict and metricsGone
Diagram, as text
  • Judge queue leads to Judge worker agent
  • Judge worker agent leads to Fresh microVM or gVisor sandbox
  • Fresh microVM or gVisor sandbox leads to Compile with limits
  • Compile with limits leads to Run tests with limits
  • Run tests with limits leads to Verdict and metrics
  • Verdict and metrics leads to Judge worker agent
  • Fresh microVM or gVisor sandbox leads to Gone (destroyed after run)

This is the answer to aim for. The point to say aloud is that a timeout and a container are not a security model, they are the first of several layers, and that you assume the code is hostile and the sandbox may eventually fail, so a failure must have nothing valuable to reach.

The second decision: fair verdicts, and who gets served first

Two design decisions keep verdicts trustworthy and the system usable.

Measure CPU time, not wall time, on isolated cores. If a submission is judged while a neighbor hogs the machine, its wall-clock time doubles and a correct solution gets Time Limit Exceeded. So charge CPU time, pin each sandbox to its own cores, and cap the number of concurrent sandboxes below the core count (the 12-on-16 above). For borderline cases, re-run a Time Limit Exceeded verdict once on a quiet machine before telling a user they failed. Different languages get different multipliers (a Python limit is a multiple of a C++ limit) because the benchmark is the algorithm, not the language.

Prioritize in the queue. A normal queue is first-in, first-out, but not all work is equal:

  • Contest submissions go first during a contest, because the clock is running and rank depends on timing.
  • Run (example tests) is quick and interactive, so it gets its own small queue with a short timeout.
  • Practice submissions fill the remaining capacity and can wait during a contest.
  • Add per-user limits (say 1 submission every 5 seconds and at most 3 in the queue) so one script cannot occupy the fleet. This is the rate limiting lesson applied.

Contests are scheduled, so unlike most spikes this one is predictable. Scale up the judge fleet 15 minutes before the contest begins, using the expected participant count. Do not rely on reactive autoscaling for a spike that arrives in one minute.

Bottlenecks and failures

A sandbox escape. Assume it can happen and limit the blast radius: no secrets on workers, a network allowlist, a separate account, short-lived workers replaced every few hours, and alerts on any sandbox that tries a blocked system call. Never test hidden data on a machine that also holds anything else of value.

Fork bombs and memory hogs. The process-count and memory cgroups handle them. The verdict is Runtime Error or Memory Limit Exceeded, and the sandbox is killed and discarded. No other submission notices.

A worker dies mid-judging. Jobs are leased with a timeout (see the message queue lesson). If the lease expires, the job returns to the queue and another worker judges it. Judging is idempotent: it only produces a verdict, so running twice is harmless, as long as the first result is the only one recorded for a submission.

Queue backlog in a contest. If the queue age passes 10 seconds, alert and add workers. Show users "in queue, position N" so they know it is working, and never drop jobs. Order matters for ranking, so use the submission's created time as the tiebreaker.

Standings at scale. 50,000 people refreshing a ranking is a read storm. Keep standings in a sorted structure (a Redis sorted set keyed by score and penalty) and cache the first pages for a few seconds. The pattern is the one in design a gaming leaderboard.

Test data leaks. Never put hidden tests in the sandbox's reach longer than needed. Mount only the current test's input, compare output outside the sandbox where you can, and show a failing case to the user only for the example tests.

What if the results store is down? Verdicts are computed but cannot be saved. Workers hold them briefly and retry, and polls return "judging". If the outage lasts, the jobs return to the queue and re-run.

Trade-offs to name aloud

  • Stronger isolation: a microVM costs more startup time and memory than a container, and removes a whole class of escape risk.
  • Warm pools: faster verdicts for idle machines you pay for.
  • Asynchronous judging: the user waits a few seconds, in return for a queue that absorbs a spike.
  • Re-running a TLE: a longer verdict for borderline cases against unfair failures.
  • Pre-scaling for contests: paying for capacity early, so the first minute does not fail.

What interviewers listen for

  • A working answer: an API, a queue, a pool of workers that run code in containers with time and memory limits, and a results store.
  • A strong answer: names the threats (network, disk, fork bombs, escape), combines cgroups, seccomp and no network, sizes the fleet by concurrent sandboxes and uses asynchronous judging.
  • A standout answer: adds a microVM or gVisor layer and a blast-radius plan, measures CPU time on pinned cores, prioritizes contest traffic, scales ahead of the schedule and protects hidden tests.

Check your understanding

Common mistakes

Treating a timeout as security. A timeout limits how long code runs, not what it can touch. Isolation is separate and needs several layers.

Letting the sandbox see the network. A submission that can reach your metadata service or internal APIs can steal credentials. Default to no network.

Compiling outside the sandbox. Compilers are programs that run input-controlled logic. Compile under the same limits as execution.

Judging synchronously. A web request that waits for execution fails exactly when load is highest. Return an id and use a queue.

Using wall-clock time. It makes verdicts depend on which machine was busy. Judge on CPU time with pinned cores.

Reactive scaling for a scheduled event. You know when the contest starts. Be ready before it does.

Practice

Ten minutes into a contest the judge queue is 40 seconds deep and rising. Contestants are complaining. What do you do, in order, and what do you tell them?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Separate what you can do in the next minute from what you fix afterwards. Protect the contest's fairness.

Show a strong answer

Add capacity first. Raise the worker count immediately. Warm pools mean new sandboxes start fast, and each machine adds about 12 sandboxes. Going from the planned 400 machines to 500 adds about 1,200 concurrent slots.

Shift priority. Pause or deprioritize practice submissions and "Run" requests from non-contestants so contest jobs get every slot. This frees capacity without buying any.

Check for a bad actor or a heavy problem. Look at the queue by user and problem. One problem with slow tests, or one user submitting repeatedly, could be eating the fleet. Per-user queue limits cap the damage.

Keep order and tell people. Submissions keep their created-at order, so ranking stays fair even when verdicts are delayed. Post a banner: "Judging is delayed, your submission time is recorded when you submit." Consider extending the contest by the delay.

Afterwards, compare actual participation with the forecast and raise the pre-scale number.

The pattern worth keeping: protect fairness first (order and timestamps), then add capacity, then investigate cause.

A user submits code that opens a socket to 169.254.169.254, the cloud metadata address, and prints whatever it gets. Explain how your design makes this harmless, and what you would check afterwards.

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Count the layers. No single control should be the only thing standing in the way.

Show a strong answer

Layer 1: no network. The sandbox has no network interface at all, so the connection fails immediately with an error. The verdict is Runtime Error.

Layer 2: nothing to find. Even if the network existed, the judge machines have no cloud credentials attached. Their identity can only read from the queue and write verdicts through a narrow API, so the metadata service has nothing valuable to give.

Layer 3: separate environment. The judge fleet lives in its own account and network, with no route to databases or production services.

Layer 4: detection. The attempt is logged: blocked system calls and connection attempts are recorded per submission and per user. Alert on patterns like this, and flag the account for review.

Afterwards: check that the sandbox's network really is disabled in the image, not only configured in the job (add a test submission that attempts a connection and expects failure on every deploy).

The pattern worth keeping: make the dangerous action impossible, make its success worthless and make its attempt visible.

Key takeaways

  • The product is easy, the execution is dangerous. Start with isolation.
  • Layer your defenses: cgroups, seccomp, no network, a microVM or gVisor boundary and nothing valuable on the machines.
  • Judge asynchronously. Return an id, queue the job and let workers lease it.
  • Size by concurrent sandboxes: about 1,000 on average and 5,000 at contest peak.
  • Measure CPU time on pinned cores, so a verdict does not depend on a noisy neighbor.
  • Contests are scheduled. Pre-scale and prioritize contest jobs.

Further reading

  • Alexandru Agache and colleagues, "Firecracker: Lightweight Virtualization for Serverless Applications" (NSDI, 2020): microVMs designed for running untrusted workloads.
  • gVisor project documentation, "What is gVisor?": a user-space kernel that narrows the host attack surface.
  • Linux man pages, cgroups(7), namespaces(7) and seccomp(2): the kernel features behind container limits.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track