To build a HackerRank-style code compiler, you don't write a compiler at all—you orchestrate one. The core is a submission pipeline: accept source code, compile or interpret it in a locked-down sandbox, feed it secret test inputs, compare outputs against expected answers, and report a verdict. The essential condition is isolation: untrusted user code must never touch your host filesystem, network, or other users' data. Everything else—queues, timeouts, scoring, the editor UI—is scaffolding around that one requirement.

This guide walks through the architecture, the sandboxing decision, the judge logic, and the operational limits that separate a weekend prototype from something you'd let strangers hammer. It targets a working single-language judge first, then explains how to add languages without multiplying your attack surface carelessly.

What you're actually building, and what "compiler" means here

HackerRank doesn't compile code itself in the sense that GCC or the JVM does. It runs user-submitted programs through a judging harness. When someone clicks "Submit," a service receives the source file, picks a language runtime, and executes it against several hidden test cases with strict limits on CPU time, memory, and output size. The platform then classifies each run as correct, wrong answer, time limit exceeded, runtime error, memory limit exceeded, or compilation error.

So "building a code compiler" for this purpose really means building three cooperating systems:

A language toolchain layer that knows how to compile or invoke each supported language and capture compile errors. A sandboxed execution layer that runs the resulting binary or script with enforced resource caps. A judging layer that prepares inputs, compares outputs, applies per-test scoring, and aggregates a verdict.

Get the boundaries between these right and each piece stays testable in isolation. Conflate them and you'll have a security hole that's also a maintenance nightmare.

Prerequisites before you write any code

Before building, decide and prepare the following. Skipping these leads to rework.

A host operating system you control. Linux is the practical choice because cgroups, namespaces, and seccomp are native. macOS can run a judge for local development but lacks the same isolation primitives. Windows requires a VM or container layer.

Container runtime or VM capability. You need Docker (or Podman) if you're going the container route, or a hypervisor if you're going the microVM route. Both must run on the judge host, not on your laptop's desktop session.

A language runtime inventory. Pick one language first—say Python 3 or C++—and install its compiler or interpreter inside the execution image. Pin the version; "latest" breaks reproducibility.

A place to store problems and test cases. A relational database works. Each problem needs a time limit, memory limit, reference solution or expected outputs, and the test inputs.

A job queue. Submissions are asynchronous. A queue (Redis, RabbitMQ, or a database-backed poller) decouples accepting a submission from judging it.

A clear verdict vocabulary. Define your statuses up front: AC (accepted), WA (wrong answer), TLE (time limit exceeded), MLE (memory limit exceeded), RE (runtime error), CE (compilation error), and an internal IE (internal error) for judge faults. Every downstream UI depends on this set.

Once these exist, the build order is: toolchain wrapper → sandbox → judge logic → orchestration → hardening.

Step 1: Build the language toolchain wrapper

Write a small service or module whose only job is to turn a source file into an executable command, and to surface compile errors cleanly.

For compiled languages, this means invoking the compiler with a timeout and capturing stderr. For C++:

g++ -O2 -std=c++17 -o /work/main /work/main.cpp

For interpreted languages there's no compile step, but you still want a lightweight syntax check where the runtime supports one (for example, python3 -m py_compile). The wrapper returns either a runnable command (/work/main or python3 /work/main.py) or a compile-error message that becomes the CE verdict.

Two details matter here. First, compile time must be bounded—a malicious submission can hand you a template that takes minutes to compile. Give compilers a generous but finite cap, something like 10 to 20 seconds, and count a timeout as a compile error. Second, compile inside the same isolated environment as execution, or at least in one that can't reach the network, because compilers process adversarial input too.

Keep the wrapper generic: a language is defined by a config object with its compile command template, run command template, file extension, and version string. Adding a language should be a config change plus a runtime installation in the image, not new judge code.

Step 2: Choose and build the isolation layer

This is the step people underestimate. Running arbitrary code with subprocess.run() and a timeout is not a sandbox. A process can fork children that outlive it, write gigabytes to disk, open network connections, read other submissions' files, or exhaust memory until the host swaps.

There are three realistic isolation strategies, and they trade off complexity against safety.

Containers (Docker or Podman). The approachable middle ground. Each execution gets a fresh container from a prebuilt image, with no network (--network none), a read-only root filesystem, a writable tmpfs mount for the working directory, a memory cap, and a CPU quota. The submission is copied in, run, and the container is destroyed. This is the standard approach for self-hosted judges that aren't defending against determined kernel exploits. Its weakness is that containers share the host kernel; a kernel vulnerability or a misconfiguration (like a world-writable mount) can escape.

MicroVMs (Firecracker and similar). Each execution runs in a lightweight virtual machine with its own kernel. This is what several production judging services converged on because it removes the shared-kernel risk and boots in well under a second. The cost is more setup: you need VM images, a host agent, and orchestration. If you're building something public-facing, this is the safer default.

Process-level restrictions (namespaces, seccomp, rlimits). Running with unshare, dropping capabilities, applying seccomp filters, and setting RLIMIT_CPU, RLIMIT_AS, and RLIMIT_FSIZE is the lowest-overhead option and is genuinely useful as a defense-in-depth layer inside a container. On its own, it's fragile—one misconfigured flag and a submission runs wild—so treat it as a supplement, not a substitute.

For a first working build, containers are the pragmatic choice. Plan an upgrade path to microVMs before you expose the judge to untrusted users at scale.

Step 3: Set resource limits that actually hold

A sandbox is only as good as the limits you enforce. Apply these per execution, not per submission:

CPU time. Use a wall-clock timeout and a CPU-time limit. Wall-clock catches programs that sleep or block; CPU time catches busy loops. Judge time-limit verdicts against CPU time so that host load doesn't unfairly fail submissions, but keep a wall-clock backstop. Memory. Set a hard cap in the container (--memory) and a process limit (RLIMIT_AS) inside it. Exceeding it yields MLE, not a crash the host notices. Output size. Cap stdout and stderr. An infinite-print loop can fill a disk in seconds. Route output through a pipe with a byte ceiling, and kill the process when it's hit. Process count. Limit RLIMIT_NPROC to stop fork bombs. File descriptors and disk. Provide a small tmpfs for working files with a size limit, and a read-only root otherwise. Network. Deny it. Most functional submissions don't need it, and the ones that do create exfiltration risk.

The subtlety: limits must be enforced by the isolation layer, not by the wrapper code polling. If your judge measures memory from a separate thread, it'll miss fast allocations. Let the container or VM enforce, then read the exit status to classify the verdict.

Step 4: Write the judging loop

Now the core logic. For each test case, in order:

1: Fetch the test input and expected output for the problem. 2: Start a fresh sandbox (container or VM) from the language's image, mounting the submission and the input. 3: Run the compiled command with stdin connected to the test input and stdout/stderr captured. 4: Wait with the time limit. If it exceeds the wall-clock cap, kill the sandbox and record TLE. 5: On exit, read the exit code. A non-zero exit (excluding the timeout kill) means RE; capture stderr for the user. 6: If the process succeeded, compare captured stdout to the expected output. 7: Record the per-test result and move to the next case.

Comparison policy is a real decision, not a detail. Exact string matching is the default and is easy to get wrong: trailing newlines and Windows line endings cause false WAs. Normalize line endings and trim trailing whitespace per line before comparing. For problems where floating-point answers are expected, allow a tolerance—for example, compare numeric tokens within 1e-6 relative error. Encode the comparison mode in the problem record so different problems can use exact, token-based, or float-tolerant matching.

Should you stop at the first failing test, or run all of them? Running all cases gives the user a fuller picture and helps with partial scoring, at the cost of more compute. Many judges stop at the first failure for efficiency on large test sets. Pick one and document it; the user-facing feedback should be consistent.

A useful debugging affordance: run the sample tests synchronously when the user clicks "Run," returning stdout, stderr, and exit code directly, and reserve the full hidden suite for "Submit." This separates quick feedback from the slower, queued judging job.

Step 5: Orchestrate submissions with a queue

At this point you can judge one submission. Now make it survive concurrency.

The request handler should not run the judge inline. Instead it writes a submission record (source, language, problem, timestamp, status = queued), pushes a job ID onto a queue, and returns immediately with a token the client uses to poll for status. A pool of worker processes—each pulling one job at a time—runs the judging loop and updates the record as it progresses, so the UI can show "running test 3 of 10."

Two rules keep this stable:

Workers are disposable. If a worker dies mid-judge, the job should be recoverable—either requeued after a visibility timeout or marked as an internal error. Never leave a submission stuck in "running" forever. Judge hosts are cattle, not pets. Build the language images once, keep them in a registry, and let workers pull them on demand. When you add a language or a compiler version, rebuild the image and roll hosts; don't hand-patch.

Concurrency controls matter for fairness. Cap the number of concurrent executions per user and globally, so one person submitting in a loop can't starve everyone else. Prioritize interactive "Run" requests over batch "Submit" jobs if you can afford the complexity.

Step 6: Add languages without breaking everything

Once one language works end to end, adding more is mostly configuration and image maintenance. Each new language needs its runtime installed and pinned in an image, a config entry with compile and run templates, and a small set of test submissions that verify it. Build the verification suite before you add the third language—at that point the mechanical differences (Java's class-name requirements, Go's compile output location, JavaScript's module setup) start producing subtle bugs that manual testing misses.

Keep the judge language-agnostic. The judging loop shouldn't know whether it's running main or python3 main.py; it should accept a run command, an input, and a limit. Language quirks belong in the toolchain wrapper.

Security failures and how to detect them

Assume submissions are hostile. The concrete failure modes to watch:

Filesystem escape. A submission reads /etc/passwd or another submission's directory. Detection: run a test submission that tries to open a known host path and assert it fails. Resource exhaustion. A submission allocates memory until the host OOM-killer fires. Detection: a test that allocates steadily and asserts MLE within the cap. Fork bombs. A submission spawns processes recursively. Detection: a test that attempts while True: os.fork() and asserts it's killed. Output floods. A submission prints in an infinite loop. Detection: a test that emits unbounded output and asserts a fast termination with output capped. Network exfiltration. A submission tries to call out. Detection: a test that attempts a socket connection and asserts failure with network disabled. Judge faults. A bug in your judging code misclassifies a correct submission. Detection: a reference solution per problem should always pass; run it in CI against every problem's tests.

Keep a small "attack suite" of these submissions and run it after every infrastructure change. It's the cheapest insurance you can buy.

The UI and scoring layer, briefly

The user-facing pieces matter less technically but shape perceived quality. A code editor with syntax highlighting, a language selector, and separate "Run" and "Submit" buttons covers the basics. On submit, a progress indicator that reflects real test execution beats a generic spinner. Feedback should be specific: for CE, show compiler stderr; for RE, show the exception and exit code (but never raw host paths); for TLE, state the limit that was exceeded and the time consumed.

Scoring is a policy choice. Two common models: full credit only when all tests pass, or partial credit per test passed. If you offer partial credit, weight tests in the problem record; otherwise a problem with one easy case and nine hard ones gives misleading scores. Make the weights visible to problem authors.

Where this stops being a weekend project

The honest limit of this architecture: a container-based judge is safe against ordinary functional submissions and careless mistakes, but it's not safe against a determined attacker who can chain a kernel exploit. If the judge is public and adversarial, move to microVMs and keep the attack suite as a regression gate. The judging logic, toolchain wrapper, and queue design don't change—only the isolation substrate does, which is exactly why you separated them.

The other limit is maintenance. Every compiler version you pin gets stale; every language you add is another image to rebuild. Budget for that. A judge with three well-maintained languages is more useful than one with fifteen half-broken ones.

If your build moves beyond educational or internal use—handling real user credentials, payment, or public competition—have someone with security engineering experience review the isolation layer before going live. This article is general educational guidance, not a security certification of any particular deployment.

Common questions

Do I need to write my own compiler or interpreter? No. You invoke existing toolchains. Your engineering effort goes into isolation, judging, and orchestration.

Can I run the judge on the same machine as the web server for a prototype? Yes, for local development with trusted testers. For anything untrusted, isolate judge hosts from the application and database. A compromised submission should not be able to reach your users' data.

What's a reasonable first time limit? Problems typically range from one to several seconds of CPU time. Start with a generous limit for your first language and tune it per problem as reference solutions reveal realistic runtimes.

How do I verify a new language works? Write a tiny correct submission, a wrong-answer submission, and a compile error, and confirm the judge reports AC, WA, and CE respectively. Add them to the attack suite's sibling—the verification suite—and run it on every image rebuild.