TinyServe
A from-scratch LLM inference runtime on llama.cpp — continuous batching, KV-cache accounting, prefix reuse and fair scheduling, built to be fully explainable
- Role
- Solo Developer
- Timeline
- Aug 2026 – Present
- Context
- Personal project · open source
- Links
- GitHub ↗
The real server running on llama.cpp with 2 decode slots: a burst of 16 requests streams through continuous batching, then the same 6 requests run under FIFO, Priority and WFQ, the scheduler hot-swapped on the live server between runs.
The outcome
- Admission backpressure verified under burst load: at 64 simultaneous requests, 42 were accepted and 22 rejected with 503 and Retry-After, matching the hand calculation of 128 KV blocks at 3 blocks per request.
- Scheduler fairness measured head to head (low/high-priority mean TTFT ratio): strict Priority 3.87×, WFQ 2.54×, FIFO 0.45×, so WFQ still favours high priority without starving the low class as hard.
- Prefix reuse on a shared-system-prompt workload: 47–70% of prompt tokens never reached llama_decode(), and TTFT p50 fell 1.4–1.9× across three paired runs. p95 showed no reliable effect and is reported that way.
- Aggregate throughput rose from 53.8 to 90.2 tok/s between 1 and 4 concurrent requests, then flattened to 96.1 at 16, exactly at the n_seq_max=4 slot limit (Qwen2.5-0.5B Q4_K_M on CPU).
- py-spy found 97.2% of wall time inside llama_decode(), in agreement with the server's own decode_step_duration_seconds metric (33.7 ms average decode); the ctypes batch fill costs under 2% of a full tick, so rewriting the Python layer in C++ was measured and rejected.
- Nine benchmark scripts with raw CSVs, a provisioned Grafana dashboard, and a native/Python prefix-cache pair held to identical behaviour by a 4000-op differential fuzz in CI.
The challenge
A small inference server built on llama.cpp, with everything above the matrix multiply written from scratch in async Python: admission control, continuous batching with chunked prefill, block-based KV-cache accounting, pluggable FIFO / Priority / WFQ scheduling, and prefix reuse through a C++ radix tree. llama.cpp computes the logits. TinyServe decides who gets a slot, what goes into each batch, when a request is refused, and how tokens reach the client. Every claim in the repo is backed by a benchmark run against a real model, including the ones that came out negative.
Continuous batching, paged KV memory and fairness-aware admission are usually learned by reading about vLLM and SGLang, whose implementations are too large to trace end to end. The goal was not to compete with them on throughput. It was to build the same ideas small enough that any latency number can be traced to a specific scheduling decision in the code, and confirmed by a metric rather than inferred.
The system
HTTP handlers never touch the model. POST /generate tokenizes the prompt, runs the Admission Controller, and pushes the request into a waiting pool; a single background asyncio task, the batch loop, owns every call into llama.cpp, so its state needs no locks. Admission is fail-fast and runs two checks in order: queue depth against max_queue_depth, then a worst-case reservation of prompt + max_tokens in the KV Cache Manager, a logical block ledger over one llama_context created with kv_unified=True. Either failure returns 503 with Retry-After and a distinct reason, so an accepted request is guaranteed room to finish. Each tick the loop expires stale waiters, lets the active policy choose which waiters claim free sequence slots, and asks the prefix cache whether another live sequence already holds a block-aligned prefix of the prompt; on a hit, llama_memory_seq_cp shares the donor's cells and the new sequence starts at a non-zero n_past. The Batch Builder then packs decode steps first and caps each prefill at chunk_size, and one llama_decode() call, run off the event loop in a worker thread, advances every active sequence together; greedy-sampled tokens stream out over SSE through the Stream Manager's incremental UTF-8 decoder. On finish the sequence is evicted from the prefix tree before its seq_id returns to the free pool, then its KV cells and blocks are released. A decode error finishes every active request with a labelled cancellation instead of wedging the loop.
The hard parts
Proving multi-sequence batching before building on it
The whole design depends on one llama_decode() call advancing several independent requests, and llama-cpp-python's high-level Llama class does not expose that. It was proven first with a standalone proof-of-concept against the low-level ctypes API. The Runtime now keeps the Llama object only for weights and tokenizer, and builds its own context with n_seq_max slots and a unified KV cache.
What a policy can actually control under continuous batching
Once a sequence holds a slot it advances every tick, whatever the policy says. The one real lever left is which waiting request claims a slot when one frees up, so FIFO, Priority and WFQ are implemented as three answers to that question behind one select() protocol. WFQ charges 1/weight of virtual time per admission, and a returning class adopts the current minimum instead of zero, so it gets no head start.
Prefix reuse that fails as wrong text, not a crash
If a finished sequence's seq_id were recycled while the tree still listed it as a donor, the next match would copy cells that now hold another prompt, producing fluent, plausible, wrong output. The batch loop evicts from the tree before the slot returns to the pool, and the Runtime checks the donor still covers the range before copying, falling back to a full prefill when it does not. Matches are also clamped to leave one block to prefill, because a fully reused prompt would have no batch row, never sample a token, and hold its slot forever.
A benchmark that argued against its own hypothesis
Chunked prefill was expected to protect short requests' tail latency from a long prompt. At chunk_size 32 versus effectively unchunked, short-prompt TTFT p95 was 2.67s against 2.51s: no meaningful difference. The mechanism was traced instead of tuned away. build_batch sorts by pending-token count, so short work is always packed ahead of a long prefill regardless of chunk size.
Checking the shipped code against the design doc
A pass over the code against the PRD found the Admission Controller checked only KV budget, so a burst of small requests could grow the waiting pool without bound. A queue-depth check now runs first and rejects with its own queue_full reason. The same pass walked back a sustained-load write-up that claimed no drift or leak from a 15-second run, and listed the remaining gaps in the architecture doc: no rate limiter, no LRU eviction, no structured logging.
Continuous batching on the live server: 16 requests, 2 decode slots — two stream at a time, and a finished stream hands its slot to the next request.
What I took from it
- Validate the riskiest architectural bet with a throwaway proof-of-concept before building the system around the assumption it depends on.
- Once batching is continuous, a scheduling policy has exactly one lever, which request claims a free slot. Describing it as more than that would misrepresent the code.
- Measure before choosing a language. The profiler said C++ would buy nothing on the hot path, so the C++ that did ship is there for portability into llama.cpp's own server, and the repo says so.
- A result that fails to show the expected effect is still a result if the mechanism is named. So is a 15-second run that cannot support a leak-freedom claim.
Stack
- Runtime
- llama.cpp, llama-cpp-python (ctypes), Python 3.11, asyncio
- Scheduling
- Continuous batching, Chunked prefill, FIFO / Priority / WFQ
- Prefix cache
- C++ radix tree, flat C ABI, CMake, Python fallback
- Serving
- FastAPI, SSE streaming
- Observability
- Prometheus, Grafana, OpenTelemetry, py-spy
- Quality
- pytest, mypy --strict, ruff, ctest, Docker Compose
Timeline
- Aug 2026
Phases 0-1: bare execution loop against llama.cpp, then SSE streaming behind a single-consumer queue.
- Aug 2026
Phase 2: real multi-sequence continuous batching, KV block accounting and admission control, validated by a standalone POC first.
- Aug 2026
Phase 3: chunked prefill, FIFO/Priority/WFQ policies, cancellation and timeouts.
- Aug 2026
Phase 4: Prometheus metrics, OpenTelemetry tracing, a Grafana dashboard and a py-spy profiling session.
- Aug 2026
Benchmark suite and architecture docs; a check against the PRD added the missing queue-depth admission check.
- Aug 2026
Phase 5: prefix cache as a C++ radix tree with a Python fallback, plus a /demo page with live policy hot-swap.