Fair Scheduler Design

Open Simulator
Design · Fair Scheduler

Fair Scheduler Design

Back to Live

Fair Scheduler for LLM Token Throughput

TL;DR

  • DRR per client for fairness, plus aging to avoid starvation.
  • HTB + SWR for minute/hour/day provider limits.
  • Estimate + overdraft to handle unknown response tokens.
  • Low/High watermarks: loosen when quiet, tighten when busy.
  • Completion hook reconciles token counts and unblocks dependent jobs.

Background

  • Deficit Round Robin (DRR) comes from network packet scheduling. It approximates weighted fair queuing with O(1) per decision, handling variable-size items by giving each flow an accumulating deficit. If the head item fits the deficit, it is served; otherwise the flow waits until more quantum accrues.
  • Token Buckets & Sliding Windows are standard rate-limit constructs. A token bucket enforces an average rate with controlled bursting; Hierarchical Token Buckets (HTB) stack limits (e.g., minute under hour under day). A Sliding Window answers "how many tokens used in the last N seconds?" continuously to avoid top-of-minute spikes.

We reinterpret packets → jobs and bytes → tokens.


Video


Terminology

  • Token: unit of cost (request + response tokens).
  • Job: compute of one field. Carries req_tokens (known) and resp_tokens_est (estimated from model stats).
  • Queue/Flow: (client_id × provider_model) FIFO stream; can contain multiple streams like (entity_id, property) for per-row ordering.
  • Deficit: client's spendable token budget under DRR, increased by quantum Q each visit.
  • Quantum Q: tokens added to a client's deficit per DRR round. Tunable; may scale with utilization.
  • Utilization u(t): fraction of a limit currently used, e.g. u_minute = tokens_used_last_60s / minute_limit.
  • SWR (Sliding Window Reservoir): per-second bins over last 60s to compute tokens_used_last_60s.
  • HTB: three concurrent checks (minute/hour/day). Dispatch only if all have headroom for the estimated spend.
  • Overdraft: temporary negative balance when actual > estimate; repaid by throttling future dispatches.
  • Aging: increasing a job's effective priority by wait time to avoid starvation: eff_priority = base + age_factor * wait_seconds.

Dispatch decision

A job may be dispatched now iff all are true:

  1. Buckets OK: SWR_60s + est_total ≤ minute_limit and HourTB.can_spend(est_total) and DayTB.can_spend(est_total)
  2. Client budget OK: client.deficit ≥ est_total
  3. Stream order OK: if the job is in a stream with a sealed head, this job may only run if policy allows tail-run (see below).

Where est_total = req_tokens + min(cap, resp_tokens_est).


Skip-with-Seal & Aging

Problem: head job is large and can't fit (deficit or buckets). If we always block, smaller tail jobs starve; if we always let tails run, the head may never catch up because tail jobs keep draining the deficit.

Policy (deterministic and finite):

  1. Seal the head: mark the head job sealed with metadata head_needed = est_total(head) and start accruing a dedicated head_reserve.

  2. Split the quantum: on every visit while a head is sealed, split Q into:

    • Q_head = ρ · Q (e.g., ρ = 0.6) → added to head_reserve (non-spendable by other jobs), and
    • Q_free = (1 − ρ) · Q → added to normal deficit_free used for tail jobs.
  3. Tail cap: while there is a sealed head, allow at most one tail dispatch per visit and only if tail_est ≤ deficit_free and buckets OK. This prevents unlimited bleeding.

  4. Run the head as soon as possible: when head_reserve ≥ head_needed and buckets OK, the sealed head must run next for this client; consume from head_reserve.

  5. Aging boost: increase this client's effective quantum slowly over time while sealed, e.g. Q := Q · (1 + age_factor · wait_seconds_clamped), bounded by a max multiplier. This makes heavy heads converge faster under contention.

This combination guarantees the head will complete in a finite number of rounds even under continuous arrival of small tail jobs, while still letting some small work proceed to keep the system responsive.

Accounting note: maintain two balances per client while sealed:

  • head_reserve (only spendable by the sealed head), and
  • deficit_free (spendable by non-head jobs). When not sealed, treat deficit = deficit_free and head_reserve = 0.

Interaction with deficit:

  • Running the smaller job still deducts tokens from the deficit.
  • So the big sealed job might fall behind temporarily.

Aging kicks in:

  • Each tick, sealed jobs get a growing priority score or weight based on wait time - boost current Q.
  • Could also introduce a threshold: once the sealed job's priority passes a threshold, scheduler prefers it even if other smaller jobs are available.

Sliding Windows & HTB

  • SWR 60s: keep 60 per-second bins in ETS; rolling sum is used_60s. Dispatch if used_60s + est_total ≤ minute_limit.
  • Hour/Day TBs: token buckets with (rate, capacity) mirrored to ETS from durable storage. Both must allow est_total.
  • Why both? SWR gives precise minute semantics; TBs smooth longer horizons and prevent "legal per-minute" bursts from exhausting hour/day caps early.

Completion Hook - what goes where

When the executor finishes a job, it sends:

  1. To Ledger: write debit/credit/overdraft events for the actual tokens.

  2. To Per-Client Queues:

    • Inflight bookkeeping: mark job done; clear sealed/reset head_reserve if this was the head.
    • Stream unblocking: if the job had dependents (DAG), emit ready events for children; if a stream was sealed behind this job, unseal it.
    • Estimator update: send (req_tokens, resp_actual) to ModelStats for future estimates.

Parameters you can tune

  • Q (base quantum): 2,048–8,192 tokens. Larger → fewer rounds for big jobs, but coarser fairness.
  • ρ (reserve split while sealed): 0.5–0.8. Larger → head clears faster; smaller → more tails progress.
  • age_factor (quantum boost slope): small, e.g. 1e−4–5e−4 per second, clamped to ×2 max.
  • low_watermark, high_watermark: e.g., 0.35 and 0.85 to toggle burst vs. strict behavior.
  • overdraft_cap_pct of minute limit: 1–5% as a safety valve.

Why works?

DRR

  • Why DRR? Jobs (like packets) vary a lot in "size" (tokens). Simple round-robin is unfair if one client's jobs are huge; WFQ is ideal but heavy. DRR is the sweet spot: constant-time, size-aware, proven to converge to fair shares.
  • Mechanics: We keep a ring of active client queues. Visit client A → add Q tokens to A's deficit → if A's head job estimated size fits in the deficit and in the provider's token buckets, dispatch it and subtract from A's deficit; otherwise skip A and move on. Repeat.

SWR - exact "per minute" behavior

  • Why SWR? Providers say "300k tokens per minute." If we just reset a counter each minute, we'd cause burstiness at :00. SWR tracks the last 60s continuously, so our "per minute" is always accurate and smooth.
  • Mechanics: 60 tiny bins (one per second) with counts. When time advances, drop bins older than 60s, add the new second, and keep a rolling sum.

HTB

  • Why HTB? Providers enforce not just a minute cap but also hour/day caps. We must ensure all three limits hold simultaneously.
  • Mechanics: Before dispatch, we check: "If I spend est_tokens now, would I exceed the minute, hour, or day buckets?" Only if all three say "OK" do we allow it. Buckets refill over time.

Utilization, watermarks, and "burst vs. strict"

  • Why modes? When the platform is quiet, we want to let a single client go fast-it harms no one. When busy, we need strict fairness.

  • How: compute u_minute(t).

    • If u is low → burst mode: larger Q, maybe allow more than one job per visit if the bucket is healthy.
    • If u is high → strict mode: smaller Q, one-job-per-visit, enforce DRR tightly.

Estimation + Overdraft - dealing with unknown response tokens

  • Why estimate? We must decide to start a job without knowing how long the model's answer will be. We estimate response tokens from history (per model and prompt family).
  • Overdraft: If actual > estimate, we "spend" the difference post-hoc. If buckets have room, we debit immediately; else we briefly go negative (up to a small cap) and the scheduler repays that debt by throttling future dispatches. This keeps the pipe flowing without violating provider posture in the long run.

Architecture Diagrams


Gotchas, rabbit holes, perf considerations

Too many to list. Picture here remains fuzzy at the edges and would need to be made very explicit during implementation. To list a few:

  • Stream/DAG ordering gaps cause rows have inter-property dependencies: either introduce explicit DAG traversal (order) or/and handle in order per-stream FIFO under each client and unblock DAG children on completion hooks or maybe FSM?
  • Heavy-tailed outputs can balloon overdraft and violate limits under load: tighter thresholds while we accumulate real use data for improved estimates?
  • Thrashing around watermarks - flips burst/strict rapidly: throttle burst/strict switching by minimum period spent in one?
  • Unlucky sealed-head vs tail budget split ratio can create large jobs build up if many of those: some kind of periodic drain?
  • Persistence/restart spikes after crash: smooth start with conservative ramp up somehow?
  • Idempotency/retries/cancelation - can we have cancellations and retries cause they may double-spend: idempotency keys and explicit FSM?
  • Atomic reservations to avoid races that may lead to oversubscribtion: centralize and maybe reserve+commit?
  • Unmodeled RPM/concurrency caps: mentioned in the task but explicitly out of scope - will definitely complicate things.
  • Timekeeping/SWR and hour/day semantics - wall-clock jumps, issues near hour/day resets: no clue cause time is hard - maybe monotonic time?