building a distributed code execution engine that survives failure
how we built aethercode's distributed judge, kept submissions recoverable, and started moving from go to rust without breaking production.
# contents (29)›

Engineering focus: durable execution, controlled concurrency, bounded resource consumption, and consistent verdicts across implementation changes.
building a code judge sounds pretty straightforward. take some code, run it against test cases, return a verdict. but once thousands of students start submitting at the same time, you're no longer just building a code runner. you're dealing with scheduling, resource limits, failed workers and state that has to survive all of it.
that's the problem i've been working on with AetherCode Execution Engine. it is an on-premise, distributed execution and evaluation system built around Go, Redis Streams, PostgreSQL and go-judge, with a Rust implementation being introduced alongside the existing Go production path.
we handle more than 60,000 submissions a month. in a separate Rust stress test, we simulated 20,000 concurrent students. monthly usage and a controlled load test are two different things, so i'll keep those numbers separate throughout this post.
here's how we built it, what happens when things fail, and why we're moving parts of the engine from Go to Rust.
01. separating the application from execution
a coding assessment platform has responsibilities that do not belong inside a judge: identity, question authoring, assessment timers, tenant management, results and analytics. AetherCode separates these application concerns into eleven Go services with their own PostgreSQL databases and communication through gRPC and NATS JetStream.
the execution engine is a separate boundary. its job is to accept execution requests, schedule work, enforce resource limits, evaluate outputs and report results. the surrounding platform does not need to know how a particular programming language is compiled or how a failed worker is recovered.
this separation also makes the engine usable independently of the assessment application. its public repository is licensed under Apache-2.0.
a simplified request path looks like this:
client / assessment platform
|
HTTP gateway
|
PostgreSQL + Redis Streams
|
execution workers
|
go-judge sandbox
|
output evaluator
|
durable verdict + SSE events
each boundary has a distinct responsibility. the gateway is not the compiler; the queue is not the permanent record; the sandbox is not the grading policy; and an SSE connection is not the source of truth.

Architecture diagram from the execution engine repository.
component responsibilities
| component | responsibility | failure consideration |
|---|---|---|
| HTTP gateway | validation, admission, job identity | retry and backpressure |
| PostgreSQL | durable submission and verdict records | reconciliation and conditional transitions |
| Redis Streams | scheduling and pending work | reclaim unacknowledged messages |
| worker pool | compilation and test orchestration | bounded concurrency |
| go-judge | isolated execution | CPU, memory and time budgets |
| SSE | progressive client updates | reconnect and replay |
Design invariant: a disconnected browser must not be treated as a failed execution.
02. admission is part of the architecture
execution is expensive relative to accepting an HTTP request. a client can send work much faster than a bounded pool of compiler and sandbox processes can consume it.
the gateway therefore validates requests, checks rate limits and queue depth, assigns a UUIDv7 job identifier, persists the submission in PostgreSQL and enqueues execution data in Redis. we use admission control that rejects new work with HTTP 429 when configured capacity is exceeded.
this is an important distinction between accepting work and completing it. a fast ingestion endpoint does not imply that every submission finishes at the same speed. compilation, test count, language runtime and resource contention all affect completion latency.
the API also supports idempotency keys. a retry from a client should not necessarily mean a second logical submission. idempotency is particularly valuable when a connection fails after the server has accepted a job but before the client receives its response.
backpressure makes overload visible instead of allowing an unbounded backlog to silently turn a responsive service into a failing one.
example execution request
The following is a small example using the documented API contract, not a production credential or recorded request.
curl -X POST http://localhost:5100/api/v1/execute \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: demo-sum-001' \
--data '{
"language": "python",
"source_code": "print(sum(map(int, input().split())))",
"tests": [
{"input": "10 20 30", "expected_output": "60"}
],
"checker": "token",
"priority": "run",
"time_limit_ms": 2000,
"memory_limit_kb": 262144
}'
| response | meaning |
|---|---|
| 201 | submission accepted |
| 400 | invalid request |
| 401 | authentication failed |
| 429 | rate or admission limit reached |
| 500 | internal processing failure |
Acceptance is asynchronous: a successful request is not itself a successful test verdict.
03. queues are a scheduling policy, not just a transport
there are three distinct classes of work in our engine:
- run: interactive executions initiated while a student is developing a solution.
- submit: formal graded assessment submissions.
- bulk: re-evaluations and background workloads.
treating all three as one FIFO stream is simple, but it couples workloads that have different latency and fairness requirements. a bulk regrade should not monopolize the same capacity used by students actively writing code. conversely, interactive runs should not prevent formal submissions from progressing.
the engine uses Redis Streams with consumer groups and configurable weighted scheduling. the worker can consume from different streams according to the selected policy, while blocking reads avoid busy-waiting when there is no work.
Redis Streams are useful here because a delivered message is not immediately forgotten. a consumer group tracks pending messages until acknowledgement, giving the system a mechanism for recovering work when a consumer stops.
the key architectural idea is to treat queue design as a resource allocation decision. throughput alone is not enough; the system must decide whose work gets access to finite execution capacity.
queue isolation in practice
interactive run ──┐
graded submit ──┼── weighted scheduler ── bounded workers
bulk evaluation ──┘
| class | latency objective | scheduling concern |
|---|---|---|
| run | responsive feedback | prevent interactive starvation |
| submit | dependable assessment progress | sustain formal grading |
| bulk | background throughput | avoid crowding out live activity |
The weights are configuration decisions, not universal performance constants.
04. design for the worker that never comes back
the happy path is straightforward. a worker receives a job, runs it, records a result and acknowledges the message.
what happens if the worker crashes somewhere in between? a process can terminate after receiving a job, after compiling a program, or after persisting a result but before acknowledging the queue message. each boundary introduces a different recovery problem.
we deal with this in three ways.
pending-message recovery
Redis XAUTOCLAIM allows stale, unacknowledged messages to be reclaimed by surviving consumers. work assigned to a failed process can therefore be picked up again rather than remaining indefinitely attached to that process.
orphan reconciliation
PostgreSQL is also checked for submissions that remain queued beyond the expected interval. a background reaper can re-enqueue these jobs, addressing cases where durable state exists but queue delivery needs repair.
this matters because PostgreSQL and Redis are separate systems. their writes should not be described as one atomic transaction. reconciliation is part of the design precisely because the boundary can fail.
dead-lettering
a repeatedly failing message is not allowed to retry forever. our retry policy routes exhausted jobs into a dead-letter stream with diagnostic metadata.
dead-lettering separates persistent processing failures from ordinary execution traffic. it creates an operational surface for investigation without letting one problematic message endlessly consume worker capacity.
together, these mechanisms favor recoverable processing over the assumption that a worker will always finish its assignment.
failure matrix
| failure | recovery mechanism | remaining concern |
|---|---|---|
| worker stops before acknowledgement | reclaim pending message | repeated execution |
| durable queued job lacks delivery | orphan reconciliation | duplicate enqueue |
| repeated processing failure | dead-letter routing | operator investigation |
| late competing result | conditional state transition | reconcile side effects |
| client disconnects | event replay / reconnect | durable result remains authoritative |
RECEIVE -> EXECUTE -> PERSIST -> ACK
| | |
+---------+----------+--> recovery / reconciliation
Important: recoverability and exactly-once execution are different guarantees.
05. durable state and duplicate execution
message recovery comes with a trade-off: the same logical job may be delivered again. reclaiming a pending message does not prove that its previous worker performed no work.
the engine uses conditional PostgreSQL state updates to protect terminal verdicts. a completed or failed submission should not be blindly overwritten by a late result from another processing attempt.
this is the distinction between delivery semantics and application semantics. retryable delivery does not automatically provide exactly-once execution. instead, the application needs state transitions that remain correct under retries and concurrent activity.
a useful way to reason about a job is as a state machine:
queued -> compiling -> running -> terminal verdict
individual execution paths can differ, and interpreted languages may skip compilation, but terminal state must remain durable.
Redis is responsible for scheduling and event transport. PostgreSQL stores the submission and result records. maintaining that distinction gives recovery routines something durable to reconcile against.
illustrative conditional state transition
-- conceptual SQL, not a verbatim repository query
UPDATE submissions
SET status = 'completed'
WHERE id = $1
AND status NOT IN ('completed', 'failed');
Checking affected rows lets a caller distinguish a newly applied transition from a state that was already terminal. Real persistence also needs to handle result records and transaction boundaries consistently.
06. running untrusted code is a security boundary
a judge executes programs supplied by other people. the application cannot assume that submitted code behaves well, exits promptly, or uses a reasonable amount of memory.
we use execution through go-judge with Linux isolation mechanisms including cgroups v2, namespaces, seccomp filtering, restricted filesystems and bounded execution budgets.
these mechanisms address different parts of the problem. cgroups constrain resource consumption. namespaces reduce visibility into the host and other processes. syscall filtering restricts the available kernel interface. time and output limits bound the amount of work a submission can impose.
the compiler and test runner also need explicit policies. the engine documents supported languages, validated multi-file submissions and whitelisted compiler flags rather than treating arbitrary command construction as a feature.
none of this should be interpreted as a proof that sandbox escape is impossible. kernel-based isolation must be configured, maintained and tested as an ongoing security responsibility. development container configuration is not a substitute for production isolation.
security is part of execution correctness, not a feature that can be added after the scheduler is finished.
isolation layers
| layer | purpose |
|---|---|
| cgroups v2 | CPU, memory and process budgets |
| namespaces | isolate process and network visibility |
| seccomp | constrain kernel syscall access |
| restricted filesystem | limit writable state |
| execution watchdog | stop work exceeding its budget |
These controls are complementary; none alone constitutes a complete security boundary.
07. delivering verdicts without constant polling
a student waiting for a result wants progress, not a spinner backed by hundreds of identical status requests.
the engine exposes Server-Sent Events for execution lifecycle updates. our event model includes QUEUED, COMPILING, RUNNING, TEST_RESULT and VERDICT.
SSE fits this workload because the dominant communication pattern is server-to-client. once a submission is accepted, the client mostly needs to receive updates until the execution terminates.
the subtle issue is reconnection. a client can disconnect while a test case finishes or between the final database write and event delivery. we use historical event replay and subscription ordering intended to close the gap between past and live events.
the gateway subscribes before replaying historical events, avoiding the obvious race where an update is published after replay but before the live subscription is established.
the durable result remains distinct from its delivery mechanism. a temporary network failure should not mean that the execution itself has disappeared.
example event stream
event: QUEUED
data: {"type":"QUEUED"}
event: COMPILING
data: {"type":"COMPILING"}
event: RUNNING
data: {"type":"RUNNING"}
event: VERDICT
data: {"type":"VERDICT"}
This abbreviated example omits identifiers, timestamps and other fields from the actual API. The client should not assume every job includes a compilation step.
08. optimizing the grading hot path
output comparison is easy to overlook next to compilation and sandbox execution. nevertheless, it is repeated for every test case, and unnecessary allocations can accumulate under concurrent workloads.
the evaluator supports exact, token and floating-point comparison. exact comparison normalizes line endings and trailing whitespace. token comparison walks whitespace-delimited values. floating-point comparison applies a numeric tolerance.
our implementation uses cursor-based scanning rather than allocating normalized copies or arrays for each comparison. the Rust path adds SIMD-oriented fast paths.
our benchmarks show 33.19 ns for its exact checker benchmark and 116.96 ns for token checking, both at zero bytes allocated per operation. these are microbenchmarks of the evaluator, not measurements of complete submission latency.
this is a useful example of optimizing at the correct granularity. a fast checker will not make a slow compiler disappear, but it can reduce repeated memory allocation and CPU work in the grading subsystem.
the engine also documents compilation artifact caching based on cryptographic hashes. when a valid compiled artifact is already available, repeating compilation can be avoided. correctness of cache identity and isolation matters more than maximizing hit rate.
comparison modes
| checker | interpretation |
|---|---|
| exact | line endings and trailing whitespace normalized |
| token | compare whitespace-delimited values |
| float | compare numeric values with tolerance |
The allocation figures below describe isolated evaluator microbenchmarks, not a full sandbox run.
| reported checker | time/op | memory/op |
|---|---|---|
| exact | 33.19 ns | 0 B |
| token | 116.96 ns | 0 B |
09. evolving from Go to Rust without breaking production
right now, we're maintaining two implementations of the engine. Go remains the live production path during the documented shadow-comparison and cutover process. Rust is the forward path.
a rewrite is not complete just because the replacement compiles or wins a benchmark. the new implementation must preserve the execution contract expected by clients and operators.
both implementations share the HTTP API, Redis stream layout, PostgreSQL migrations and Prometheus metric names. these common boundaries reduce the amount of surrounding infrastructure that must change with the implementation.
we also use a compare-only Rust shadow worker. its verdicts can be compared with the existing engine without writing production PostgreSQL results.
shadow comparison provides a way to evaluate behavioral differences before transferring responsibility for live traffic. this is especially important for grading systems, where a faster implementation that returns a different verdict is not an acceptable replacement.
the Rust implementation uses optimizations including reduced cloning on Redis enqueue operations, concurrent admission checks, allocator selection and release-time link optimization. these are implementation-level changes within a shared system contract.
the migration is best understood as an incremental replacement of an execution path, rather than an unconditional claim that one language is superior to another.
migration topology
production requests ──> Go engine ──> durable verdicts
|
comparison workload
|
Rust shadow
|
verdict diff
| concern | Go path | Rust path |
|---|---|---|
| role | live traffic | shadow / cutover candidate |
| source | cmd/ and internal/ | crates/ |
| interface | shared HTTP contract | shared HTTP contract |
| data model | shared migrations | shared migrations |
| shadow writes | production path | no production verdict writes |
The shared interface makes parity measurable instead of requiring clients to adopt a second API.
10. measuring the system
here are some numbers from our Rust engine tests:
| workload | reported result |
|---|---|
| 20,000-student stress test | 26,751 submissions |
| stress-test ingest p50 | 0.820 ms |
| stress-test throughput | 239.25 submissions/sec |
| stress-test lost jobs | 0 |
| stress-test error rate | 0.0% |
| HTTP ingest microbenchmark | 12,784 requests/sec |
| HTTP read microbenchmark | 44,833 requests/sec |
| exact checker microbenchmark | 33.19 ns, 0 B/op |
the numbers describe different workloads. the HTTP ingest benchmark measures request handling under its own test conditions. the stress test includes a much larger submission workload across C, C++, Python and Java. the checker benchmark measures an isolated computational operation.
in an earlier Go-engine test, we ran 15,000 submissions with 5,000 concurrent clients and observed zero lost jobs.
mixing these measurements into a single headline would obscure the actual system behavior. a useful benchmark report should say what was measured, under what workload, and which engine was running.
zero lost jobs in a test is evidence for the tested scenario. it does not establish that loss is impossible under every future failure mode.
reading benchmark results correctly
0.820 ms p50 ingest measures the median admission-side latency in the documented Rust stress test. It does not mean that compilation and all test cases complete in under one millisecond.
reproducibility checklist
- Record the engine version, workload and language mix.
- Distinguish ingestion latency from end-to-end verdict latency.
- Track unsuccessful and unfinished jobs, not just successful throughput.
- Compare verdict parity before changing the production engine.
- Record resource limits and machine configuration with any new benchmark.
11. operability is part of the product
a system running on campus infrastructure needs to be diagnosable without relying on the original developer to manually inspect every job.
we use structured logs, Prometheus metrics, profiling, health checks, graceful shutdown and database migrations. these are operational interfaces as much as the HTTP endpoints used by clients.
queue depth, pending work, execution failures and request latency are useful signals because they describe different parts of the pipeline. a healthy gateway does not necessarily imply healthy workers; a short request latency does not imply an empty queue.
graceful shutdown matters for the same reason as crash recovery: deployments and restarts should be planned around in-flight work rather than treating every process termination as harmless.
we provide Docker Compose, systemd deployment configuration and Kubernetes overlays. these support different operating environments without changing the underlying execution contract.
local smoke-test workflow
# commands documented in the project README
make up
curl -fsSL http://127.0.0.1:5100/api/v1/health | jq .
bash scripts/smoke_test.sh
make down
operational signals worth watching
| signal | what it helps diagnose |
|---|---|
| queue depth | backlog and admission pressure |
| pending messages | stalled or failed consumers |
| gateway latency | request-side saturation |
| worker errors | execution pipeline failures |
| terminal outcomes | completion and grading behavior |
The exact metric names and alert thresholds should come from the deployed engine version and workload, rather than invented defaults.
12. what this architecture taught me
what i've learned building this is that getting the right test verdict is only one part of correctness.
a submission must remain recoverable after a worker failure. competing workloads need scheduling policies. resource use must be bounded. terminal verdicts must survive retries. a reconnecting client should be able to recover progress. a faster replacement engine must preserve the existing contract.
each of these requirements affects a different part of the architecture, and no single database, language or framework solves all of them.
i care more about optimizations that preserve correctness than numbers that just look good in a benchmark. a faster evaluator reduces grading overhead. a recoverable queue improves failure handling. a durable state machine protects results. shadow comparison reduces migration risk.
i don't just want the engine to be fast. i want to know what it will do when a worker dies, the queue fills up, or we ship a new implementation. that's the part of building infrastructure i find most interesting.
source & further reading
- AetherCode Execution Engine , architecture, benchmarks, deployment and implementation.
- AetherCode platform , service boundaries and assessment integration.
the benchmark numbers above are from our project tests, not guarantees for every deployment. Go is still serving production traffic while we work through the Rust cutover.