Skip to content

How to design LeetCode

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Asked at
Practice this question

The problem

An online judge stores coding problems with hidden test cases, takes a solution in one of several languages, runs it against those tests and reports a verdict; during a contest it also ranks a crowd of people while scores keep changing. The answer turns on two facts about the workload. The code you run was written by strangers, so it has to run in a locked-down box that holds nothing of yours, well apart from the API server. A contest also sends thousands of submissions in the same moment, so a queue and a runner fleet that grows on demand sit between the API and that box, while the ranking lives in memory rather than in a sorted query.

Clarifying questions

AskWhy it mattersA typical answer

How is a submission judged: a function compared against expected outputs per test case, or a whole program reading standard input?

It decides what the runner needs: a small test harness per language that invokes the function and checks its outputs, or a program runner that pipes inputs and diffs stdout. The harness design shapes the sandbox interface.

A function per problem, with a code stub in each supported language and a set of test cases with expected outputs. The harness invokes the function and checks the result.

Which languages, and do any need a compile step?

A compile step adds time and a second thing that can be attacked (a compiler bomb), and the number of languages decides how many runner images you maintain.

Several mainstream languages. Assume one container image per language that can compile and run; the compile happens inside the same sandbox as the run.

How fast must a result come back, and how many people submit at once?

The gap between the normal case and the contest peak is where the design gets interesting: a fixed pool that meets the normal case is far too small for the peak.

Results within 5 seconds in ordinary use. In a 90-minute contest with 100,000 people, plan for 10,000 submissions landing at once, each with about 100 test cases.

Does the leaderboard need to be exact at each instant, or is a few seconds of lag fine?

An exact, instantly updated board pushes you toward faster delivery and a tighter coupling between the verdict write and the ranking; a few seconds of lag lets you poll an in-memory ranking.

A few seconds stale is acceptable. Availability matters more than consistency: the board must keep answering during the contest.

Are contests scheduled in advance?

A known start time lets you warm the runner fleet before the burst instead of reacting to it, which changes how you argue the scaling story.

Yes. Contests start at an announced time, and assume the heaviest burst comes right at the start, when the scenario has 10,000 people submit at once.

Is there a Run button that tries the sample tests without submitting?

If it exists, it shares the runner path and adds unscored executions on top of the ones you plan for, but it carries no score and no leaderboard write.

Treat it as optional. If you add it, it goes through the same queue and sandbox with a lower priority than scored submissions.

The requirements menu

RequirementScopeWhy

View a list of coding problems

Core

The entry point. Cheap to serve: a paged read of problem summaries that a cache in front of the database handles with ease.

View a problem and write a solution in one of several languages

Core

The problem page carries the statement and a code stub per language, so the Problem entity needs a stub per supported language, not one body of code.

Submit a solution and get the result

Core

The heart of the system and of this round: it is where untrusted code runs, and the path the contest burst hits.

View a live leaderboard during a competition

Core

It turns a batch judging system into something with a crowd reading one changing ranking, which is why it gets its own store.

Run the code against the sample tests without submitting

Optional

Worth a sentence: it reuses the queue and sandbox, so it costs little design. Leave the details unless asked, and say it would take lower priority than scored submissions during a contest.

Show the failing test case, runtime and memory for each submission

Optional

Useful feedback and easy to add because the harness already records the failing case and the runtime; memory needs one more measurement at the sandbox. Hiding the failing input during a contest is a product choice to mention.

A submission history per user and problem

Optional

A paged read of the Submission table by user. Take it if you have time: it adds an index, not a component.

Plagiarism detection across contest submissions

Out of scope

A batch job over the submission bodies after the contest ends. Name it, say it reads from the submissions store, and move on.

Rating changes and badges once a contest ends

Out of scope

Computed once from the final ranking. It does not touch the live path, so it is safe to park.

Sign-up, login and profiles

Out of scope

Ordinary account work. Keep a user id on each submission and take it from the session, not from the request body.

Payments

Out of scope

A premium tier is its own system and does not change how code is judged.

Social features and analytics

Out of scope

Discussion threads and usage dashboards are separate products that read from this one. Mention that submission events could feed an analytics pipeline, then stop.

Non-functional requirements

RequirementWhat it forces

Results come back within 5 seconds

The time a submission waits in the queue plus the time its tests run has to fit the budget, so one submission's test cases run in parallel inside its sandbox rather than one after another, and the status read is a lookup by submission id. At the contest peak the wait grows: say out loud that a short extra wait during a burst is acceptable, and size the fleet to keep it to about a minute.

User code runs isolated and cannot harm the system

Submitted code runs in a sandbox on separate machines from the API server, with no network, a read-only root file system, caps on CPU, memory, processes and wall time, and nothing in it but the code and its inputs. The piece that holds database credentials stays outside the sandbox.

Competitions of 100,000 users

A burst of submissions has to be absorbed by a queue and worked off by a runner fleet that grows for the contest, and the leaderboard has to be read tens of thousands of times a second from memory rather than computed by a sorted query.

Availability over consistency

The API accepts a submission by queuing it and answering at once, even when runners are behind. The leaderboard may lag a few seconds and may be rebuilt from the submissions table if the Redis copy disappears. The problems list can be served from a cache that is slightly behind an edit.

Estimates

QuantityWorkingResultWhat it sizes

CPU time to judge the contest peak

10,000 submissions × 100 test cases = 1 million test runs. Assuming about 100 ms of CPU per test run: 1 million × 0.1 s = 100,000 CPU-seconds, about 28 CPU-hours

Roughly 100,000 CPU-seconds of judging, arriving in one moment

The runner fleet: this is the work that has to be spread across cores, and the figure that drives the rest of the contest story.

Cores to clear the peak

To finish in about a minute: 100,000 CPU-seconds ÷ 60 s ≈ 1,667 cores needed. To finish inside the 5 second target instead: 100,000 ÷ 5 = 20,000 cores

About 1,667 cores for a minute's wait; about 20,000 to hold the 5 second target through the burst

The autoscaler's target during a contest, and the honest statement that the 5 second target is for ordinary load, with a short queue wait accepted at the peak.

CPU time of one submission

100 cases at 100 ms each = 10 s of CPU if the tests run one after another; spread across 4 worker processes inside the sandbox, about 2.5 s

About 10 CPU-seconds per submission, about 2.5 s of wall time with 4 workers

The harness design: tests within one submission must run in parallel, or the 5 second target fails even with an empty queue.

Runner hosts at the peak

Assuming hosts of 64 cores: 1,667 ÷ 64 ≈ 26.05, so round up to 27 hosts

About 27 hosts of 64 cores (26 falls a few cores short)

The warm pool to start ahead of an announced contest, and how many machines the autoscaler must be allowed to add.

Leaderboard reads a second

100,000 contestants ÷ 5 s between polls = 20,000 reads/s. Polling every 2 s in the closing minutes: 50,000 reads/s. Polling every 10 s early on: 10,000 reads/s

About 20,000 reads/s, rising to 50,000 near the end

The leaderboard read path: a ranking that has to come from memory, not from a ranking query against the submissions table.

Status polls during the burst

10,000 submitters × 1 poll per second = 10,000 reads/s for about a minute while their results arrive

About 10,000 reads/s of GET /check

The status endpoint: a primary-key read of one submission row, cheap enough that polling beats a push channel here.

Queue backlog at the peak

10,000 submissions × about 30 KB each ≈ 300 MB if the queue carried the whole code body; in this design the queue carries the submission id and the code stays in the submission row, so the real backlog is a small fraction of that

About 300 MB even if whole submissions were queued; far less with ids only

The queue: the backlog itself is small, so what you plan for the broker is durability and failover rather than storage.

Submissions stored per contest

100,000 users × 10 problems × about 3 attempts each = 3 million submissions × 30 KB ≈ 90 GB

Roughly 90 GB of submissions per contest

Submission storage: code bodies should move to object storage after a while, with the row keeping status, score and a pointer.

Core entities

EntityWhat it holds

Problem

One row per problem: the statement, a code stub for each supported language, and a pointer to its test cases.

Test case

An input and its expected output for one problem; sample cases are shown on the problem page, and hidden ones are read only by the execution service.

Submission

One attempt by one user at one problem: the code, the language, and what happened when it ran.

Competition

A scheduled window with a set of problems and the scoring rule for its leaderboard.

Leaderboard entry

A member of the per-competition sorted set in Redis: the user and a single score that encodes points and time.

The API

EndpointNotes

GET /problems?page=&limit= → problem summaries

A paged list of id, title and difficulty. Cache the pages: problems change rarely and the list is read by everyone who lands on the site.

GET /problems/{id}?language= → problem with code stub

Returns the statement, the sample cases and the stub for the requested language. Hidden test cases are not in this response, and the execution service is their one reader.

POST /problems/{id}/submit { code, language } → { submission_id }

The server takes the user id from the session and the timestamp from its own clock. It writes a row with status queued, enqueues the id, and answers 202 Accepted with the id before any code runs. Reject bodies over a size cap and rate-limit per user so one person's flood stays small.

GET /check/{submission_id} → status and results

A primary-key read of the submission row, polled about once a second by the client until the status is final. During a contest the failing input can be withheld and just the verdict returned.

GET /leaderboard/{competition_id}?page=&limit= → rankings

Reads a page of the sorted set and, when the caller is a contestant, their own rank and score in the same response. Polled every few seconds; the interval is a hint from the server so it can slow or speed the crowd.

The high-level design

submitdataBrowserAPI serverPostgres

Step 1 of 4

An API server and a database

Start with the ordinary part. One API service answers the problem list, the problem page and the submit and check calls, backed by a Postgres database that holds problems, their test cases and submissions. About 4,000 problems with their stubs is a small table; even the alternative figure of 100,000 problems at about 10 KB each is about 1 GB, so one database with a replica is plenty for the catalog. In this first cut the API server itself starts a container for the submitted code, waits for it and writes the verdict. That is where it breaks: the untrusted code runs next to the process that holds your database credentials, and a request thread blocks for the whole run.

submit, pollproblems, statusenqueueadd hostsload testscode, inputsverdictacceptedranksBrowserAPI serverPostgres:problems,submissionsSubmission queueExecution serviceAutoscaler onqueue depthSandbox: nonetwork,read-only,capsLeaderboardsorted set
The whole design

What breaks first

The deep dives

Running untrusted code safely. Someone submits code that tries to delete files, open connections to the internet and run without stopping. Walk one such submission through the runner and name each thing that stops it.

A concept that helps here: Sandboxing untrusted codeA concept that helps here: Multi-tenant isolationA concept that helps here: Failing open or failing closed

Contest bursts. 100,000 people are in a 90-minute contest and 10,000 of them submit in the same moment, each with about 100 test cases. What runs their code, how many cores does it take, and how does each result get back to the browser?

A concept that helps here: Backpressure and load sheddingA concept that helps here: Queues and logsA concept that helps here: Retries and dead-letter queues

A live leaderboard. 100,000 contestants refresh the leaderboard every few seconds while scores keep changing. How does it stay fast, how does it change when a submission passes, and how stale may it be?

A concept that helps here: Sorted sets and leaderboardsA concept that helps here: WebSockets, server-sent events and pollingA concept that helps here: Cache invalidation and TTLs

Concepts this guide uses

Sources

  1. DEV Community: Docker container security hardening, rootless, seccomp, AppArmor and read-only filesystems
  2. Claude Code documentation: Securely deploying AI agents
  3. OneUptime: How to implement Docker container security context
  4. Fly.io: Firecracker vs gVisor, how each isolates untrusted code
  5. AWS Lambda developer guide: Understanding the Lambda execution environment lifecycle
  6. Redis documentation: ZADD
  7. Redis documentation: ZREVRANK
  8. OneUptime: How to use Redis sorted sets for leaderboards and rankings
  9. KEDA documentation: RabbitMQ Queue scaler
Sign in to report a mistake