Phase 06/Shipping and being seen/Systems languages for inference: C++, Rust, Go
PHASE 06 · Shipping and being seen

Systems languages for inference: C++, Rust, Go

0%
14 h7 subtopics3 lessons · 2 required
In plain English

Most model code is written in Python because it is quick to change, but Python is slow at the plumbing: handling thousands of network connections, shuffling bytes, deciding every few milliseconds which requests run next. Serving systems therefore keep Python for the model and write the plumbing in faster languages. C++ sits closest to the GPU and inside the engines, Rust powers request routers and new serving runtimes, and Go runs the cluster control planes that start and stop machines. Think of a hospital where doctors (Python) make the decisions but the building's power, water and paging systems (C++, Rust, Go) must never hiccup. This topic has you build small pieces in each language that mirror real serving components, so you can read and contribute to the parts of an inference stack that are not Python.

Why it matters

Fifteen of the forty-six postings require C++, ten Rust and ten Go. Perplexity is replacing Python serving with a Rust runtime, Modal builds its runtime in Rust and Go, and every engine's scheduler and kernels are C++. Being able to write a streaming proxy in Rust or a scheduler in C++ with Python bindings is the difference between tuning an engine and extending it.

Hiring signal

Perplexity's inference role develops an internal Rust-based inference server to escape Python's overhead under rapidly growing traffic; Modal wants strong Rust or Go with an interest in becoming productive in both; Cerebras and Liquid AI require strong C++ and Python with multithreading and memory management experience for performance-sensitive code.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Poolside, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Write a Rust asynchronous HTTP proxy with Tokio and axum that streams OpenAI-compatible responses and coalesces identical in-flight requests.
  • Implement a continuous-batching scheduler in C++17 and expose it to Python with pybind11, matching a Python reference exactly.
  • Read a production Rust serving component (the TGI router) and map its queue, batcher and token budget to the concepts from Phase 3.
  • Explain where Go is used in inference infrastructure (Kubernetes controllers, gateways) and read a controller reconciliation loop.
  • Choose a language for a new serving component with a stated argument about latency, safety, ecosystem and team.

Key concepts

Async runtime
Tokio in Rust and asyncio in Python schedule many in-flight requests on few threads; the proxy and router pattern depends on it.
Ownership and borrowing
Rust's compile-time rules that prevent data races and use-after-free, which is why control-plane and runtime code is moving to Rust.
Request coalescing
Detecting identical in-flight requests and serving all callers from one upstream call, a cheap win for retried or duplicated agent requests.
Server-sent events (SSE)
The streaming format OpenAI-compatible APIs use for tokens; a proxy must forward chunks without buffering the whole response.
pybind11
Header-only library for exposing C++ classes and functions to Python; how engines ship C++ schedulers and ops behind Python APIs.
GIL release
Dropping Python's global interpreter lock while C++ code runs so other Python threads make progress; essential for a scheduler called from an async server.
Token budget scheduling
The engine scheduler's rule of admitting prefill and decode work up to a per-step token limit, as in vLLM V1 and TGI's max_batch_prefill_tokens.
Reconciliation loop
The Go controller pattern that repeatedly compares desired and actual state of a resource and acts on the difference; how GPU fleets are managed on Kubernetes.
FFI boundary cost
The overhead of crossing between Python and native code per call; it decides how coarse-grained a native API must be.

Subtopics

  1. 1. Where each language lives in a serving stack

    Python for model code and glue, C++ for kernels and engine cores (TensorRT-LLM, vLLM csrc), Rust for routers and runtimes (TGI router, mistral.rs, candle), Go for Kubernetes controllers and gateways.

  2. 2. Modern C++ for inference servers

    C++17/20 features that matter (move semantics, std::variant, spans, coroutines), threads and lock-free queues, RAII for GPU resources, sanitizers.

  3. 3. Binding C++ to Python

    pybind11 modules, GIL release, zero-copy views of tensors and NumPy arrays, torch custom ops as the engine-facing variant.

  4. 4. Rust for serving

    Tokio, axum or hyper, reqwest streaming, serde for OpenAI schemas, error handling with Result, backpressure with bounded channels.

  5. 5. Reading the TGI router

    Validation, queue, batcher and token-budget logic in Rust; how it mirrors the Python scheduler in vLLM and where it differs.

  6. 6. Go for control planes

    controller-runtime reconciliation loops, informers, CRDs for model deployments, gateways; reading a small controller end to end.

  7. 7. Linux systems knowledge for the runtime layer

    Processes and signals for graceful drain, sockets and epoll under async runtimes, cgroups and namespaces for container runtimes, NUMA pinning for GPU hosts.

Resources

course
repo

Hands-on lessons

L1

Rust OpenAI-compatible streaming proxy with request coalescing

CPU · your Macscript240 minrequired

Goal · A Rust service that accepts /v1/chat/completions, streams SSE chunks from an upstream (the Phase 5 stub server), coalesces identical concurrent requests into one upstream call, and passes a load test.

  1. 1cargo new llm_proxy; add axum, tokio, reqwest (stream feature), serde, serde_json, sha2 and tokio-stream.
  2. 2Define the request and chunk structs with serde matching the OpenAI chat schema (messages, model, stream, max_tokens; choices with delta content).
  3. 3Implement a handler that forwards the request to the upstream URL and relays SSE chunks to the client as they arrive using a streaming body; verify the first chunk reaches the client before the upstream finishes.
  4. 4Add coalescing with a DashMap or Mutex<HashMap> keyed by a hash of the canonicalised request body; the first caller creates a tokio broadcast channel and performs the upstream call, later identical callers subscribe to it.
  5. 5Add a 429 response when in-flight requests exceed a configurable limit, and a /metrics endpoint with request, coalesced and shed counters.
  6. 6Run cargo clippy and cargo fmt; add an integration test with a mock upstream that counts calls.
  7. 7Load test with 50 identical concurrent requests and with 50 distinct ones against the stub server, counting upstream requests from the stub's logs.
Deliverable
The llm_proxy crate with tests, and a load test log.
Check
With 50 identical concurrent requests the upstream receives exactly 1 request and all 50 clients receive the full stream; with 50 distinct requests the upstream receives 50; cargo clippy reports zero warnings; the first SSE chunk is delivered to the client before the upstream stream completes.
L2

C++17 continuous-batching scheduler with pybind11 bindings

CPU · your Macscript240 minrequired

Goal · A token-budget scheduler in C++17 exposed to Python via pybind11 that reproduces a Python reference step for step on a request trace and runs at least 10x faster.

  1. 1Write scheduler.py, a Python reference with a waiting queue, a running set, a per-step token budget (for example 2048), chunked prefill, one decode token per running request and preemption of the newest request when KV blocks (a counter) run out.
  2. 2Write scheduler.hpp/.cpp in C++17 with the same semantics; use std::deque for the waiting queue, a struct per request, and return per step a vector of (request_id, tokens_scheduled) pairs plus preempted ids.
  3. 3Expose Scheduler with pybind11 (add_request, step, state) and build with a setup.py or CMake; release the GIL inside step.
  4. 4Generate a trace of 2000 requests with random prompt and output lengths; drive both schedulers from Python with the same trace and seed and compare the step outputs for equality.
  5. 5Benchmark 100,000 steps of each on the trace and report the ratio; profile the Python version with cProfile to name the hot spot.
  6. 6Build with -fsanitize=address,undefined once and run the trace to confirm no memory errors.
  7. 7Write a note on which parts of a real engine scheduler (vLLM V1) would need to stay in Python and why.
Deliverable
scheduler.py, the C++ sources, the pybind11 module, equality test and benchmark output.
Check
The C++ and Python step outputs are identical for all steps of the 2000-request trace; the C++ scheduler is at least 10x faster over 100,000 steps; the sanitizer run reports no errors.
L3

Read the TGI router and a Go controller

CPU · your Macreading-code150 minoptional

Goal · Annotated walkthroughs of the TGI Rust router request path and of a controller-runtime example in Go, mapping each to the Phase 3 and Phase 5 concepts.

  1. 1Clone text-generation-inference; starting at router/src/server.rs find the chat completions handler and follow into the validation module and infer.rs.
  2. 2Open router/src/queue.rs (or its current equivalent) and annotate how the queue forms the next batch under max_batch_prefill_tokens, max_batch_total_tokens and waiting_served_ratio; record path:line for each parameter's use.
  3. 3Find where the router streams tokens back to the client and how it handles client disconnects.
  4. 4Write a table mapping TGI router concepts (queue, batcher, token budget, prefill chunking) to the vLLM V1 scheduler concepts from p6-reading-vllm-source.
  5. 5Clone controller-runtime; read the example controller under examples and annotate the Reconcile function, how it requeues, and how an informer feeds it events.
  6. 6Write a half-page on what a GPU model-deployment CRD controller would reconcile (replicas, model version, placement) and which failure modes from Phase 5 it would detect.
Deliverable
tgi-router-notes.md and go-controller-notes.md with path:line references.
Check
The TGI notes contain at least 10 path:line references and locate the three batching parameters; the Go notes identify the Reconcile function signature and the requeue mechanism.

Build your own

Build your own Rust inference router

RustCPU · your Mac~12 h

An OpenAI-compatible HTTP router in Rust that streams SSE from upstream engines, coalesces identical in-flight requests, retries and fails over between backends, and exposes Prometheus metrics.

The real thing: github.com/huggingface/text-generation-inference/tree/main/router ↗

How you know a stage passes

Integration tests live in tests/ and start the router against two instances of the Phase 5 stub engine (a Python server that streams fake tokens with configurable delay and failure injection) on random ports. Each stage adds a `#[tokio::test]` that drives the router with reqwest and asserts on responses, upstream request counts (the stub exposes /stats) and /metrics text. `cargo test` must pass and `cargo clippy -- -D warnings` must be clean for a stage to count; stage 6 adds a k6 or oha load test whose summary JSON is checked by a test.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01non-streaming proxy
    An axum server accepting POST /v1/chat/completions that validates the JSON body with serde, forwards it to one upstream with reqwest, and returns the upstream JSON unchanged.
    test · A test posts a request and receives the stub's completion with identical id and choices fields; a malformed body returns 400 with an OpenAI-style error object; `cargo clippy -- -D warnings` passes.
  2. 02SSE streaming passthrough
    With stream: true the router returns text/event-stream and forwards each upstream chunk as it arrives using a bounded tokio channel, ending with the data: [DONE] sentinel.
    test · The first SSE chunk reaches the client before the upstream finishes (measured with a 50 ms per-token stub delay and 20 tokens, first-chunk latency under 200 ms) and the concatenated chunks equal the non-streaming content.
  3. 03request coalescing
    Identical concurrent requests (same body hash, temperature 0) share one upstream call; later arrivals subscribe to a broadcast of the stream and receive the chunks already sent.
    test · 50 identical concurrent streaming requests produce exactly 1 upstream request in /stats and all 50 clients receive the full stream; 50 distinct requests produce 50 upstream requests.
  4. 04multiple backends and failover
    A backends list with health checks every second; requests go to healthy backends by least in-flight; an upstream connection error or 5xx before the first byte is retried on another backend with a budget of 2 retries and exponential backoff.
    test · With backend A set to fail 100 percent, 100 requests all succeed via B and /stats shows A received at most 100 attempts and B received 100 completions; a stream that fails after the first byte is not retried and the client sees an error event.
  5. 05metrics, timeouts and admission control
    /metrics exposes request counts by backend and status, TTFT and end-to-end latency histograms, in-flight gauges and coalescing hits; per-request timeouts and a max in-flight limit return 503 with Retry-After when exceeded.
    test · After 200 requests /metrics contains router_requests_total with status labels summing to 200, a ttft_seconds histogram with nonzero counts, and with max_in_flight 10 and 50 slow concurrent requests at least 30 clients receive 503 while the rest succeed.
  6. 06load test and release build
    A `cargo build --release` binary with a TOML config file, structured JSON logs with request ids, and a load test script (oha or k6) that records throughput and latency percentiles against two stubs.
    test · At 500 concurrent streaming requests the router adds under 5 ms of p50 and under 20 ms of p99 latency over the stub alone, zero errors are reported, and RSS stays under 100 MB (checked from the load test summary and ps).

Knowledge check

QWhy do serving teams move routers and runtimes to Rust rather than optimising Python?

Python's GIL and per-request overhead cap connection handling and add latency jitter; Rust gives predictable latency and memory safety without a garbage collector, while keeping the model code in Python.

QWhat must a C++ function called from an async Python server do to avoid stalling the event loop?

Release the GIL for the duration of the native work and keep the call coarse-grained so the FFI crossing cost is amortised.

QWhat does request coalescing exploit and when is it unsafe?

Identical in-flight requests (retries, duplicated agent calls) can share one upstream generation; it is unsafe when sampling is non-deterministic and callers expect independent samples, or when requests carry per-user state.

QWhat is a reconciliation loop and why does GPU fleet management use it?

A controller repeatedly compares desired state (a CRD) with actual state and acts to close the gap; it is robust to missed events and restarts, which matters when nodes and GPUs fail unpredictably.

QWhich language would you pick for a new KV-cache-aware gateway and why?

Rust or Go, because the component is network-bound and latency-sensitive with no GPU code; Rust for tighter latency and safety, Go when it must integrate with Kubernetes controllers and the team already writes Go.

Completion

  • All 7 subtopics marked done
  • All 2 required lessons done
  • Lesson l1 proxy passes the coalescing and streaming checks with zero clippy warnings.
  • Lesson l2 scheduler matches the Python reference and meets the speed ratio.
  • Can explain where C++, Rust and Go each sit in an inference stack with one real example per language.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →