Core Pattern · Interactive Simmedium•DECEMBER 2026•8 MIN
Lazy Token Bucket & Micro-Batch Queue: O(1) Quota Enforcement
Meter variable-cost requests in O(1) without background threads and group admitted work into bounded micro-batches.
token bucketmicro-batchingjittered backoffinfrarate-limitingasync
The problem
Enforce steady-state refill rate and burst limit capacity across variable-cost requests (such as LLM token budgets) in O(1) time per request without background ticker threads, and batch admitted requests up to max_batch.
Watch it run
Adjust Refill Rate and Burst Capacity to watch lazy refill clamp at capacity, reject requests when tokens < cost with a 429 retry estimate, and flush micro-batches at size 3.
LOADING TOKEN BUCKET & BATCH QUEUE SIM...
Reference implementation
def allow_request(
buckets: dict[str, tuple[float, float]],
tenant: str,
now: float,
cost: float,
rate: float,
cap: float,
) -> tuple[bool, float]:
tokens, last_ts = buckets.get(tenant, (cap, now))
elapsed = max(0.0, now - last_ts)
tokens = min(cap, tokens + elapsed * rate)
if tokens >= cost:
buckets[tenant] = (tokens - cost, now)
return True, 0.0
buckets[tenant] = (tokens, now)
return False, (cost - tokens) / rate