All my work / AI infrastructure · by Ravindra Sawant
Batchwise
LLM inference scheduler simulator: static vs continuous vs chunked-prefill batching.
Verified 2026-11-28; CI re-runs the acceptance tests on every push.
The problem
Model servers must share limited decode capacity among requests with different arrival times, prompt and output lengths. Static batches waste slots and short requests wait behind long prefills. This simulator makes the latency / throughput / fairness / memory-admission trade-off measurable without a GPU.
What I found
- Continuous batching cut makespan from 2,560 to 1,123 ticks at high load versus static cohorts; chunked prefill cut p95 time-to-first-token from 18.5 to 8 ticks at the same throughput.
- A dynamic-reservation mode livelocked (the same request was preempted and re-admitted every tick) until admission was frozen after a memory stall - a nice example of why vLLM-style schedulers prioritise preempted work.
- Every tick asserts capacity invariants (token budget, active sequences, block ownership), so any policy bug fails loudly instead of skewing results.
Architecture
trace.json ─► trace loader ─► arrival heap ─► admission (policy order, KV reservation)
│
policy.choose(queue, active, budget, ctx) ─► Plan(admit, work)
│
simulated prefill/decode backend (cost = tokens × weight ≤ token_budget)
│
state transitions + BlockPool accounting ─► Event log ─► metrics/report.json
Tick contract (order inside Scheduler.step)
- Idle fast-forward if nothing is queued/running.
- Move arrivals (
arrival <= tick) into the queue; apply due cancellations. policy.choosereturns admissions (strict policy order: the head blocks if it doesn't fit — no starvation of large requests in a finite trace) and work items.- Admissions reserve KV blocks all-or-nothing (
ceil(tokens / block_size)), never partially mutating counters. - Prefill chunks run, then decodes (or decode-first for
chunked). At most one decode token per sequence per tick. A sequence that finishes prefill in tick t emits its first token in tick t+1 (first_token= first decode). - Completions release blocks and emit exactly one terminal event.
- Invariants are asserted every tick: cost ≤ budget, active ≤ max_sequences, Σ owned blocks = pool.used ≤ capacity, every running sequence holds ≥ blocks for its live KV tokens.
Policies
| policy | admission | budget split | weakness |
|---|---|---|---|
| static | FCFS cohort, only when previous cohort drained | prefill-first | idle slots while the longest member finishes |
| continuous | FCFS, refill freed slots every tick | prefill-first | long prompt monopolises a tick → short TTFT and decode stalls |
| chunked | priority + aging (priority + aging_rate × waited) | decode-first, then ≤ prefill_chunk per prompt, then leftovers | slightly slower long-prompt prefill |
Memory modes
reserve=max(default, MVP): admission reservesprompt + max_newblocks. Deadlock-free, may idle blocks.reserve=dynamic(P1): admission reserves prompt blocks only; decode grows on block boundaries. On a stall the youngest sequence is preempted (blocks released, later re-prefilled with prompt+generated tokens = recompute) and admission freezes until something finishes, which guarantees the oldest sequence progresses.
Requirements → tests
| Req | Pri | Requirement | Proven by | Status |
|---|---|---|---|---|
| FR-01 | P0 | Request intake: validate IDs/tokens, statuses queued/running/completed/canceled/rejected | T01, T03 | pass |
| FR-02 | P0 | FCFS static and continuous batching behind one policy interface, token budget + max sequences | T02, T04 | pass |
| FR-03 | P0 | KV block charging/release, queue when full, reject never-fitting requests | T03, T04 | pass |
| FR-04 | P0 | Event log + metrics: queue depth, active seqs, block utilization, TTFT, ITL, E2E | T01, T04 | pass |
| FR-05 | P1 | Chunked prefill, aging fairness, cancellation, same-trace policy comparison | T05, T03 | pass |
| Test | What it proves | Result |
|---|---|---|
| T01 | Single request (prompt 8, out 3, budget 4): prefill + exactly three decodes, TTFT from log | pass |
| T02 | Long+short together: static cohort semantics vs continuous slot replacement | pass |
| T03 | Infeasible, duplicate, cancel in queue and during decode; unique terminal events, no leaks | pass |
| T04 | Overload: per-tick token/memory bounds, progress, deterministic replay (all policies, both reserve modes) | pass |
| T05 | Aging stress: old low-priority request vs burst of younger high-priority requests | pass |
Benchmark
| Target (hypothesis from the spec) | Goal | Actual | |
|---|---|---|---|
| low load: >=10% shorter makespan or better TTFT vs static | hypothesis | continuous makespan 3969.5 vs static 4016.5; ttft_p95 2.5 vs 129.5 | met |
| medium load: >=10% shorter makespan or better TTFT vs static | hypothesis | continuous makespan 2022 vs static 2538; ttft_p95 3 vs 590.5 | met |
| high load: >=10% shorter makespan or better TTFT vs static | hypothesis | continuous makespan 1123 vs static 2560.5; ttft_p95 18.5 vs 1396 | met |
high_makespan_static= 2560.5high_makespan_continuous= 1123high_makespan_chunked= 1123high_ttft_p95_static= 1396high_ttft_p95_continuous= 18.5high_ttft_p95_chunked= 8
quick run · 2026-11-28T23:56:56+00:00 · Units are simulated ticks/token-cost units; wall-clock only measures simulator overhead.
Design questions
Why does continuous batching help?
It refills slots as soon as a sequence finishes while others keep decoding, so fewer slots idle. Cost: scheduler complexity and a different latency distribution.
What distinguishes prefill and decode?
Prefill processes all prompt tokens and populates KV state (compute-bound, parallel); decode emits one token per step reading that state (memory-bound). Real costs depend on model, hardware, sequence length and kernels - unlike this simple cost model.
How would you prevent KV deadlock?
Reserve worst-case capacity at admission (this MVP), or allow controlled preemption with recompute/swap. Never hold blocks while waiting forever for another block.
How do you handle overload?
Bound queues, reject infeasible work, enforce deadlines and rate limits, and expose queueing and tail latency rather than hiding failed requests.
How would you productionize it?
Connect a real backend, calibrate cost per shape, make dispatch and cancellation asynchronous, add multi-GPU placement and validate real TTFT/TPOT and memory telemetry.
Limitations
- No GPU, tokenizer, HTTP server or speculative decoding
- Ticks are simulated units; wall-clock only measures simulator overhead
Run it
git clone https://github.com/ravirs/batchwise.git && cd batchwise
pip install -r requirements.txt
PYTHONPATH=src python -m infsched demo # demo
PYTHONPATH=src python -m pytest -q # test
PYTHONPATH=src python benchmarks/bench.py --quick # benchMore systems I've built from scratch
Storage & data systems
- Strata LSM-tree key-value storage engine: WAL, SSTables with Bloom filters, atomic manifest, compaction
- Tidelog Kafka-style durable partitioned log broker: CRC'd records, offsets, generation-fenced consumer groups
- Floe Iceberg-style table format: immutable Parquet, manifests, snapshots, time travel, compare-and-swap commits
- Flint Spark-style batch engine: lazy lineage, stage planning, shuffles, broadcast and salted skew joins
- Watermark Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints
- Warden Data governance catalog: explainable grants, row filters, column masks, lineage impact
- SnapshotDB MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode
AI infrastructure
- Nearline HNSW-style vector search index from scratch, measured against exact search
- KVPager Paged KV cache with copy-on-write forks and prefix reuse (PagedAttention-style)
- Steadyhand Durable AI agent runtime: allowlisted tools, approvals, budgets, crash recovery, replay
- Toolgate Model Context Protocol gateway: curated tools, signed identity, tenant policy, approvals, audit