Design a Competitive Programming Practice Platform
System DesignModel answerLast updated
Design a scalable web platform where users can browse coding problems, run code in a sandboxed environment, and receive automatic judgement across multiple languages.
Build a Coding Practice Platform
You are tasked with designing a web-based platform where developers can sharpen their algorithmic skills. The platform needs to handle two very different workloads simultaneously: serving content to millions of users, and safely executing untrusted code on their behalf.
What the platform does
- Users register, authenticate, and maintain a profile.
- Users browse a library of coding problems, filterable by difficulty and topic.
- A browser-based code editor lets users write solutions in any of roughly 10 supported languages.
- Users can run code against custom input and see output immediately, or submit code to be judged against a hidden test suite.
- The judge returns a verdict: Accepted, Wrong Answer, Time Limit Exceeded, Memory Limit Exceeded, Runtime Error, or Compilation Error.
- The platform tracks each user's submission history and overall progress (problems solved, difficulty breakdown, etc.).
- An optional leaderboard ranks users globally or within a contest.
Constraints to assume
- 5 million registered users, up to 200,000 daily active users.
- Peak load: 10,000 code executions per minute.
- Roughly 5,000 problems in the library; test data for each problem is order-of-megabytes.
What is expected
Describe the system end-to-end. Cover:
- High-level architecture — major components and how they interact.
- Data model and storage choices — what goes in a relational DB, what goes elsewhere, and why.
- Code execution and sandboxing — how you isolate untrusted code, enforce limits, and scale the judge fleet.
- Caching and read performance — how you keep problem browsing fast under load.
- Trade-offs and evolution — what you would change as the system grows, and what you would consciously defer.
You do not need to cover payments, collaborative live coding, or discussion forums.
Hints
Hint 1
Start by separating the two workloads: read-heavy CRUD (browsing problems, viewing profiles) and CPU-heavy untrusted compute (running/judging code). They have completely different scaling strategies, so the cleaner you separate them early, the easier the rest of the design becomes.
Hint 2
For the execution layer, think about what makes a sandbox trustworthy vs just convenient. Plain Docker shares the host kernel — what is a stronger boundary? Then think about warm pools: what is the cold-start cost of a JVM, and how do you avoid paying it on every submission?
Hint 3
Async is the right model for code execution — the client should get an ID immediately and receive results via WebSocket or SSE. Once you commit to async, think through the failure modes: what happens if a worker dies mid-job, and how do you avoid charging the user a submission attempt for an infrastructure failure?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The central insight here is that one product contains two fundamentally different systems. Problem browsing is read-heavy, highly cacheable, and latency-sensitive. Code execution is CPU-intensive, security-critical, and throughput-limited. A strong answer separates these early and spends the majority of its depth on the execution side, because that is where the real engineering challenge lives.
Sizing the problem first
Before drawing any boxes, put numbers on the table.
- 10,000 executions/minute ≈ 170/second at peak.
- A typical submission compiles and runs against up to ~50 test cases, taking roughly 2–4 seconds of sandbox time.
- Concurrent sandboxes needed: 170 × 3 s ≈ ~500 at peak. Provision ~1,000 for headroom.
- At ~8 sandbox slots per 16-vCPU node, you need roughly 125 nodes at peak — but far fewer off-peak, so autoscaling matters a lot.
- Submission storage: 200k DAU × ~10 submissions × ~2 KB ≈ 4 GB/day, around 1.5 TB/year.
- Problem page reads: 200k DAU × ~50 views ≈ 10M/day, ~500 QPS peak, almost all cache-friendly.
The metadata footprint is small enough for a single relational primary plus replicas. The hard problem is the execution fleet.
API surface
Execution is asynchronous. The client receives an ID immediately; results arrive via WebSocket or SSE, with polling as a fallback.
GET /problems?difficulty=&tag=&q=&cursor= # paginated list with user's solved flag
GET /problems/{slug} # statement, samples, per-language templates
POST /problems/{id}/run {lang, code, input} # returns {run_id}
POST /problems/{id}/submit {lang, code} # returns {submission_id}
GET /submissions/{id} # status, verdict, runtime_ms, memory_kb
GET /users/{id}/stats # solved counts by difficulty and topic
GET /leaderboard?contest=&page=
Data model
Postgres holds users, problems, tags, and submissions. A few specific choices are worth calling out:
test_casesstores only a blob storage key (e.g., S3), never the raw content. Test inputs and expected outputs never touch the main database and are never exposed to clients.submissionsindexes on(user_id, problem_id, created_at). It grows at ~4 GB/day, so partition it by time from the start. Once it gets large, moving it to Cassandra or DynamoDB byuser_idis a reasonable migration path.- A separate
user_problem_statustable — keyed on(user_id, problem_id)— stores best verdict and first-solved timestamp. This denormalization powers "solved" checkmarks and progress stats without scanning the submissions table on every page load. - Problem search (full-text, tag, difficulty) is handled by Elasticsearch/OpenSearch, fed by CDC from the problems table.
High-level architecture
Client (Monaco editor)
│
CDN ── API Gateway (auth, rate limiting)
│
├── User/Auth service → Postgres
├── Problem service → Redis cache → Postgres / Elasticsearch
├── Submission service → Postgres / S3 (code blobs)
│ │
│ └── enqueue job → Queue (separate topics: run, submit, contest)
│ │
│ Judge workers (autoscaled)
│ │ sandbox pool
│ │ S3 test data (locally cached)
│ ▼
│ Result topic
│ ├── Submission service (persist, update stats)
│ └── Notification service (WebSocket push)
│
└── Leaderboard service → Redis sorted sets
Code execution — the core of the design
Isolation is the first concern. Plain Docker shares the host kernel, which is a weak boundary for hostile code. Use one of:
- gVisor (intercepts syscalls in userspace) — lower overhead, weaker isolation.
- Firecracker microVMs — stronger VM-level isolation, boots in ~125 ms, supports snapshot/restore for warm starts.
Layer additional defenses regardless of the container runtime:
seccompsyscall allowlists.- No network access whatsoever.
- Read-only root filesystem with a small
tmpfsfor output. - Non-root user inside the sandbox.
- cgroup limits on CPU, memory, and PID count — the PID cap is what stops fork bombs.
- External wall-clock timeout enforced by the host process, not inside the sandbox (a malicious program can ignore its own timer).
Judge nodes live in an isolated VPC with no credentials to production databases. Workers receive job payloads and return results only.
Performance of the execution layer:
- Maintain warm pools of pre-booted sandboxes per language. Cold-starting a JVM on every submission adds several seconds of latency.
- Cache test-case data on worker local disk, keyed by
(problem_id, version). Fetching from S3 on every run would dominate latency. - Compile once, then run all test cases in the same sandbox; exit on first failure for Submit jobs.
- Measure CPU time, not wall time, to avoid penalizing users for noisy-neighbor effects. Pin cores for fair measurement.
Reliability:
- Jobs are at-least-once. Result writes must be idempotent (keyed on
submission_id). - If a worker dies, the queue redelivers after the visibility timeout expires.
- Cap retries at 2–3, then mark the submission "Internal Error" so the user can resubmit without penalty.
Scaling:
- Autoscale workers on queue depth and age, not CPU utilization — a deep queue of small jobs may not spike CPU.
- Use separate queue topics so interactive Run jobs cannot be starved by a contest Submit flood.
- Per-user rate limits (e.g., 1 in-flight run, ~10/min) prevent a single user from monopolizing the fleet.
- Pre-scale before scheduled contests — contest start spikes are predictable and sudden.
Caching and read performance
- Problem pages are immutable per version. Serve from CDN and Redis; invalidate on publish. TTL can be long (hours to days).
- Per-user "solved" flags are fetched separately and merged client-side, keeping the main problem-list response cache-friendly.
- The filter space (difficulty × tag) is small enough to cache popular combinations as separate keys rather than invalidating the whole list.
- User stats come from
user_problem_status, not from aggregating submissions at query time.
Common mistakes to avoid
- Using wall-clock time as the execution timeout inside the sandbox. The user's code can spin-wait and defeat it. Enforce externally.
- Storing test cases in the database. They are large, binary, version-controlled blobs — object storage is the right home.
- Synchronous execution flow. Making the HTTP request block until the sandbox finishes ties up threads and caps throughput. Async with an ID-and-poll or push model is necessary.
- Flat submission table. Without time-based partitioning, queries slow down as the table grows, and you will not want to retroactively partition a 500 GB table under live traffic.
Evolution path
At early scale, a single Postgres instance, a managed queue (SQS), and a small autoscaling group of judge workers is sufficient. As load grows: separate read replicas for problem queries, migrate submissions to a wide-column store, increase sandbox warm-pool size, and eventually shard the execution fleet by language to avoid one slow language (e.g., Java compile) from affecting Python jobs.