All my work / AI infrastructure · by Ravindra Sawant

Batchwise

LLM inference scheduler simulator: static vs continuous vs chunked-prefill batching.

Python 3.11+ · standard library 633 lines of core code source on GitHub ↗ CI status

4/4 core requirements 13 tests passing 3/3 benchmark targets

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)

  1. Idle fast-forward if nothing is queued/running.
  2. Move arrivals (arrival <= tick) into the queue; apply due cancellations.
  3. policy.choose returns admissions (strict policy order: the head blocks if it doesn't fit — no starvation of large requests in a finite trace) and work items.
  4. Admissions reserve KV blocks all-or-nothing (ceil(tokens / block_size)), never partially mutating counters.
  5. 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).
  6. Completions release blocks and emit exactly one terminal event.
  7. 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

policyadmissionbudget splitweakness
staticFCFS cohort, only when previous cohort drainedprefill-firstidle slots while the longest member finishes
continuousFCFS, refill freed slots every tickprefill-firstlong prompt monopolises a tick → short TTFT and decode stalls
chunkedpriority + aging (priority + aging_rate × waited)decode-first, then ≤ prefill_chunk per prompt, then leftoversslightly slower long-prompt prefill

Memory modes

  • reserve=max (default, MVP): admission reserves prompt + max_new blocks. 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

ReqPriRequirement Proven byStatus
FR-01P0Request intake: validate IDs/tokens, statuses queued/running/completed/canceled/rejectedT01, T03pass
FR-02P0FCFS static and continuous batching behind one policy interface, token budget + max sequencesT02, T04pass
FR-03P0KV block charging/release, queue when full, reject never-fitting requestsT03, T04pass
FR-04P0Event log + metrics: queue depth, active seqs, block utilization, TTFT, ITL, E2ET01, T04pass
FR-05P1Chunked prefill, aging fairness, cancellation, same-trace policy comparisonT05, T03pass
TestWhat it provesResult
T01Single request (prompt 8, out 3, budget 4): prefill + exactly three decodes, TTFT from logpass
T02Long+short together: static cohort semantics vs continuous slot replacementpass
T03Infeasible, duplicate, cancel in queue and during decode; unique terminal events, no leakspass
T04Overload: per-tick token/memory bounds, progress, deterministic replay (all policies, both reserve modes)pass
T05Aging stress: old low-priority request vs burst of younger high-priority requestspass

Benchmark

Target (hypothesis from the spec)GoalActual
low load: >=10% shorter makespan or better TTFT vs statichypothesiscontinuous makespan 3969.5 vs static 4016.5; ttft_p95 2.5 vs 129.5met
medium load: >=10% shorter makespan or better TTFT vs statichypothesiscontinuous makespan 2022 vs static 2538; ttft_p95 3 vs 590.5met
high load: >=10% shorter makespan or better TTFT vs statichypothesiscontinuous makespan 1123 vs static 2560.5; ttft_p95 18.5 vs 1396met
  • high_makespan_static = 2560.5
  • high_makespan_continuous = 1123
  • high_makespan_chunked = 1123
  • high_ttft_p95_static = 1396
  • high_ttft_p95_continuous = 18.5
  • high_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   # bench

More 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

Distributed systems

  • Quorum Deterministic Raft consensus simulator with fault injection and an always-on invariant checker
  • Tandem Collaborative text editor on a sequence CRDT: offline edits, any delivery order, always converges
  • Burrow Minimal Linux container runtime in Go: namespaces, pivot_root, cgroup v2 limits

← See all my work: apps, ML/AI and systems