Building a "HackerRank code compiler" really means building the judging backend behind a competitive-programming site: a service that accepts submitted source code, compiles and runs it inside a disposable sandbox, feeds it test input, compares output against a reference answer, and reports a verdict such as Accepted, Wrong Answer, Time Limit Exceeded, or Runtime Error. The compiler itself (GCC, JVM, Python) is ordinary open-source software; the hard engineering is isolation, resource limits, and abuse resistance. This guide walks the whole system in dependency order, from the execution runner upward, with the trade-offs you'll actually face—and notes that direct browsing isn't available here, so version-specific details should be confirmed against current tool documentation.
One framing choice matters up front. The real HackerRank runs on a proprietary, container-based execution environment whose exact internals aren't public. So "build a HackerRank code compiler" cannot mean cloning their private code. It means reproducing the observable behavior—multi-language compilation, per-test-case time and memory limits, streamed output comparison, and verdicts—in a system you control. Everything below targets that behavioral clone.
Start with the job the judge actually does
A competitive-programming judge is a pipeline with five stages, and failures in any one produce distinct verdicts:
1: Intake. Validate that the submission fits your policy: language ID, code size cap (say 64 KB), allowed dependencies, and submission rate. 2: Compile. Invoke the language toolchain with fixed flags, under its own time limit, and capture build diagnostics. 3: Run. Execute the compiled artifact per test case with wall-clock and memory limits, stdin routed from the test file, stdout captured. 4: Compare. Diff the output against the expected answer using an exact, token-based, or custom checker. 5: Score and report. Aggregate per-case results into a final verdict and release all resources.
Two constraints shape everything downstream. First, time limits are enforced around each test case, so your runner must re-spawn or rigorously reset state between cases—otherwise a submission that leaks memory or spawns threads gets a free pass on later cases. Second, untrusted code is hostile by default. A correct-looking solution can try to read your test files from disk, open a network socket, fork-bomb the host, or sleep past the limit. Isolation isn't a nice-to-have feature bolted on later; it's the prerequisite for running someone else's code at all.
A useful mental model: the compiler is a commodity that you call; the sandbox and scheduler are what you build.
Prerequisites before you write any runner code
You need more infrastructure than you'd guess. Before the first submission is judged, have these in place:
A Linux host or VM fleet with a recent kernel. Isolation primitives (namespaces, seccomp, cgroups) are Linux-specific, so Windows and macOS are non-starters for the runner itself. Toolchains installed at pinned versions for every language you offer—for example GCC and G++ from the GCC release series, OpenJDK from a specific JDK feature release, and CPython from a specific minor version. Pin exact versions, because compiler diagnostics and runtime behavior shift between releases. A queue (Redis, RabbitMQ, or a database-backed job table) so intake never blocks on execution. A control plane that owns test cases, problems, and submission records, and a worker service that pulls jobs and talks to the sandbox. A filesystem convention for problem test data, readable by the worker but never mounted into the sandbox. Logging and metrics from day one, because debugging an escape attempt or a flaky TLE without timestamps is guesswork.
Two more decisions belong here rather than later. Choose whether the sandbox is a container inside a shared VM (lighter weight, weaker boundary) or a microVM (stronger boundary, higher startup cost); both are covered below. And decide your default limits: common competitive-programming practice is roughly a 1–2 second limit per test case and 256 MB of memory, with variants per problem. Pick conservative defaults and make them per-problem overridable.
Design the submission and verdict contracts
Before the pipeline, fix the data shapes, because every component depends on them.
A submission record needs a unique ID, the problem ID, the language ID, the source code or a pointer to it, a status, and a timestamp. A result record needs the submission ID, the verdict, per-test-case entries (case index, verdict, time used, memory peak), and the compiler output string.
The verdict vocabulary should cover at least: Accepted, Wrong Answer, Compilation Error, Runtime Error, Time Limit Exceeded, Memory Limit Exceeded, and Output Limit Exceeded. Add an Internal Error verdict for judge faults, kept separate from user faults; mixing the two makes your error dashboards useless. Decide too whether a failed case stops the run (cheaper) or whether all cases run and partial credit is reported (more informative). For a HackerRank-like experience, running every case and showing per-case pass/fail is the friendlier default; note that this costs more compute.
On the API side, keep intake and polling separate. A submit endpoint returns a submission ID immediately and enqueues work; a status endpoint returns the current verdict. That asynchronous split is what lets you survive a burst of submissions without timing out clients.
Build the execution sandbox, stage by stage
This is the heart of the system, and it's where you should expect to spend most of your effort. The stages below go from weakest to strongest isolation; you can stop at the level that matches your threat model, but understand the gaps at each level.
Stage 1: Process-level limits
The cheapest controls are per-process ones. Run each solution in its own child process and apply a memory cap (setrlimit with RLIMIT_AS) and, as a backstop, a wall-clock cutoff enforced by the parent. Set RLIMIT_FSIZE to cap file writes (a Output Limit Exceeded or 4–16 MB cap is typical) and RLIMIT_NPROC to block fork bombs. Wall-clock enforcement matters because RLIMIT_CPU only counts CPU time; a solution that sleeps forever on read() would otherwise hang your worker. Always kill the whole process group, not just the direct child, since a program can spawn grandchildren.
What this level does not provide: file-system isolation (the program can still read anything reachable), network isolation, or protection against a determined attacker. It's fine for a private class assignment, not for a public site.
Stage 2: Namespaces and privilege drop
Add filesystem containment and privilege reduction. Use unshare() (or a container runtime, below) to give the solution a private mount namespace with a read-only root filesystem, a writable /tmp (possibly an in-memory tmpfs size-capped), and no visibility into your test-data directory. Run the child as a dedicated unprivileged user with no shell, no home directory, and no access to device nodes. A network namespace with no interfaces—or a blocking firewall rule—kills network access at the namespace level, which is stronger than an application-level block.
Bind-mount only the file the program needs to read (the compiled binary or the source for interpreted languages), then the test input and expected output are never present in the sandbox by default. The worker streams the test input into the child's stdin from outside the namespace. Output comparison happens in the worker, so a solution cannot read the expected answers.
Stage 3: Seccomp filtering
Seccomp is the fine-grained syscall control layer that catches what filesystem permissions miss. Apply a whitelist filter to the sandboxed process after the runtime has initialized, allowing only the syscalls a normal solution needs (read, write, mmap, brk, exit-group, and so on) and returning errors, or killing the process, on everything else. Block the dangerous families outright: execve after startup (stops a solution from spawning helpers), socket and connect, ptrace (stops debugging or injecting into other processes), and mount. For the JVM and other runtimes, build the whitelist empirically—trace a sample program's syscalls and allow the observed set, then test your full language matrix, because "Hello World" alone will undercount.
Stage 4: cgroups for hard resource ceilings
cgroups (v2 is the current generation) give you per-process-group accounting and enforcement: a memory limit that includes all descendant processes (the important part, since a solution can spawn a child to escape a per-process RLIMIT_AS), CPU quotas, and a PID cap that neutralizes fork bombs. Read the peak memory from the cgroup's memory.peak counter (or the current usage during the run) to report Memory Limit Exceeded precisely. Kill by writing to the cgroup, not by tracking PIDs individually.
Stage 5: Containers or microVMs
If you want the boundary to be a real security perimeter rather than a pile of well-configured kernels, package the above into a container runtime with seccomp and cgroups defaults (leading runtimes ship sensible profiles), or step up to a microVM that boots the workload in its own minimal virtual machine. Containers are much cheaper to start (tens to hundreds of milliseconds) and are fine when your host kernel is patched and your config is hardened. MicroVMs add a full hardware-virtualization boundary at a startup cost in the hundreds of milliseconds to a few seconds, which is the right trade when you're judging code from strangers at scale.
Whichever boundary you choose, enforce these invariants: no network, read-only system filesystem, writable only a size-capped tmpfs, unprivileged user, no device access, and a hard total wall-clock kill. Then verify them adversarially—see the failure section below.
Wire up test-case execution and output checking
With the sandbox solid, the per-case loop is straightforward:
1: Write the compiled binary (or interpreted source) into the sandbox's private directory. 2: Start the child with stdin from the test input stream, stdout to a capped buffer or file, stderr captured separately. 3: Start the wall-clock timer; record start time and the cgroup memory baseline. 4: Wait for exit, timeout kill, or an over-limit signal. 5: Classify the case: exited cleanly → compare output; killed for time → TLE; exceeded memory → MLE; nonzero exit or signal → RE; output over the cap → OLE. 6: Compare, record time and memory, move to the next case with a fresh sandbox or a fully reset one.
Output comparison deserves a word. Exact byte comparison is simplest but punishes trailing whitespace that most problems consider irrelevant. Detection mode, which trims trailing spaces per line and trailing blank lines, is the pragmatic default. Token-based comparison (collapse all whitespace to single spaces) is more forgiving still. For problems with multiple valid answers—any valid shortest path, any correct permutation—you need a special checker: a separate trusted program that reads input, expected output, and contestant output and returns pass/fail. Keep checkers out of the sandbox or treat them as fully trusted code you wrote.
For interactive problems, the model flips: the judge process talks to the solution over pipes, sending input chunks and reading responses in turn, so the "test file" handling becomes a protocol. Build plain batch judging first and add interactive support only when you need it; the scheduling and streaming requirements are materially different.
Choose the language toolchain matrix and compilation strategy
Each language is a compile-and-run recipe with its own quirks. A workable starting matrix:
C: GCC, gcc -O2 -o solution solution.c, run with a small stack expansion fudge if needed. C++: G++, g++ -O2 -std=c++20 -o solution solution.cpp, run with memory limits that account for the allocator's overhead. Java: javac Main.java then java -Xmx set slightly below the scheduler's memory cap, because the JVM reserves overhead beyond the heap. Startup time is nontrivial; budget 0.3–1 second of the time limit for JVM boot alone or you'll produce spurious TLEs. Python: run CPython directly with no compilation step. Interpreted submissions are slower by an order of magnitude, which is why competitive sites either apply language-specific time multipliers or accept that Python rarely passes the tightest limits. Document your policy explicitly. JavaScript: Node.js runs directly; similar startup-time caveats to Python.
Two implementation strategies. The one-container-per-language approach bakes exactly one toolchain into each image, keeping images small and startup fast, but you pay for the JVM image's size and a compile step inside the sandbox. The single fat image runs everything with one image but bloats startup and attack surface. For a v1, per-language images are easier to reason about.
Pin all toolchain versions and record them in the submission result—when a solution fails to compile, the diagnostics string should reflect exactly what the grader ran, or you'll field disputes you can't resolve. Compile inside a sandbox too, with its own wall-clock and memory budget; a malicious template could try to run at compile time (macros, build hooks).
Scale intake with queues, workers, and pooling
At any real volume, execution is the bottleneck and it's bursty—a contest opening bell can multiply traffic by orders of magnitude. The architecture that survives this:
Intake service validates and enqueues; it never executes. Worker pool pulls jobs; each worker owns at most one active sandbox at a time. A dead-letter queue for jobs that fail repeatedly for systemic reasons, tagged Internal Error so they don't masquerade as user failures. Autoscaling keyed on queue depth rather than CPU, so idle workers don't hold sandbox capacity hostage.
Reuse sandboxes where the isolation reasoning allows it—one container per language per worker, reset between cases by killing the process group and wiping the writable tmpfs. This saves most of the container-startup cost; the rule that keeps you honest is that no state from one submission's execution may be visible to the next. Since the namespace and filesystem setup is deterministic, a reset is exactly as clean as a fresh boot if done right, and you should test that claim with a state-leak probe.
Backpressure matters more than raw throughput. Cap concurrent sandboxes per host based on memory headroom (each sandbox may hold up to the problem's memory limit), and reject submissions with a clear "queue full, try again" instead of letting latency climb until clients time out.
Watch the failure modes and guardrails
The list of ways a judge goes wrong is the list of what to test against before launch. Notable ones:
Escape attempts. A solution that opens /etc/passwd or a test file should fail; verify with adversarial submissions (a checker program that deliberately tries each prohibited operation and reports what succeeded). Run this suite on every config change. Fork bombs. Verify that RLIMIT_NPROC and the cgroup PID cap both hold, and that killing the cgroup (not just the PID) actually cleans up. Wall-clock runaway. Test a solution that blocks on stdin forever or sleeps past the limit; your timer must kill it. Memory accounting mismatch. Compare what the cgroup reports against the problem limit; JVM heap-plus-overhead is the classic source of "my solution got MLE at half the limit" complaints. Compiler-output leakage. Compilation errors should show toolchain messages but never sandbox paths, hostnames, or your test-data layout. Queue starvation. Under a flood, short jobs should not sit behind pathological ones; per-problem or per-user caps prevent a single unresponsive worker from starving a contest. Version drift. After upgrading a compiler or runtime, regress your reference solutions across languages; an upgrade that changes default optimization or diagnostic format is a false-negative generator.
Stop condition: if you cannot verify the isolation invariants with adversarial tests, don't expose the judge to untrusted users. Keep it on a private network until they pass.
Work through an illustrative capacity estimate
Here's a worked sizing exercise, with assumptions labeled because real numbers depend on your kernel, storage, and workload.
Assume a contest with 1,000 participants, each making 10 submissions during a one-hour window, for 10,000 submissions. Assume each judge job—compile plus roughly 10 test cases—takes an average of 3 seconds of wall-clock time at one sandbox per worker (compile ~0.5 s, cases ~0.25 s each at the low end of the stated defaults). That's 30,000 sandbox-seconds, or about 8.3 sandbox-hours spread over that hour—roughly 8–9 concurrent workers at full utilization. Add a safety factor of 1.5–2 for burstiness (most submissions arrive in small clusters) and sandbox setup overhead, and you'd provision around 12–18 workers for the window, autoscaling down afterward.
The lesson from the arithmetic isn't the specific number—it's that the multiplier you're sizing on is average judge wall-clock time per submission, which you measure from your own logs, not a fixed constant. If your test cases are heavier (say 1 s each across 10 cases), the same contest needs roughly 4× the workers. Measure, then size.
Keep limits fair across languages
A familiar complaint pattern: "My Python solution got TLE, but the C++ one passed with the same logic." The mechanism is real—interpreted languages execute the same algorithm perhaps tens of times slower—and the common fixes are language-specific time multipliers (e.g., Python gets a longer limit) or a documented statement that the limits are language-neutral and interpreters must optimize harder. Both are defensible; silently doing neither is not. Whatever you choose, publish the policy, apply it consistently, and log the multiplier with each result so disputes have facts behind them. Memory limits deserve the same treatment: a uniform 256 MB cap is roughly fair for C/C++, but the JVM's baseline overhead means Java submissions effectively get less effective headroom unless you raise the cap or reduce the heap setting.
That fairness question is the one people most often miss when they ask how to build a HackerRank-style judge—the execution mechanics are learnable in a week, but the limit policy is a product decision that users will notice and argue about.
Bring it up in a defensible order
A practical build order: get a single-language, single-test-case runner working on your laptop with process limits only (day one); add filesystem and network namespaces and a privilege drop (week one); wrap it in container images with seccomp and cgroups (week two); add the queue, worker service, and asynchronous API (week three); add multi-language toolchains and the output comparison modes (week four); then spend the remaining effort on the adversarial test suite, limit policy, and metrics. Deploy to a private network first and pass your adversarial suite before opening the door. The compiler itself was never the hard part—the discipline of isolating it is.