Live Competitive Programming Contest Backend

Medium · System Design · Software Engineer · Technical Screen

Prompt

Architect the backend infrastructure for a live competitive programming service that hosts scheduled global coding tournaments. During an active event, tens of thousands of developers write and submit solutions in languages such as C++, Java, Python, and Go, which the platform compiles and evaluates against private test suites while updating a live tournament scoreboard.

Your design must satisfy the following functional and operational constraints:

  • Code evaluation & verdicts: Competitors submit source files against a tournament problem; the backend compiles and executes the program across hidden test inputs under strict CPU, memory, and runtime ceilings, returning an authoritative verdict (Accepted, Wrong Answer, Time Limit Exceeded, Memory Limit Exceeded, Runtime Error, or Compile Error).
  • Hardened sandbox isolation: Every untrusted submission must execute inside a tightly locked-down sandbox with zero network connectivity and strict kernel/hardware caps so hostile code cannot compromise worker hosts or read expected outputs.
  • Deterministic scoring: Participant standings combine solved problem points, wrong-attempt penalties, and runtime tie-breakers deterministically, producing identical results even when worker verdicts finish out of submission order or retry after crashes.
  • Dual-view live standings:
    • A public top-100 leaderboard updated with under 2 seconds of end-to-end lag.
    • On-demand exact personal standing queries for any active entrant (for instance, reporting rank #11,280 out of 92,000 active competitors).
  • Scale & performance targets:
    • 100,000 simultaneous active competitors during a tournament.
    • Peak ingestion spikes of 5,000 submissions per second right after tournament start and in the closing minutes.
    • Maximum execution limit of 2 seconds per individual test case, with mean end-to-end judging turnaround below 10 seconds.
    • Crash resilience: evaluation node failures must never drop accepted submissions or leave scores inconsistent.

Scope & Expectations

  • End-to-end pipeline & schema: Walk through submission ingestion, durable persistence (contests, problems, submissions, judgments, and participant standings), asynchronous task queuing, score updates, and real-time client delivery.
  • Untrusted execution & fleet sizing: Explain the kernel/virtualization isolation primitives, pre-warmed worker pool management, and capacity strategy needed to absorb 5,000 submissions/second safely.
  • Leaderboard data structures: Detail how the ranking tier serves both < 2 s top-100 reads and exact arbitrary-rank lookups under heavy concurrent score writes.
  • Failure modes & operational edge cases: Cover worker crashes mid-evaluation, hostile submissions (process bombs, disallowed system calls, timing abuse), and mid-tournament test-case fixes requiring targeted re-evaluation.

Step-by-step walkthrough

  1. Clarify requirements, scoring rules, and scope

    Accepting source code over HTTP is easy. Three engineering challenges make an online coding competition platform hard:

    1. Hostile multi-tenancy at scale: executing 50,000 untrusted programs simultaneously without letting any submission crash a host, spy on hidden test cases, open network connections, or distort another competitor's CPU timing.
    2. Deterministic scoring under chaos: producing the exact same score no matter what order worker verdicts arrive in, which machine crashed mid-run, or whether a problem's test suite was fixed mid-contest.
    3. High-write, dual-mode leaderboard: serving both the global top 100 within 2 seconds and any participant's exact personal rank (#11,280 out of 92,000) while thousands of verdicts land every second.

    Functional requirements

    • Submission & automated judging: entrants send C++, Java, Python, or Go source files for a tournament problem. Workers compile and run the binary against private test suites under strict CPU, RAM, and runtime ceilings, emitting AC (Accepted), WA (Wrong Answer), TLE (Time Limit Exceeded), MLE (Memory Limit Exceeded), RE (Runtime Error), or CE (Compile Error).
    • Locked-down sandboxes: untrusted binaries execute with network interfaces stripped and rigid kernel resource limits.
    • Order-independent scoring: standings reflect solved problem points, wrong-attempt time penalties, and CPU runtime tie-breakers deterministically.
    • Dual-view live standings: public top-100 leaderboard refreshed under 2 seconds, paired with exact personal standing queries for every active entrant.

    Non-functional requirements

    • Tournament scale: 100,000 simultaneous active entrants; bursts of 5,000 submissions/second at the opening bell and during the closing rush.
    • Turnaround budget: at most 2 seconds of CPU time per test case; below 10 seconds mean end-to-end judging turnaround.
    • Crash durability: lost worker nodes never drop accepted submissions or corrupt tournament standings.
    Clarifying question Concrete assumption Why it matters for the design
    Exact scoring formula? ICPC-style with points: each solved problem awards its points; its penalty is ac_submitted_at_s + 20 min x prior_wrong_attempts (WA, TLE, MLE, RE; CE is free). Unsolved problems add zero penalty. Ties break by lower penalty, then lower sum of accepted cpu_ms Scores depend on all prior attempts before the first AC, so out-of-order verdicts must be handled carefully
    Which timestamp counts for penalty? The timestamp when the API accepted the submission (submitted_at), never when a worker finished judging it Queue backlogs or worker retries never penalize the participant
    Stop on first failing test? Yes: run tests 1..K sequentially and stop at the first failure, reporting failed_test Keeps average judging under 10 s and speeds up mid-contest rejudging
    Per-user submission limit? At most 2 in-flight (queued or running) submissions per participant Stops one script from flooding thousands of sandboxes
    Contest duration & ending? 2 hours; submissions accepted until end_at, standings marked FINAL once all in-flight and rejudge queues drain Clean separation between submission cutoff and final standings
  2. Back-of-the-envelope capacity math

    Start with Little's Law, a fundamental queueing formula stating that the average number of items simultaneously inside a system equals the arrival rate multiplied by the average time each item spends inside (in_flight = arrival_rate x time_in_system).

    1. Submission traffic
       Peak arrival rate       5,000 submissions/s (at start and final minutes)
       Contest total           100,000 users x ~20 submissions = 2,000,000 submissions over 2 hours
       Average arrival rate    2,000,000 / 7,200 s = ~280 submissions/s
       Peak-to-average ratio   5,000 / 280 = ~18x (short, predictable spikes!)
    
    2. Judge sandbox fleet (the dominant cost)
       Concurrent runs (peak)  5,000 sub/s x 10 s avg evaluation = 50,000 sandboxes busy at once
       CPU per sandbox         1 dedicated physical CPU core = 2 cloud vCPUs (a cloud vCPU is one
                               hyperthread — half of a physical core sharing caches and execution units;
                               pinning both sibling vCPUs prevents noisy-neighbor timing drift)
       Host sizing             128-vCPU host = 64 physical cores -> 56 sandbox cores + 8 cores for OS/agent
       Hosts at 100% load      50,000 / 56 = ~893 hosts
       Hosts with 25% headroom ~62,000 sandboxes / 56 = ~1,100 hosts at peak (absorbs runtime variance
                               and per-language skew)
       RAM per host            56 x (256 MB user limit + ~64 MB sandbox overhead) = ~18 GB (fits easily
                               inside standard 256 GB compute hosts, leaving room for 1 GB Java compiles)
    
    3. Ingestion, storage, and test data
       Source code bandwidth   avg 3 KB (max 64 KB) x 5,000/s = ~15 MB/s peak; 2M x 3 KB = ~6 GB/contest
       Object storage PUTs     5,000 PUTs/s -> hash-prefix keys ("a9/3f/...") to exceed S3's 3,500 PUT/s
                               per-prefix ceiling
       Database writes (peak)  5,000 submissions + 5,000 outbox rows + 5,000 judgments + <= 5,000 scores
                               = ~15,000-20,000 row writes/s across 4 Postgres shards
       Hidden test suites      6 problems x ~200 MB = ~1.2 GB per host -> ~1.3 TB pre-pulled 20 min early
    
    4. Leaderboard traffic
       Memory footprint        100,000 users x ~100 bytes = ~10 MB in one Redis Sorted Set
       Score updates           <= 5,000 ZADD/s (fewer with 200 ms batching)
       Top-100 reads           1 query/s published over WebSockets + cached 1 s at CDN (not 50,000/s!)
       Personal rank lookups   100,000 users / 10 s = ~10,000 O(log N) lookups/s + push on verdict
    

    What the numbers tell us: the leaderboard fits in 10 MB of RAM on a single Redis primary plus replica. Almost all infrastructure cost and risk sit in the 1,100-host judge fleet. Because contests start on a known schedule with prior registration, we pre-warm capacity 20 minutes before start_at instead of waiting for reactive autoscalers to catch an 18x spike.

  3. API design and client notification

    Every mutating endpoint requires an Idempotency-Key (a client-generated UUID per button click so retrying after a flaky network timeout returns the original submission instead of creating a duplicate attempt and a duplicate 20-minute penalty).

    POST /v1/contests/{contest_id}/problems/{problem_id}/submissions
      Idempotency-Key: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
      {"language": "cpp20", "code": "#include <iostream>\n..."}            # max 64 KB
      -> 202 Accepted
         {"submission_id": "sub_01J9Z...", "status": "QUEUED",
          "submitted_at": "2026-11-30T17:04:05.120Z"}
      -> 429 Too Many Requests {"error": "MAX_IN_FLIGHT", "retry_after_s": 3}
    
    GET  /v1/submissions/{submission_id}
      -> 200 {"status": "JUDGED", "verdict": "WA", "failed_test": 7, "cpu_ms": 412, "memory_kb": 38120}
    
    GET  /v1/contests/{contest_id}/leaderboard?top=100                      # CDN Cache-Control: max-age=1
      -> 200 {"as_of": "2026-11-30T17:04:12Z", "provisional_problems": [],
              "rows": [{"rank": 1, "user": "ana", "points": 2400, "penalty_s": 5410}]}
    
    GET  /v1/contests/{contest_id}/rank/me
      -> 200 {"rank": 11280, "out_of": 92000, "points": 900, "penalty_s": 7322}
    
    WS   /v1/contests/{contest_id}/live
      server -> client:
        {"type": "verdict", "submission_id": "sub_01J9Z...", "verdict": "AC", ...}
        {"type": "rank", "rank": 1840, "out_of": 92000, "points": 1400, "penalty_s": 6120}
        {"type": "top100", "as_of": "...", "rows": [...]}                   # broadcast once per second
    
    POST /admin/v1/problems/{problem_id}/rejudge
      {"suite_version": 4, "reason": "Fixed edge case in test 12"}
    

    Why this API shape works smoothly under load:

    • 202 Accepted + authoritative submitted_at: judging takes ~10 s asynchronously, and returning submitted_at immediately proves to the competitor which second counts for scoring.
    • WebSockets with HTTP polling fallback: a WebSocket is a persistent two-way connection over TCP that lets the server push events instantly. Pushing one verdict message when judging finishes avoids 100,000 browsers polling GET /submissions/{id} every second; if corporate Wi-Fi drops the WebSocket, the browser falls back to exponential-backoff HTTP polling.
    • CDN-cached public top 100: a CDN (content delivery network) caches identical public responses at edge servers worldwide. Because the top-100 JSON is identical for all 100,000 viewers, a 1-second CDN TTL collapses 50,000 browser refreshes/s down to 1 origin read/s.
  4. Data model and storage split

    PostgreSQL stores the durable source of truth, object storage (S3/GCS) holds source-code files and test-case blobs, and Redis holds a fast, disposable leaderboard view that can be rebuilt from PostgreSQL in seconds.

    CREATE TABLE contests (
      contest_id           bigint PRIMARY KEY,
      start_at             timestamptz NOT NULL,
      end_at               timestamptz NOT NULL,
      penalty_per_wrong_s  int  NOT NULL DEFAULT 1200,
      status               text NOT NULL            -- SCHEDULED, RUNNING, ENDED, FINAL
    );
    
    CREATE TABLE problems (
      problem_id       bigint PRIMARY KEY,
      contest_id       bigint NOT NULL,
      label            text   NOT NULL,             -- 'A', 'B', 'C', ...
      points           int    NOT NULL,
      time_limit_ms    int    NOT NULL,             -- e.g. 2000 ms CPU per test
      memory_limit_mb  int    NOT NULL,             -- e.g. 256 MB
      checker_type     text   NOT NULL,             -- TOKENS, FLOAT_1E6, CUSTOM_SANDBOXED
      active_suite     int    NOT NULL              -- active test_suites.version
    );
    
    CREATE TABLE test_suites (
      problem_id  bigint NOT NULL,
      version     int    NOT NULL,
      manifest    jsonb  NOT NULL,                  -- [{"test": 1, "in_uri": "...", "out_uri": "...", "sha256": "..."}]
      PRIMARY KEY (problem_id, version)
    );
    
    -- Sharded across 4 primaries by hash(user_id); shard ID is encoded in submission_id.
    CREATE TABLE submissions (
      submission_id    bigint PRIMARY KEY,
      contest_id       bigint NOT NULL,
      problem_id       bigint NOT NULL,
      user_id          bigint NOT NULL,
      idempotency_key  uuid   NOT NULL,
      language         text   NOT NULL,             -- cpp20, java21, python3, go122
      code_key         text   NOT NULL,             -- deterministic: "{hash_prefix}/{contest_id}/{user_id}/{idem_key}"
      submitted_at     timestamptz NOT NULL,        -- set once at ingestion; drives penalty calculation
      status           text   NOT NULL,             -- QUEUED, RUNNING, JUDGED, JUDGE_ERROR
      infra_failures   int    NOT NULL DEFAULT 0,
      UNIQUE (user_id, idempotency_key)
    );
    CREATE INDEX idx_sub_user_problem ON submissions (contest_id, user_id, problem_id, submitted_at);
    
    CREATE TABLE outbox (
      outbox_id      bigserial PRIMARY KEY,
      submission_id  bigint NOT NULL,
      queue_name     text   NOT NULL,               -- e.g. 'judge.live.cpp20'
      payload        jsonb  NOT NULL,
      created_at     timestamptz NOT NULL
    );
    
    CREATE TABLE judgments (
      submission_id  bigint NOT NULL,
      suite_version  int    NOT NULL,
      verdict        text   NOT NULL,               -- AC, WA, TLE, MLE, RE, CE
      failed_test    int,                           -- NULL when AC
      cpu_ms         int    NOT NULL,               -- max single-test CPU time
      memory_kb      int    NOT NULL,
      worker_id      text   NOT NULL,
      judged_at      timestamptz NOT NULL,
      PRIMARY KEY (submission_id, suite_version)    -- idempotent on retry; preserves history on rejudge!
    );
    
    CREATE TABLE participant_scores (
      contest_id     bigint NOT NULL,
      user_id        bigint NOT NULL,
      points         int    NOT NULL,
      penalty_s      int    NOT NULL,
      runtime_bucket int    NOT NULL,
      per_problem    jsonb  NOT NULL,               -- {"A": {"solved": true, "wrong": 1, "ac_at_s": 1305}}
      encoded_score  bigint NOT NULL,               -- 53-bit integer written to Redis ZSET
      is_provisional boolean NOT NULL DEFAULT false,
      updated_at     timestamptz NOT NULL,
      PRIMARY KEY (contest_id, user_id)
    );
    

    Three schema choices eliminate subtle bugs:

    • Deterministic code_key: deriving the object-storage key from (contest_id, user_id, idempotency_key) means uploading code before opening the SQL transaction is idempotent on retries and never holds a database connection open during blob I/O.
    • judgments keyed by (submission_id, suite_version): if a crashed worker's retry finishes twice, ON CONFLICT DO NOTHING makes the second write harmless; if Problem C is rejudged on suite_version = 4, new verdicts write alongside version = 3 instead of overwriting audit history.
    • participant_scores is 100% derived: both participant_scores and Redis (lb:{contest_id}) are pure projections of submissions + judgments.
  5. High-level architecture and message-broker choice

                           100,000 Participant Browsers
              HTTPS: submit, rank/me |                 ^ WebSocket: verdicts, personal rank, 1 Hz top-100
                                     v                 |
      [ CDN (1 s TTL: GET /leaderboard) ]      [ WebSocket Gateways x10 ] <---- Redis Pub/Sub ----+
                     |                                                                             |
                     v                                                                             |
      [ Load Balancer ] --> [ Submission API x20 ] ---> [ Object Storage: source code + tests ]    |
                                    |                                                              |
                                    | 1 SQL txn: INSERT submissions + INSERT outbox                |
                                    v                                                              |
                       [ PostgreSQL (4 shards by user_id) ]                                        |
                                    |                                                              |
                                    | Outbox Relay (polls/streams outbox, deletes after ack)       |
                                    v                                                              |
         [ Work Queues (RabbitMQ / SQS): judge.live.{cpp,java,py,go} + judge.rejudge.{...} ]       |
                                    |                                                              |
                                    | Pull 1 job when warm sandbox free; 120 s visibility lease    |
                                    v                                                              |
         [ ~1,100 Judge Hosts: Host Agent + Warm gVisor Sandboxes + Local SSD Test Suites ]        |
                                    |                                                              |
                                    | Report verdict                                               |
                                    v                                                              |
                       [ Results Service ] ---> INSERT judgments ---> [ Kafka: verdicts ]          |
                                                                      (key = contest_id:user_id)   |
                                                                           |               |       |
                                                                           v               v       |
                                                              [ Score Aggregator ]   [ Notifier ] -+
                                                                recompute score,
                                                                upsert Postgres,
                                                                pipelined ZADD
                                                                       |
                                                                       v
                                                         [ Redis Primary + Replica ]
                                                           lb:{contest_id} (ZSET)
                                                                       |
                                                 [ Leaderboard Publisher (1 Hz ZREVRANGE 0 99) ] --+
    

    Why decouple ingestion from evaluation with a message broker? During the opening minute and final rush, submissions spike to 5,000/s regardless of how long C++ templates take to compile or slow TLE loops take to run. Writing into a distributed broker lets the Submission API respond 202 Accepted in ~15 ms while workers drain jobs steadily at their exact sandbox capacity. To prevent a crash between COMMIT and publishing to the queue from stranding a submission in QUEUED, the API uses a transactional outbox (inserting an outbox row inside the same database transaction as submissions, which a background relay publishes to the broker and deletes only after broker acknowledgment).

    Why use a lease-based work queue for judging, and Kafka for verdicts?

    • Judging needs per-message leases (RabbitMQ or SQS): one submission might finish in 0.2 s (CE) while the next takes 35 s (TLE on test 18). In a classic Kafka consumer group (where progress per partition is tracked by a single sequential offset watermark), one slow 35-second job blocks offset commits for faster jobs behind it on the same partition, and redelivering only one crashed message requires side-Queues. A work queue with visibility timeouts (a temporary lease hiding a pulled message for 120 s, renewed every 15 s by worker heartbeats, automatically reappearing if the worker dies) fits uneven, multi-second tasks naturally.
    • Scoring needs per-user ordering and replay (Kafka): once a verdict is produced, it is tiny (~300 bytes) and fast (~2 ms to aggregate). Keying the verdicts Kafka topic by contest_id:user_id routes all verdicts for User u_42 to a single partition and single Score Aggregator consumer, eliminating concurrent race conditions on u_42's score while preserving a replayable log.
  6. Deep dive 1: Sandboxing untrusted code

    Every submission must be treated as hostile exploit code trying to fork-bomb the machine, scan internal cloud networks, or read the expected test outputs off disk.

    First, define the Linux isolation primitives we choose between:

    • Syscall (system call): the boundary call a program makes to ask the OS kernel to open files, allocate memory, spawn processes, or send packets.
    • cgroups v2 (control groups) & seccomp: kernel features that cap hardware resources (CPU, RAM, process count) and block forbidden syscalls, while still sharing the single host Linux kernel across containers.
    • gVisor (runsc): an application kernel written in memory-safe Go that runs in user space and intercepts the sandboxed program's syscalls itself, forwarding only a tiny, heavily restricted subset to the host OS.
    • Firecracker microVM: a lightweight virtual machine monitor using hardware virtualization (KVM) so each sandbox runs inside its own isolated guest Linux kernel.
    Isolation option Security boundary Escape requires Overhead & startup Infrastructure requirement
    Plain Docker (namespaces + cgroups + seccomp) Shared host Linux kernel 1 bug in any allowed host syscall Near zero Any cloud VM
    gVisor + cgroups (chosen) User-space Go kernel (Sentry) + host seccomp A gVisor bug chained with a host kernel bug in gVisor's tiny syscall surface Low for CPU-bound contest algorithms; higher on heavy file I/O Any standard cloud VM (no bare metal required)
    Firecracker microVM Hardware KVM hypervisor + separate guest kernel A KVM hypervisor escape bug ~125 ms boot (0 ms from warm pool), ~5 MiB RAM overhead Bare-metal instances or nested KVM virtualization

    Why gVisor (or Firecracker if bare-metal hosts are standard): plain Docker shares the host kernel with 56 hostile programs per machine — too thin a wall for arbitrary C++ pointer/syscall exploits. gVisor gives strong defense-in-depth on ordinary cloud VMs, while Firecracker is the drop-in upgrade on bare-metal fleets.

    Per-submission Sandbox Specification (single-use; destroyed after every submission!)
    ------------------------------------------------------------------------------------
    Identity        uid 65534 (nobody), zero Linux capabilities, PR_SET_NO_NEW_PRIVS
    Network         Isolated network namespace with NO network interfaces (not even loopback needed)
    Filesystem      Read-only rootfs (compiler/runtime image); code mounted read-only;
                    writable /tmp backed by 64 MB RAM-only tmpfs; RLIMIT_FSIZE = 64 MB
    Answer secrecy  Test inputs piped via stdin; expected output files NEVER mounted inside sandbox!
                    Stdout captured via host pipe capped at 64 MB -> Checker runs in a SEPARATE process
    CPU & fairness  cgroup v2 cpuset.cpus pinned to BOTH hyperthreads of 1 dedicated physical core;
                    cpu.max = 100% of 1 core; measure user+sys CPU time via cpu.stat
    Wall watchdog   Host kills entire cgroup (cgroup.kill = 1) at 2x time_limit_ms so sleep(9999) dies
    Memory          cgroup v2 memory.max = problem limit (e.g. 256 MB), memory.swap.max = 0 -> OOM = MLE
    Process cap     pids.max = 64 inside gVisor's emulated cgroup (higher for JVM threads) + larger
                    host-cgroup backstop covering gVisor's own Sentry/Gofer threads
    Compilation     Runs in a separate, stricter compile sandbox (10 s wall limit, 1 GB RAM, 64 MB binary)
    

    How each classic exploit fails safely:

    • Fork bomb (while(1) fork();): hits pids.max = 64 inside the sandbox (fork returns EAGAIN), burns out its 2-second CPU budget, and gets wiped atomically via cgroup.kill so zero orphan child processes survive.
    • Compile-time bomb (#include "/dev/random" or C++ template explosion): compilation runs in its own capped sandbox with a 10 s timeout and 1 GB RAM ceiling, returning CE cleanly.
    • Answer peeking or custom checker exploits: expected .out files live exclusively on the host SSD outside the submission's mount tree; if a problem uses a custom problem-setter checker, that checker runs in its own isolated sandbox too.
    • Noisy neighbors & timing fairness: pinning one whole physical core per sandbox ensures Participant A's cache-thrashing C++ code never shares L1/L2 caches or execution ports with Participant B's tight 1.95 s solution.
  7. Deep dive 2: Worker orchestration and warm pools at 5,000/s

    Pre-Contest Capacity Warm-Up (T - 20 min): contests are scheduled events. Twenty minutes before start_at, the cluster scaler provisions the ~1,100 judge hosts based on registered headcount, pulls the ~1.2 GB encrypted test-suite bundle from object storage onto each host's local NVMe SSD, and fills warm sandbox pools.

    Single-use warm pools: starting a sandbox and booting a Python interpreter or JVM on every job adds 150–600 ms of waste. Instead, each host agent maintains pre-booted idle sandboxes per language proportional to historical submission mix (e.g., 50% C++, 25% Python, 20% Java, 5% Go, dynamically rebalanced every minute based on queue depth). When a job arrives, code is injected into an already-warm sandbox; the instant the run finishes, that sandbox is destroyed and a fresh replacement warms in the background so zero files, memory pages, or JIT states ever leak between users.

    Pull-based execution with leased heartbeats: no central master pushes tasks to 62,000 slots. Each host agent pulls one message from judge.live.{lang} only when it holds a free warm sandbox for {lang}:

    1. Claim message with a 120 s visibility timeout; renew the lease every 15 s while judging.
    2. Fetch source code from object storage, compile in a compile sandbox, then stream test inputs 1..K into the run sandbox until all pass (AC) or the first test fails (WA/TLE/MLE/RE).
    3. Send the verdict to the Results Service (INSERT INTO judgments ... ON CONFLICT DO NOTHING + publish to Kafka verdicts), and only then ACK (delete) the queue message.

    Why peak provisioning beats deep queueing during final minutes:

    Option A: Provision full peak (~1,100 hosts, ~62,000 sandboxes >= 50,000 needed)
      -> Queue wait ~ 0-1 s; verdicts return in ~10 s even at 1:59:50!
    
    Option B: Provision half peak (~550 hosts, 25,000 sandboxes = 2,500 completions/s)
      -> During a 5,000/s burst, net backlog grows by 5,000 - 2,500 = 2,500 jobs/s.
      -> The 2-in-flight cap per user bounds total jobs at 2 x 100,000 = 200,000 (25,000 running +
         175,000 queued), reached at t = 70 s.
      -> Queue wait hits 175,000 / 2,500 = 70 s (+ 10 s run = 80 s total!), blocking users with 429s
         during the crucial final minute!
    
    Practical sweet spot:
      -> Run ~1,100 hosts for the first 20 min and final 20 min, scaling down to ~400 hosts mid-contest.
      -> Use cheap Spot/Preemptible VMs for 70% of burst capacity: a reclaimed Spot VM simply stops
         heartbeating, and its leased jobs automatically re-run elsewhere!
    
  8. Deep dive 3: Deterministic scoring and the Redis leaderboard

    Why naive incremental scoring (score += delta) fails: suppose User u_42 submits Attempt #1 at t = 100 s (a slow WA that runs 19 tests before failing on Test 20, taking 12 s to judge -> verdict arrives at t = 112 s), and submits Attempt #2 at t = 105 s (a fast AC taking 2 s -> verdict arrives at t = 107 s).

    t = 107 s   Attempt #2 (submitted_at = 105 s, AC) arrives FIRST!
                -> Recompute from known verdicts [(105 s, AC)]:
                   points = 500, wrong_before_ac = 0, penalty = 105 s.
    
    t = 112 s   Attempt #1 (submitted_at = 100 s, WA) arrives SECOND!
                -> Naive incremental logic sees "already solved, ignore WA" -> WRONG penalty (105 s)!
                -> Pure recomputation sorts all verdicts by submitted_at: [(100 s, WA), (105 s, AC)]
                   points = 500, wrong_before_ac = 1, penalty = 105 + 1200 = 1,305 s -> EXACT!
    

    On every verdict, the Score Aggregator reads all judgments for (contest_id, user_id, problem_id) on the problem's active_suite (at most a few dozen rows, indexed!) and recomputes that problem's score from scratch as a pure function:

    PENALTY_PER_WRONG_S = 20 * 60  # 20 minutes in seconds
    WRONG_VERDICTS = {"WA", "TLE", "MLE", "RE"}  # Compile errors (CE) carry no penalty
    
    
    def compute_problem_score(judgments):
        """Compute (solved, penalty_s, accepted_cpu_ms) from judgments sorted by (submitted_at_s, submission_id)."""
        wrong_attempts = 0
        for judgment in judgments:
            if judgment.verdict == "AC":
                penalty_s = judgment.submitted_at_s + wrong_attempts * PENALTY_PER_WRONG_S
                return True, penalty_s, judgment.cpu_ms
            if judgment.verdict in WRONG_VERDICTS:
                wrong_attempts += 1
    
        # Unsolved problems contribute zero points and zero penalty seconds.
        return False, 0, 0
    

    Packing 3 tie-breakers into one 53-bit Redis score: a Redis Sorted Set (ZSET) stores unique member strings (user_id) ordered by a single 64-bit IEEE 754 floating-point score. Internally, Redis pairs a hash table (user_id -> score) with an order-statistic skip list (a multi-level linked list whose forward pointers store how many elements each jump skips over, enabling both top-K slices and exact rank counting in O(log N) time — unlike a standard SQL B-tree where COUNT(*) WHERE score > x scans O(N) index entries). Because 64-bit floats represent integers with zero rounding loss up to 2^53 - 1 (9,007,199,254,740,991), we pack (points, penalty_s, runtime_bucket) into 53 bits:

    POINTS_BITS = 14   # up to 16,383 points
    PENALTY_BITS = 20  # up to 1,048,575 penalty seconds (~12.1 days)
    RUNTIME_BITS = 19  # up to 524,287 buckets of 10 ms CPU time (14 + 20 + 19 = 53 bits!)
    
    
    def encode_leaderboard_score(points: int, penalty_s: int, total_cpu_ms: int) -> int:
        """Pack higher-is-better standing into an exact 53-bit integer for Redis ZADD."""
        max_penalty = (1 << PENALTY_BITS) - 1
        max_runtime = (1 << RUNTIME_BITS) - 1
    
        clamped_penalty = min(penalty_s, max_penalty)
        # Bucket CPU time in 10 ms steps so 1-2 ms OS jitter does not randomly flip ties.
        runtime_bucket = min(total_cpu_ms // 10, max_runtime)
    
        # Invert penalty and runtime ("max - value") so larger numbers always rank higher.
        inverted_penalty = max_penalty - clamped_penalty
        inverted_runtime = max_runtime - runtime_bucket
    
        packed = (points << (PENALTY_BITS + RUNTIME_BITS))
        packed |= (inverted_penalty << RUNTIME_BITS)
        packed |= inverted_runtime
        return packed
    

    Redis commands, tie handling, and write-through durability:

    ZADD      lb:42 2196401815541 "u_42"        O(log N)        idempotent absolute score overwrite (pipelined
                                                                every 100-200 ms; NEVER non-idempotent ZINCRBY!)
    ZREVRANGE lb:42 0 99 WITHSCORES             O(log N + 100)  top 100 fetched once every 500 ms - 1 s
    ZREVRANK  lb:42 "u_42"                      O(log N)        0-based distinct position (breaks ties by ID)
    ZCOUNT    lb:42 (2196401815541 +inf         O(log N)        exact count of strictly higher scores ->
                                                                rank = ZCOUNT + 1 (tied users share rank!)
    ZCARD     lb:42                             O(1)            total active participants ("out of 92,000")
    
    • Why ZCOUNT + ZREVRANK both matter: ZREVRANK gives an O(log N) distinct index, while ZCOUNT(lb:42, "(" + my_score, "+inf") + 1 gives true competition ranking (1, 2, 2, 4) so two participants with identical points, penalty, and runtime bucket see the exact same rank!
    • Write-through over write-behind: the Aggregator writes participant_scores to PostgreSQL first, then pipelines ZADD to Redis in 100 ms micro-batches. Write-behind (writing Redis first and flushing to SQL later) risks losing official contest scores if Redis crashes; at <= 5,000 updates/s across 4 SQL shards, write-through easily meets our < 2 s top-100 budget (~150 ms verdict-to-Redis + 500 ms publisher tick + 100 ms WebSocket push + 1 s CDN TTL = <= 1.75 s worst case even for HTTP polling clients!).
  9. Failure handling, mid-contest rejudging, and scaling bottlenecks

    Failure mode or edge case What happens How the architecture recovers cleanly
    Judge host crashes mid-run Heartbeats stop; 120 s queue lease expires Another host pulls the job. judgments uses PRIMARY KEY (submission_id, suite_version) with ON CONFLICT DO NOTHING, and always re-emits the Kafka verdict before ACKing the queue
    Poison submission crashes host Rare gVisor or agent bug crashes host on one input Increment submissions.infra_failures when a lease expires without a verdict; after 3 infra crashes, mark JUDGE_ERROR (zero penalty!) and alert staff instead of crashing the whole fleet
    Score Aggregator crashes Kafka consumer rebalances partition contest:user New consumer replays from last committed offset; pure score recomputation + absolute ZADD make replays 100% idempotent
    Redis primary fails Replica promoted via Sentinel/Cluster in seconds Any replication-lag gap is healed by pipelining ZADD for all participant_scores updated in the last 60 s (or rebuilding all 100,000 rows in < 2 s)
    Contest ends (now >= end_at) Submissions rejected after end_at; queue still busy Scoreboard displays "Judging final submissions..." until live and rejudge queues hit 0, then flips contest status to FINAL

    Mid-contest rejudge without starving live submissions: suppose Test 12 of Problem C had a broken expected output and admins upload fixed suite_version = 4:

    1. Prune unnecessary reruns: because tests run sequentially 1..K and stop on the first failure, any submission that failed on unchanged Tests 1..11 under version = 3 is guaranteed to fail identically on version = 4 — copy its verdict forward! Enqueue only prior ACs and failures on Test >= 12.
    2. Isolated queues + bounded 10% slot budget: push rerun jobs into judge.rejudge.{lang}, prioritized by current high-rank participants first. Host agents dedicate at most 10% of sandbox slots (~6,200 slots) plus any idle slots not needed by judge.live.{lang}. Live submissions retain >= 90% of fleet capacity (~55,800 sandboxes > 50,000 peak demand), so live competitors experience zero extra wait! At ~10 s per rerun, 150,000 reruns finish in 150,000 x 10 s / 6,200 ≈ 242 s (~4 minutes), and even faster during mid-contest lulls.
    3. Provisional transition: flip problems.active_suite = 4, banner "Problem C rejudging", recompute each user's Problem C score using version = 4 once judged (falling back to provisional version = 3 meanwhile), and push WebSocket notifications to anyone whose verdict changed.

    Summary of scaling bottlenecks:

    • PostgreSQL write rate (~15k–20k/s peak): shard submissions, outbox, judgments, and participant_scores across 4 primaries by hash(user_id). Every hot-path read and write touches a single user on a single shard.
    • S3 request rate & test distribution: hash-prefix code keys (a9/3f/...) to scale object PUTs linearly, and pre-pull test suites 20 minutes before start_at so 1,100 hosts never stampede object storage at 00:00.
    • WebSocket fan-out: the Leaderboard Publisher sends 1 message every 500 ms to Redis Pub/Sub; 10 stateless WebSocket Gateways (~10,000 sockets each) serialize that buffer once and write it to local sockets.

Intuition & how it works

Think of an online coding contest like grading 100,000 live chemistry experiments during a timed exam while updating a giant stadium scoreboard. Every student hands in mystery chemicals that might catch fire (untrusted code), different experiments take anywhere from 1 second to 40 seconds to finish reacting, and the scoreboard must display both the top 100 leaders within 2 seconds and every student's exact personal rank (#11,280 out of 92,000). To survive safely, you stamp every submission at the front desk with the exact clock time it arrived (submitted_at), carry each beaker via a buffered conveyor belt (message queue) into a single-use blast-proof fume hood with the gas and internet disconnected (sandbox — a tightly isolated execution environment that blocks unauthorized file, process, and network access), and recompute each student's score from their complete timestamped receipt log rather than adding points in whatever order graders walk back.

Why does a naive implementation fall apart under contest load? First, running submitted code inside an ordinary process or default container lets a five-line fork() bomb freeze the host kernel or read the hidden .out answer files straight off disk. Second, updating scores incrementally (score += points, or Redis ZINCRBY) produces wrong penalties whenever a slow Wrong Answer finishes judging after a fast Accepted submission submitted 5 seconds later, and double-counts points whenever a crashed worker replays a message. Third, computing personal rank in SQL (SELECT COUNT(*) FROM scores WHERE score > my_score) scans up to 100,000 rows per query — at 10,000 rank lookups per second, that means a billion row comparisons per second!

Trace a concrete 4-event example where Competitor u_42 submits twice on Problem A (worth 500 points, 1,200 s penalty per prior wrong attempt) and verdicts finish out of order:

Event  Contest clock  What happens                                   Stored judgments & leaderboard state
-----  -------------  ---------------------------------------------  ----------------------------------------------------------
1      t = 100 s      u_42 submits Attempt #1 (idem_key = "k1").     submissions row saved (submitted_at = 100 s) + outbox row
                      Slow bug: runs 19 tests, fails WA on Test 20.  queued to judge.live.cpp20 (takes 12 s in gVisor sandbox).
2      t = 105 s      u_42 fixes bug, submits Attempt #2 ("k2").     submissions row saved (submitted_at = 105 s); picked up by
                      Fast solution: passes all 20 tests in 2 s!     a second warm sandbox on another dedicated physical core.
3      t = 107 s      Attempt #2 finishes FIRST (AC, 40 ms CPU).     Aggregator reads [(105 s, AC)] -> 500 pts, penalty 105 s.
                                                                     Packs 53-bit score -> ZADD lb:42 overwrites u_42's score.
4      t = 112 s      Attempt #1 finishes SECOND (WA on Test 20).    Aggregator reads sorted [(100 s, WA), (105 s, AC)] ->
                                                                     recomputes 500 pts, penalty = 105 + 1200 = 1,305 s!
                                                                     ZADD overwrites score; ZCOUNT (> score) + 1 gives exact rank.

Key trade-offs

  • gVisor vs. Firecracker microVMs vs. plain Docker containers. Plain Docker containers use Linux cgroups (kernel resource caps on CPU, RAM, and process counts) and seccomp (a kernel filter that blocks disallowed syscalls, the system calls programs make to request OS services), which have near-zero overhead but share one host Linux kernel across 56 hostile programs. gVisor inserts a memory-safe Go user-space kernel that intercepts syscalls before they reach the host OS and runs on standard cloud VMs, trading modest syscall overhead for strong isolation. Firecracker uses KVM (hardware-assisted kernel virtual machines) to give every run its own guest kernel with ~5 MiB memory overhead, trading away cloud VM flexibility because it requires bare-metal or nested-virtualization instances.
  • Single-use warm sandbox pools vs. cold starts or sandbox reuse. Keeping pre-booted idle sandboxes per language hides 150–600 ms of container and JVM/Python startup latency at the cost of a small idle RAM footprint. Destroying each sandbox immediately after one submission costs background replacement CPU, whereas reusing a sandbox across users risks leaking /tmp files, environment state, or warmed caches.
  • Planned peak capacity vs. deep queueing. By Little's Law (concurrent_items = arrival_rate x average_duration), 5,000 sub/s x 10 s = 50,000 concurrent runs requires ~1,100 hosts (with 25% headroom). Provisioning half that capacity saves machine hours but builds a 70-second queue wait and triggers 429 in-flight blocks during the decisive final minute; pre-scaling Spot/Preemptible VMs for the opening and closing 20 minutes captures nearly the same speed at much lower cost.
  • Lease-based work queue for judging vs. Kafka for verdicts. Variable 1–60 s judge runs fit a work queue (RabbitMQ or SQS) with per-message visibility timeouts (temporary leases that hide a message while a worker heartbeats and automatically re-expose just that message if the worker dies), avoiding head-of-line partition blocking. Short, uniform verdicts fit Kafka (an append-only partitioned log) keyed by contest_id:user_id so one consumer processes each user's score updates sequentially and can replay cleanly on crash.
  • Pure score recomputation vs. incremental counters. Re-reading a user's <= 30 judgments on a problem and overwriting Redis with an absolute ZADD costs a tiny indexed SQL read per verdict, in exchange for 100% immunity against out-of-order verdicts and duplicate message deliveries.
  • 53-bit packed score in a Redis Sorted Set (ZSET) vs. SQL ordering. A ZSET pairs a hash map with an order-statistic skip list (a layered linked list tracking span counts on forward pointers so both top-100 slices and exact rank counts run in O(log N) time). Packing (points, inverted_penalty, inverted_runtime) into 53 bits fits without rounding inside Redis's IEEE 754 float64 (64-bit floating-point format, which stores every integer up to 2^53 - 1 with exact integer precision), trading fixed bit ceilings (14 + 20 + 19 = 53 bits) for microsecond rank queries.
  • Write-through vs. write-behind leaderboard updates. Writing PostgreSQL first and pipelining Redis ZADDs every 100 ms keeps official standings crash-safe and rebuildable within our < 2 s SLA, whereas write-behind (writing Redis first and flushing to SQL asynchronously) risks losing contest results if Redis fails.
  • WebSocket push + CDN caching vs. client polling. Pushing verdicts over WebSockets (persistent two-way TCP streams) and serving the public top-100 JSON behind a 1-second CDN (content delivery network edge cache) collapses 50,000 redundant origin reads/s down to 1 Redis ZREVRANGE every 500 ms–1 s, at the cost of running 10 stateless WebSocket gateway nodes.

Common mistakes

  • Treating a default Docker container as a security boundary: sharing an unfiltered host kernel across untrusted C++ programs leaves hundreds of kernel syscalls exposed.
  • Mounting expected .out test answers inside the sandbox: clever user code will simply scan the filesystem, read the expected output, and print it to stdout. Keep expected outputs strictly outside the sandbox and run custom checkers in a separate sandbox.
  • Timing wall-clock elapsed time on shared vCPUs: one cloud vCPU is typically a single hyperthread (one of two virtual threads sharing a single physical CPU core's caches and pipelines). Co-locating two competitors on sibling hyperthreads makes a 1.95 s solution randomly TLE whenever its neighbor thrashes memory; pin both sibling hyperthreads (1 full physical core) per sandbox and measure cgroup CPU time.
  • Computing wrong-attempt penalty from judged_at instead of submitted_at: queueing delays during peak bursts then add unfair penalty seconds to competitors' scores.
  • Using ZINCRBY or ZREVRANK naively: ZINCRBY double-counts on retries and breaks on out-of-order verdicts, while ZREVRANK breaks ties alphabetically by user_id instead of awarding tied participants the same rank (ZCOUNT of strictly higher scores + 1).
  • Dual-writing to PostgreSQL and the job queue without a transactional outbox: crashing after COMMIT but before queue.publish() strands submissions in QUEUED forever. Save an outbox row in the same SQL transaction and relay it asynchronously.
  • Packing 64 bits into a Redis ZSET score: integers above 2^53 silently round in IEEE 754 float64, scrambling runtime and penalty tie-breakers.
  • Pushing mid-contest rejudges into the live submission queue: dumping 150,000 rerun jobs into judge.live.* starves live competitors for minutes.

Follow-up questions

  • What defenses stop hostile code from spawning runaway processes, invoking restricted kernel calls, or leaking data via timing side channels? Enforce pids.max = 64 inside the sandbox's own gVisor cgroup so fork() immediately fails with EAGAIN, backstopped by a host-level pids.max, a 2-second CPU quota, and a 4-second wall-clock watchdog that wipes the entire process group atomically via cgroup.kill so no child process escapes. Disallowed syscalls (ptrace, mount, socket, bpf) are blocked first by an in-sandbox seccomp allow-list and second by gVisor's user-space Go kernel, terminating violators as RE and flagging accounts that repeatedly probe blocked syscalls. For timing side channels, address both hardware leaks and test-oracle leaks: pin one whole physical core (both hyperthreads) per sandbox so co-located submissions never share L1/L2 caches, and prevent competitors from extracting hidden test inputs bit-by-bit (e.g., intentionally triggering TLE if input bit k is 1) by returning detailed runtime/test numbers only on sample tests, charging 20-minute penalties per failed submission, and capping submission rates.
  • Suppose participation grows to several million competitors and write load overwhelms one Redis node—how can you shard or estimate personal ranks while keeping the global top 100 exact? Hash-partition the leaderboard by hash(user_id) across K = 16 Redis primaries, coalescing each user's score changes in 200 ms aggregator windows so each shard absorbs only 1/16 of batched ZADD writes. Anyone in the global top 100 must have fewer than 100 people ahead of them globally and therefore fewer than 100 ahead of them in their own shard, so taking ZREVRANGE 0 99 from all 16 shards (1,600 candidates) and merging the top 100 every 500 ms yields a 100% exact global top 100! For exact personal rank on demand, scatter-gather 1 + sum(ZCOUNT(shard_i, "(" + my_score, "+inf")) across all 16 shards in parallel (16 fast O(log(N/16)) calls). To avoid running scatter-gather on every dashboard refresh for 5 million tail users, maintain a tiny replicated in-memory score histogram bucketed by (points, penalty_minute) (~20 KB total) that computes approximate rank locally in O(1) time to within a single bucket's width, reserving exact scatter-gather for top contenders and explicit profile clicks.

text Exact global top 100 : merge top 100 from each of 16 shards (1,600 rows) every 500 ms Exact rank on click : 1 + sum_{i=1..16} ZCOUNT(shard_i, "(" + score, "+inf") Fast UI rank refresh : prefix sum of replicated (points, penalty_minute) histogram - If organizers patch a broken test case halfway through an active contest, how do you re-evaluate prior submissions without delaying fresh incoming attempts? Store the corrected test suite as immutable suite_version = 4 (never overwriting version = 3, since judgments uses PRIMARY KEY (submission_id, suite_version)). First, prune redundant work: because tests execute sequentially 1..K and stop at the first failure, any submission that failed on an unchanged earlier test (failed_test < 12) will fail identically and needs no re-execution. Second, enqueue remaining candidates into dedicated judge.rejudge.{lang} queues ordered by current top-ranked participants first, and configure host agents to pull rejudge tasks from at most 10% of sandbox slots (~6,200 slots) plus any slots left idle by judge.live.{lang} — guaranteeing live submissions at least 90% of fleet capacity (~55,800 sandboxes, still above the 50,000 peak requirement) while finishing 150,000 reruns in ~4 minutes. During those 4 minutes, display a "Problem C rejudging" banner, compute each user's Problem C score from version = 4 if ready or provisional version = 3 otherwise, notify affected users over WebSockets, and delay marking standings FINAL until rejudge queues reach zero.

Follow-up questions

Similar questions

More Nubank interview questions

All 3 Nubank questions →