Online judge API: how to build an online judge or LeetCode-style site
An online judge, the engine behind LeetCode-style practice sites and coding contests, runs a submission against hidden test cases and returns a verdict. An online judge API does that part for you: with stored problems you keep each problem's tests, checker and limits on the API and judge by id, so a submission is a compiler and code and you never run a sandbox yourself. This guide builds it step by step, with code you can copy into Node.js or Python.
Também em portuguêsTambién en español
How a judge works
Every online judge, from a university autograder to LeetCode, follows the same loop:
- A problem has hidden test cases: an input and the output a correct program prints for it.
- A student submits code and picks a language.
- For each test, the judge runs the code with the test's input on stdin, in a sandbox.
- It compares the program's output with the expected output, and checks time and memory.
- It returns a verdict: Accepted if every test passed, or the first failure.
Step 3 is the hard part to build yourself: running untrusted code safely needs isolation, resource
limits and no network. With stored problems the API does the rest as well. You store
a problem once, with its tests, its checker and its limits. After that a submission is only a compiler and the
code: POST /api/problems/{problem}/submissions/ runs steps 3 to 5 against the stored tests and returns a
verdict for each test, an overall verdict, a score and a signed receipt. The hidden tests never leave our servers,
so they cannot leak from your front end or your logs. If your tests already live in your own database, you can send
them with each request instead, as in the second half of this guide.
1. Store the problem once
POST /api/problems/ creates a problem with its first draft: a title, an optional slug of your own, the statement, the languages allowed, scoring, and the tests. Each test is an input,
an expected output and a hidden flag; a test is hidden unless you say "hidden": false,
so only the samples you choose are ever shown to candidates. A draft is not judged against until you publish it: POST /api/problems/{problem}/publish/ numbers it as the next version. If the draft has a reference_solution, the version is checking while that solution is judged against every test as a queued
submission (the answer is 202), and it goes live only if every test is accepted; otherwise it is rejected and
you fix the draft and publish again. Without a reference solution the version is published at once, with a warning that the
expected outputs were not checked.
# 1. Store the problem. Tests are hidden unless you say "hidden": false.
curl -X POST https://api.onlinecompiler.io/api/problems/ \
-H "Authorization: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"title": "Sum of two numbers",
"slug": "sum",
"statement": "Write solve(a, b), which returns the sum of two integers.",
"languages": ["python-3.14"],
"scoring": "percent",
"tests": [
{"name": "sample", "input": "1 2\n", "expected_output": "3\n", "hidden": false},
{"input": "5 7\n", "expected_output": "12\n"},
{"input": "-4 4\n", "expected_output": "0\n"}
],
"starter_code": {"python-3.14": "def solve(a, b):\n pass\n"},
"drivers": {"python-3.14": "##CODE##\n\na, b = map(int, input().split())\nprint(solve(a, b))\n"},
"reference_solution": {"compiler": "python-3.14", "code": "def solve(a, b):\n return a + b\n"}
}'
# 201: the problem and its draft.
# 2. Publish the draft as version 1. With a reference solution the answer is 202:
# the check runs as a queued submission and the version is "checking" until it ends.
curl -X POST https://api.onlinecompiler.io/api/problems/sum/publish/ -H "Authorization: YOUR_API_KEY"
# {"problem": "prob_...", "version": 1, "state": "checking", "check": "sub_..."}
# 3. Read the problem until the version is "published" (or "rejected").
# A rejected version's check.message says why: fix the draft and publish again before judging.
curl https://api.onlinecompiler.io/api/problems/sum/ -H "Authorization: YOUR_API_KEY"A classic first problem reads two numbers and prints their sum. Add a test such as 2000000000 2000000000:
four billion does not fit in a 32-bit int (the largest is 2,147,483,647), so a C++ solution that uses int prints a wrong, negative number. Good test sets include edge cases like this.
A version can also carry up to 8 data files, such as a CSV or a SQLite database,
that every test reads from its working directory. An input can be up to 5 MB, and all the inputs, expected
outputs and data files of a version together up to 20 MB (the limits table has the active problems and data each plan keeps). Published versions stay readable, and every submission is judged against the version that was
current when it was accepted. If you fix a test later, publish a new version and re-judge the earlier submissions against it.
2. Drivers, checkers and partial credit
For a "write this function" problem, give the problem a driver for each language: a program of yours with ##CODE## where the candidate's code goes. The driver reads the input, calls the candidate's function and prints the answer, so
candidates write only the function. The driver is not shown to candidates, but it is not secret: a candidate's program can read
its own source, driver included, and print it on a visible test, so keep test data and anything sensitive out of drivers. Starter
code you give is in the public view.
The built-in checkers (trim, exact, tokens, float, rows, table and table_ordered) cover most
problems. For answers that are not one fixed text, such as "print any valid path", set checker to custom and
give a custom_checker, plus a reference solution that passes it. The checker reads
the test's input, the expected output and the program's output as files, and exits 0 to accept, 1 or 2 for a wrong answer, or 3
for a checker error. Its first line of stdout can be a number from 0 to 1: the test's credit, which counts under percent and weighted scoring. It can be written in any supported language; Python, JavaScript (Node), C, C++
and Java are recommended. C, C++ and Java checkers are compiled once and the build is kept, and interpreted languages start fast;
other compiled languages (Rust, Go, Kotlin, C# and so on) compile again for every test inside the checker's
30-second sandbox, so on a problem with many tests they can run out of time and give checker errors. Each
test's checker gets 5 seconds. Checking with a custom checker is not charged as runs. A checker that fails gives the candidate a checker_error verdict, never a wrong answer, and only you see why.
3. Judge by id
A submission is POST /api/problems/{problem}/submissions/ with a compiler and the code. {problem} is the problem's prob_ id or its slug. The tests, checker, scoring and limits
come from the current version. mode is all (the default) or samples, which judges only the
visible tests so a candidate can try code before submitting, and tests, a list of test positions, judges only those. A synchronous request waits for the result; for a problem with a custom
checker, or whenever a submission may be slow, send async: true: the answer is 202 with a submission id, and you read it with GET /api/submissions/{id}/ or receive it at a callback_url (below). The refusals are 404 for a problem that
is not yours, 409 for an archived problem or one with no published version yet, 400 for a compiler the problem does not allow,
and 429 when your plan's limits are busy.
// judge.js: judge code against a stored problem, by its slug or id.
const API = "https://api.onlinecompiler.io";
const headers = {
Authorization: process.env.ONLINECOMPILER_API_KEY,
"Content-Type": "application/json",
};
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// mode "samples" judges only the visible tests (a Run button); "all" judges every test.
export async function judge(problem, submission, { mode = "all" } = {}) {
for (let attempt = 0; ; attempt++) {
const res = await fetch(`${API}/api/problems/${problem}/submissions/`, {
method: "POST",
headers,
// async: true answers 202 at once; the result is read later (see "Queue it").
body: JSON.stringify({ compiler: submission.compiler, code: submission.code, mode, async: true }),
});
// 429: the account's limits are busy. Wait, then try again.
if (res.status === 429 && attempt < 5) {
await wait(500 * 2 ** attempt);
continue;
}
// 404: not your problem. 409: archived, or no published version yet. 400: a compiler the problem does not allow.
if (!res.ok) throw new Error(`Judging failed: HTTP ${res.status} ${await res.text()}`);
const { submission: id } = await res.json();
for (;;) {
await wait(2000);
const poll = await fetch(`${API}/api/submissions/${id}/`, { headers });
const result = await poll.json();
// finished: result.result.verdict and .score; failed: result.error and no result.
if (result.status === "finished" || result.status === "failed") return result;
}
}
}# judge.py: judge code against a stored problem, by its slug or id.
import os
import time
import requests
API = "https://api.onlinecompiler.io"
HEADERS = {"Authorization": os.environ["ONLINECOMPILER_API_KEY"]}
def judge(problem, compiler, code, mode="all"):
# mode="samples" judges only the visible tests (a Run button); "all" judges every test.
body = {"compiler": compiler, "code": code, "mode": mode, "async": True}
for attempt in range(6):
res = requests.post(f"{API}/api/problems/{problem}/submissions/", headers=HEADERS, json=body, timeout=30)
# 429: the account's limits are busy. Wait, then try again.
if res.status_code == 429 and attempt < 5:
time.sleep(0.5 * 2**attempt)
continue
# 404: not your problem. 409: archived, or no published version yet.
# 400: a compiler the problem does not allow.
res.raise_for_status()
break
submission = res.json()["submission"]
while True:
time.sleep(2)
result = requests.get(f"{API}/api/submissions/{submission}/", headers=HEADERS, timeout=30).json()
if result["status"] in ("finished", "failed"):
return result # finished: result["result"]["verdict"], ["score"]; failed: result["error"] and no resultEach judged test is one run, as with /api/run-tests/, and samples counts only the visible tests. Judging
uses your API key, so a candidate needs no account of ours. Keep the key on your server; the browser sends the code to your
route and gets back a verdict. To show the statement, the samples and your starter code on a candidate's page, read GET /api/problems/{problem}/public/ from your server, or make the problem public and read it from the browser:
it has the visible tests and only the number of hidden ones.
4. Read the verdicts
Each test gets a verdict, and the response has an overall one: the first test in your order that failed.
| Verdict | When |
|---|---|
time_limit_exceeded | Exit code 124, or time over the problem's time_limit plus the start-up allowance for Java (1 s), Groovy (1.5 s) and F# (2.5 s) |
memory_limit_exceeded | Killed at 512 MB (exit code 137). A stored problem has no memory limit of its own yet; for a lower one, send the tests with /api/run-tests/ and its memory_limit, or check memory on a visible run. |
output_limit_exceeded | Stdout went over 64 KB |
compilation_error | Compiling failed; compile_error holds the message for a visible test that failed to compile, and for C and C++ requests that compile once whenever any test is visible |
runtime_error | Any other non-zero exit or signal; error holds the stack trace on a visible test |
wrong_answer | The run succeeded but the checker rejected the output |
checker_error, problem_error | The problem or its checker could not judge the test: never the candidate's fault. The overall verdict is the same, and only the problem's owner sees why, in checker_log |
accepted | The run succeeded and the output matches |
skipped | The test never started: an earlier one failed with stop_on_failure on (the default for all-or-nothing scoring) or the program failed to compile, or the 45-second start cut-off came first |
incomplete | Overall verdict only: the start cut-off skipped tests and none failed, usually because the service was busy or your account's other runs kept its sandboxes busy. Retry the request; every test runs and counts again. |
score runs from 0 to 100: all or nothing by default, or the share of tests (or of their weight) that passed with percent and weighted.
5. Async, webhooks and receipts
When a whole class submits before a deadline, send async: true with a callback_url and an external_ref of your own, such as an attempt id. Each finished submission is posted to you in a signed webhook, retried if your endpoint does not answer, and the queue is your account's: it
holds up to 320 submissions on Free, 600 submissions on Starter, 1,200 submissions on Pro, 2,400 submissions on Business, 6,000 submissions on Platform. Send an Idempotency-Key header and a retried request does not run twice.
Every judged submission gets a signed receipt that names the problem id and the version, whether all tests or only the samples were judged, and the hash of the tests. Store the receipt with the grade. Anyone can verify it offline against our public keys, which is how an assessment or a course certificate can show that a result is the one our run produced and has not been edited since. The coding assessment API page says what a receipt does and does not prove.
6. Keep it safe
- Keep the API key on your server. The browser only sends code to your route and gets a verdict. The hidden tests and the checker are readable only with your key.
- Rate-limit submissions per user, so one student can't use up your quota.
- Treat output as untrusted text. Escape it before showing it in a page.
- Keep secrets out of drivers. A candidate's program can read its own source, driver included, and print it on a visible test, and a compile error or a visible test's error can quote a driver line.
- The sandbox side is handled: every run gets a fresh gVisor sandbox with no network, 512 MB of memory (up to 2 GB on Pro and above), 2 CPUs and 16 processes.
Keeping the tests in your own database
A stored problem is the simplest route, but it is not the only one. POST /api/run-tests/ takes the code and the
tests in one request, with any input files the tests share (a stored problem keeps its own data files). The rest of this section covers it.
For a working example, onlinecompiler-io/online-judge-starter on GitHub is a small practice site in Next.js built this way: problems in JSON files on the server, Run on the sample tests, Submit on every test, and only a verdict shown for each hidden test.
Test cases in your own database
If you keep the tests yourself, keep them on your server, never in the browser. Each test is an input string and the expected output, plus limits for the problem. A classic first problem reads two numbers and prints their sum:
import { judge } from "./inline-judge.js";
const problem = {
timeLimit: 2, // seconds per test
partialCredit: false,
tests: [
{ input: "2 3\n", expected: "5\n" },
{ input: "-7 10\n", expected: "3\n" },
{ input: "2000000000 2000000000\n", expected: "4000000000\n" },
],
};
const submission = {
compiler: "g++-15",
code: `#include <iostream>
int main() { int a, b; std::cin >> a >> b; std::cout << a + b << "\\n"; }`,
};
console.log(await judge(problem, submission, { submit: true }));
// { verdict: "wrong_answer", score: 0, passed: 2, total: 3, ... }: int overflows. With long long, it's "accepted".The third test is deliberate: four billion doesn't fit in a 32-bit int (the largest is
2,147,483,647), so a C++ solution that uses int prints a wrong, negative number. Good test sets include edge cases like
this. Each input can be up to 5 MB.
Send the code and the tests
One request carries the code, the language and every test: an input, the expected_output, and whether the test is hidden. Each test runs in its own
fresh sandbox, at most 4 at a time on Free, in the order you list them, and
each counts as one run. A request holds up to 32 tests on Free and up to
600 on Platform, and has a 60-second budget; a request over it
gets 400 with the largest time_limit that would fit. If the service is busy it answers
429; back off and retry. If it stays busy, tests that cannot start within
45 seconds come back skipped and the overall verdict is incomplete; run the request again. The judge() function below handles both.
Output is compared for you
Comparing byte for byte fails students over a trailing space or a missing final newline, so the
default trim checker strips trailing whitespace from each line and blank lines from the
end, then compares exactly. For other problems, set checker to exact, tokens (ignore all whitespace differences) or float (numbers within tolerance, 1e-6 by default). Problems with several valid answers
need a checker program: a stored problem can run one for you (above); with tests sent in the request, compare those in your own code from the output of a visible run.
Grading pandas and SQL questions
Data questions have two problems the plain checkers cannot solve: a table has no fixed row order, and
a float column rarely matches to the last digit. The rows checker handles both. It compares
the output lines as an unordered set (a line that appears twice must appear twice). A line with |, a comma or a tab is split at each one into fields, keeping empty fields so every value stays
in its column; any other line is split at whitespace. Numbers match within tolerance and every
other field must match exactly. Send the data once in files; each test's sandbox gets its own copy
in the working directory (20 files and 1 MB at most). A stored problem keeps the data
with its version instead, up to 10 MB, as data files.
For SQL, use duckdb-1.5: the student's query reads the files with read_csv and
DuckDB prints each row with | between columns and no header row, so write the expected output the same way.
curl -X POST https://api.onlinecompiler.io/api/run-tests/ \
-H "Authorization: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"compiler": "duckdb-1.5",
"code": "SELECT region, sum(amount) FROM read_csv('\''sales.csv'\'') GROUP BY region;",
"files": [
{"name": "sales.csv", "content": "region,amount\nnorth,10\nsouth,20\nnorth,5.5\n"}
],
"tests": [
{"expected_output": "south|20.0\nnorth|15.5\n"}
],
"checker": "rows"
}'For pandas, use python-3.14 (3.0.6), or python-3.14-pandas2 (2.3.3) if your questions were written
for pandas 2. Have the program print one row per line, and give the question a stub that does so:
import pandas as pd
df = pd.read_csv("sales.csv")
out = df.groupby("region", as_index=False)["amount"].sum()
for row in out.itertuples(index=False):
print(row.region, row.amount)Importing the stack takes a moment (about 0.55 s for pandas and up to
3 s for the whole set on our measurements), so raise time_limit above the default for pandas questions. The package list is in the package
table; the full request is in the run-tests reference.
Judge a whole submission
Put together, the judge is one function:
// judge.js: run a submission against tests you send, with one API call.
const RUN_TESTS_URL = "https://api.onlinecompiler.io/api/run-tests/";
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// submit: true hides every test, so the response holds verdicts and nothing else.
// submit: false (the Run button) also returns each test's output and error.
export async function judge(problem, submission, { submit = false } = {}) {
for (let attempt = 0; ; attempt++) {
const res = await fetch(RUN_TESTS_URL, {
method: "POST",
headers: {
Authorization: process.env.ONLINECOMPILER_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
compiler: submission.compiler,
code: submission.code,
// time_limit stops each test at the problem's limit, not counting compilation.
time_limit: problem.timeLimit,
tests: problem.tests.map((t) => ({
input: t.input,
expected_output: t.expected,
hidden: submit,
})),
// Stop at the first failure, like ICPC. "percent" goes on past a failure and scores them all.
scoring: problem.partialCredit ? "percent" : "all_or_nothing",
}),
});
// The endpoint answers 429 when it's busy: wait, then try again.
if (res.status === 429 && attempt < 5) {
await wait(500 * 2 ** attempt);
continue;
}
if (!res.ok) throw new Error(`Run failed: HTTP ${res.status} ${await res.text()}`);
const result = await res.json(); // { verdict, score, passed, total, compile_error, tests }
// "incomplete": the sandboxes were busy, so some tests could not start in time. Skipped
// tests cost nothing, but a retry runs and counts every test again, so retry a few times at most.
if (result.verdict === "incomplete" && attempt < 3) {
await wait(2000);
continue;
}
return result;
}
}# judge.py: run a submission against tests you send, with one API call.
import os
import time
import requests
RUN_TESTS_URL = "https://api.onlinecompiler.io/api/run-tests/"
def judge(problem, compiler, code, submit=False):
# submit=True hides every test, so the response holds verdicts and nothing else.
# submit=False (the Run button) also returns each test's output and error.
body = {
"compiler": compiler,
"code": code,
# time_limit stops each test at the problem's limit, not counting compilation.
"time_limit": problem["time_limit"],
"tests": [
{"input": t["input"], "expected_output": t["expected"], "hidden": submit}
for t in problem["tests"]
],
# Stop at the first failure, like ICPC. "percent" goes on past a failure and scores them all.
"scoring": "percent" if problem.get("partial_credit") else "all_or_nothing",
}
for attempt in range(6):
res = requests.post(
RUN_TESTS_URL,
headers={"Authorization": os.environ["ONLINECOMPILER_API_KEY"]},
json=body,
timeout=90,
)
# The endpoint answers 429 when it's busy: wait, then try again.
if res.status_code == 429 and attempt < 5:
time.sleep(0.5 * 2**attempt)
continue
res.raise_for_status()
result = res.json() # {"verdict", "score", "passed", "total", "compile_error", "tests"}
# "incomplete": the sandboxes were busy, so some tests could not start in time. Skipped
# tests cost nothing, but a retry runs and counts every test again, so retry a few times at most.
if result["verdict"] == "incomplete" and attempt < 3:
time.sleep(2)
continue
return resultBy default it stops at the first failing test, as ICPC-style contests do. For partial credit, IOI-style,
set partialCredit so a failing test does not stop the rest and the score is the share that passed. A hidden test
comes back with only its verdict: no output, error, exit code, time or memory, and no
compiler output, because a program can smuggle a hidden input out through any of them. Show students the
verdict and the failing test's number, never the hidden input or expected output. Use submit: false for the Run button on sample tests, where the student sees the output.
Scale up with the async endpoint
/api/run-tests/ holds the request open until every test has finished, and one request
takes at most your plan's pending limit of tests. When a whole class submits before a deadline,
queue the runs instead: the async endpoint returns straight
away, and each result is POSTed to the callback URL set on your API key. Put your own ids in extra_params and they come back with the result.
// Queue every test at once. Each result is POSTed to the callback URL set on your API key.
for (const [i, test] of problem.tests.entries()) {
await fetch("https://api.onlinecompiler.io/api/run-code/", {
method: "POST",
headers: {
Authorization: process.env.ONLINECOMPILER_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
compiler: submission.compiler,
code: submission.code,
input: test.input,
extra_params: { submissionId: submission.id, test: i },
}),
});
}
// In your callback handler, extra_params says which submission and test a result is for:
app.post("/judge/callback", (req, res) => {
const { submissionId, test } = req.body.extra_params;
saveResult(submissionId, test, req.body); // output, error, exit_code, signal, truncated, time, memory
res.sendStatus(200);
});Two cost notes: each test case is one run, and each queued run compiles the program again, so a
20-test C++ submission compiles 20 times; /api/run-tests/ compiles C, C++ and Java once per
request when there are more tests than run at once, so prefer it when a submission fits in one request. Use this route
when a submission has more tests than one /api/run-tests/ request takes, or when you
would rather not hold a request open. To size a plan from your users, submissions and tests, use the plan estimator.
Coming from Judge0: the batch endpoint
If you already have a Judge0 client, the Judge0-compatible API compares output
too, and you can keep it as it is. Send each test's expected_output and it compares the output the way the trim checker does,
ignoring trailing whitespace on each line and at the end. A batch sends a whole test set in one request:
const JUDGE0 = "https://api.onlinecompiler.io/api/judge0";
const headers = {
"X-Auth-Token": process.env.ONLINECOMPILER_API_KEY,
"Content-Type": "application/json",
};
const res = await fetch(`${JUDGE0}/submissions/batch`, {
method: "POST",
headers,
body: JSON.stringify({
submissions: problem.tests.map((test) => ({
language_id: 105, // C++ (GCC 15); GET /languages lists the ids
source_code: submission.code,
stdin: test.input,
expected_output: test.expected,
cpu_time_limit: problem.timeLimit,
})),
}),
});
if (!res.ok) throw new Error(`Batch failed: HTTP ${res.status}`);
const tokens = (await res.json()).map((s) => s.token).join(",");
// Poll until no test is In Queue (1) or Processing (2).
let results;
do {
await new Promise((resolve) => setTimeout(resolve, 1000));
const poll = await fetch(
`${JUDGE0}/submissions/batch?tokens=${tokens}&fields=status,time,memory`,
{ headers },
);
({ submissions: results } = await poll.json());
} while (results.some((r) => r.status.id <= 2));
console.log(results.map((r) => r.status.description));
// [ "Accepted", "Accepted", "Wrong Answer" ]: the int overflow again.Each test comes back with a Judge0 status: 3 Accepted, 4 Wrong Answer, 5 Time Limit Exceeded (over cpu_time_limit or the 30-second cap), 6 Compilation Error, and 7 to 12
for runtime errors (the Judge0 API guide explains each). memory_limit only raises a run's memory (above 512 MB, up to 2 GB on Pro and above);
a lower value keeps 512 MB, so check memory yourself if a problem needs a lower limit. A batch holds up to 20 tests and no
more than the account's pending limit (32 on Free), so split larger test sets.
Each test is still one run.
Run a coding contest for your college
There is no hosted contest here: no contest page, sign-up or scoreboard to switch on. The API is the judge, and the rest is small enough to build for one event. The smallest build has three parts. First, a problem list that holds the id of each stored problem, whose hidden tests stay with us:
CREATE TABLE problems (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
stored_problem TEXT NOT NULL -- the id of the stored problem: prob_...
);
CREATE TABLE submissions (
id INTEGER PRIMARY KEY,
contestant TEXT NOT NULL,
problem_id INTEGER NOT NULL REFERENCES problems(id),
verdict TEXT NOT NULL,
receipt TEXT, -- the receipt id, for disputes
submitted_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);Second, a submit route that judges each submission against its stored problem, through the judge() function from step 3, and stores the verdict and the receipt's id:
# contest.py: a contest's submit route, using judge() from step 3 and SQLite.
import sqlite3
from judge import judge
db = sqlite3.connect("contest.db")
def submit(contestant, problem_id, compiler, code):
(stored,) = db.execute(
"SELECT stored_problem FROM problems WHERE id = ?", (problem_id,)
).fetchone()
# The tests, the checker and the limits live in the stored problem: send only the code.
submission = judge(stored, compiler, code)
if submission["status"] == "failed":
# A failure on our side has an error and no result: record no verdict, and let the contestant resubmit.
return submission["error"]
verdict = submission["result"]["verdict"]
db.execute(
"INSERT INTO submissions (contestant, problem_id, verdict, receipt) VALUES (?, ?, ?, ?)",
(contestant, problem_id, verdict, (submission.get("receipt") or {}).get("receipt")),
)
db.commit()
return verdict # show the contestant this, never the testsThird, the leaderboard, ranked by problems solved and then by penalty time, as ICPC does:
-- ICPC-style: most problems solved, then the least penalty: minutes from :start to each
-- first accepted answer, plus 20 for every rejected try before it.
WITH first_ac AS (
SELECT contestant, problem_id, MIN(submitted_at) AS solved_at
FROM submissions
WHERE verdict = 'accepted'
GROUP BY contestant, problem_id
)
SELECT
f.contestant,
COUNT(*) AS solved,
SUM(
(strftime('%s', f.solved_at) - strftime('%s', :start)) / 60
+ 20 * (
SELECT COUNT(*) FROM submissions s
WHERE s.contestant = f.contestant
AND s.problem_id = f.problem_id
AND s.submitted_at < f.solved_at
AND s.verdict NOT IN ('compilation_error', 'incomplete', 'checker_error', 'problem_error')
)
) AS penalty
FROM first_ac f
GROUP BY f.contestant
ORDER BY solved DESC, penalty ASC;Run it with :start set to the contest's start time in UTC, such as 2026-11-14 09:00:00. Compile errors, incomplete runs and checker_error or problem_error verdicts (the problem's fault, not the contestant's) don't count as rejected tries,
and a contestant appears once they solve a problem. Each submission costs one run per test: on Free a problem
can have up to 32 tests (and you can store 25 problems), and 60 runs a minute is
7 submissions of 8 tests a minute.
That suits a club's practice round, not a hall of contestants submitting at once; the table below sizes each
plan.
Backend for a coding exam or lab-test platform
If you're building an exam or lab-test product, the API can be its judging core. It covers the part that is hard to build safely and leaves the exam itself to you:
| The API covers | You build or bring |
|---|---|
| Running untrusted code: a fresh sandbox for each test, with no network | Proctoring: webcam, screen and tab-switch monitoring |
Stored problems: visible and hidden tests, versions with a reference check, hidden drivers, custom checkers, points (weight) and partial credit | The question bank's catalogue, tags and difficulty, and which questions an exam uses |
| A time limit for each test, up to 30 seconds, and 7 output checkers | Rosters, logins and the exam schedule |
| 46 languages | Plagiarism checks, with a tool such as MOSS or JPlag |
| The async endpoint, which queues runs and posts each result to your callback URL | Offline exams: every run goes to our servers over the internet, so a lab with no internet access needs a judge of its own |
How many students a plan takes at once
Each test is one run, and each plan caps the runs your account starts in a minute. Assume the worst moment of a lab test, when every student submits once in the same minute. Dividing each plan's cap by the tests per submission gives the class that fits:
| Plan | Runs a minute | Students at once, 4 tests each | Students at once, 8 tests each |
|---|---|---|---|
| Free | 60 | 15 | 7 |
| Starter | 300 | 75 | 37 |
| Pro | 600 | 150 | 75 |
| Business | 1,200 | 300 | 150 |
| Platform | 3,000 | 750 | 375 |
So Pro allows 600 runs a minute: 150
students submitting 4 tests each stay under the cap, and 200 students need
2 minutes for the same round. Within the minute, submissions that arrive together also queue: an
account runs 10 tests at a time on Pro, with up to 120
queued or running, and past that the API answers HTTP 429, which judge() retries. These are
your account's caps. Even within them, a request can occasionally answer 429 or return incomplete. For a timed exam with a large class, talk to us first and we'll
set aside capacity for it.
What the API doesn't do for you
- There are no contest pages and no plagiarism checks: a leaderboard, a candidate's page and a timer are yours to build.
- A stored problem keeps up to your plan's pending limit of tests per version, with at most 5 MB per input and 20 MB per version, data files included (8 files and 10 MB at most). The run-code endpoints take one test per request and leave the verdict to your code. The Judge0-compatible endpoint compares output and takes batches of up to 20 tests.
- The built-in checkers are
trim,exact,tokens,float,rows,tableandtable_ordered; a custom checker covers anything else, but not interactive problems. - Output is kept up to 64 KB per stream, so problems with larger output need a checker inside the program or another approach.
- It supports 46 languages.
Sphere Engine's Problems module also stores problems and has a problem widget, and adds interactive problems. See how it compares, or how all the options compare. Grading course assignments rather than running a judge? The autograder API guide covers points, partial credit and grading a folder of submissions.
Frequently asked questions
Can I store a problem and its tests on the server?
Yes. POST /api/problems/ stores a problem with its statement, tests (hidden unless you say otherwise), checker and limits; POST /api/problems/{problem}/publish/ makes a version, checked first by a reference solution if you give one. Then POST /api/problems/{problem}/submissions/ judges code against it by id. A plan keeps 25 active problems on Free, 250 active problems on Starter, 2,500 active problems on Pro, 10,000 active problems on Platform; Business has Pro's.
Can I use my own checker program?
Yes, for a stored problem: set checker to custom and give a custom_checker, plus a reference solution that passes it. It reads the input, the expected output and the program's output, exits 0 to accept, and can print a credit from 0 to 1 for partial scores. It can be written in any supported language; Python, JavaScript (Node), C, C++ and Java are recommended, because C, C++ and Java checkers are compiled once and interpreted languages start fast, while other compiled languages compile again for every test and can run out of time on a problem with many tests. Each test's check gets 5 seconds, and checking is not charged as runs.
How do I grade a pandas or SQL question?
Send the data as files with the request, have the student's program print its answer one row per line, and set checker to rows, which ignores the order of the rows and accepts numbers within a tolerance. Use python-3.14 for pandas 3.0.6 or python-3.14-pandas2 for pandas 2.3.3, and duckdb-1.5 for SQL. The files are shared by every test, up to 20 files and 1 MB in total.
How do I build a LeetCode clone?
You need four parts: a code editor in the browser (Monaco or CodeMirror), a catalogue of problems in your own database, a backend route that sends the code to a code execution API, and a page that shows the verdicts. With stored problems the tests live in the API: the route sends a compiler and the code to /api/problems/{problem}/submissions/, and you never run a sandbox. This guide builds that route in Node.js and Python.
Does each test compile the program again?
For C, C++ and Java, not when a request has more tests than run at once: one sandbox compiles the program, then every test runs that build. Other compiled languages compile in each test, so slow compilers such as Kotlin, Scala and Crystal fit fewer tests in one request.
What do AC, WA, TLE, MLE, RE and CE mean?
They are the classic judge verdicts. Accepted (AC): the output matched. Wrong Answer (WA): it ran but printed something else. Time Limit Exceeded (TLE): still running at the time limit. Memory Limit Exceeded (MLE): used more than the memory limit, 512 MB or the memory_limit sent with /api/run-tests/ (up to 2 GB on Pro and above). Runtime Error (RE): any other crash or non-zero exit. Compilation Error (CE): it didn't compile. The API returns them as accepted, wrong_answer, time_limit_exceeded, memory_limit_exceeded, runtime_error and compilation_error.
How do online judges compare output?
Most ignore trailing spaces at the end of each line and blank lines at the end of the output, then compare exactly. Problems with several valid answers, or floating-point answers, need a checker: compare tokens, allow a small tolerance such as 1e-6, or run a checker program that validates the answer.
How do I set a time limit lower than 30 seconds?
Send time_limit, in seconds, with /api/run-tests/ (it applies to each test; 2 if left out) or with a single run. The program is stopped at that limit with exit code 124, and compiling before it does not count; compile and run together are still capped at 30 seconds. Java, Groovy and F# compile as they start, so they get a start-up allowance on top of the limit: Java (1 s), Groovy (1.5 s) and F# (2.5 s). For memory, send memory_limit in MB (16 to 512) with /api/run-tests/: a test whose program peaks above it is memory_limit_exceeded. The peak includes the language's runtime, so leave headroom.
How many API calls does one submission use?
One per test case, whether you send tests one at a time, in one /api/run-tests/ request or as a Judge0 batch. A problem with 20 tests uses 20 runs per submission, so the free plan's 100,000 runs a month covers 5,000 submissions of that size.
Can students see the hidden test cases?
Not with a stored problem: tests are hidden unless you set hidden to false, and the hidden tests and the checker are readable only with your API key. A candidate's result has a hidden test's verdict and nothing else. Keep the key on your server and return only the verdict. Drivers are not shown to candidates, but a candidate's program can read and print its own driver, so keep test data and anything sensitive out of drivers.
Can I host a coding contest for my college on OnlineCompiler.io?
Not as a hosted contest: there are no contest pages, sign-ups or scoreboards to switch on. The API judges each submission, and the rest is small: a problems table, a submit route that judges the code against a stored problem, and a leaderboard query. This page has all three.
Can it be the backend of a coding exam platform?
For the judging, yes: stored problems with hidden and visible tests, points, a time limit for each test and 46 languages. Proctoring, plagiarism checks, rosters and offline exams are yours to build or buy, and every run needs an internet connection to our servers.
Which languages can the judge accept?
Any of the 46 the API supports: Python (3.14), C (GCC 15), C++ (G++ 15), Java (OpenJDK 25), C# (.NET SDK 10), F# (.NET SDK 10), Go (1.26), Rust (1.93), PHP (8.5), Ruby (4.0), Haskell (GHC 9.12), TypeScript (Deno), JavaScript (Node.js 24), SQL (SQLite 3), DuckDB (1.5), Bash (5.2), Fortran (gfortran 15), Visual Basic (.NET SDK 10), Kotlin (2.4), R (4.6), Swift (6.4), COBOL (GnuCOBOL 3.2), Perl (5.44), Julia (1.13), Pascal (Free Pascal 3.2), Octave (11), Assembly (NASM 3), Lua (5.5), OCaml (5.4), Common Lisp (SBCL 2.6), Erlang (OTP 29), Elixir (1.20), Prolog (SWI-Prolog 10), D (LDC 1.43), FreeBASIC (1.10), Dart (3.13), Clojure (1.12), Groovy (6.0), Scala (3.10), Zig (0.17), Nim (2.2), Crystal (1.22), Ada (GNAT 15), PowerShell (7.6), Racket (9.3), Objective-C (Clang 21).