Quota-Aware LLM Pipeline Dispatch and Checkpoint Recovery
Hard · System Design · Software Engineer · Onsite
Prompt
A multi-worker DAG orchestration platform invokes third-party LLM endpoints to summarize long documents, generate vector embeddings, extract structured fields, and run multi-step inference. Single model invocations typically run for 10 to 60 seconds, span multi-part documents, and can fail late in a pipeline after most stages have already succeeded. Total workload demand is projected around 80B daily tokens (treat this figure as a demand-sizing input rather than guaranteed vendor capacity), bounded by upstream request-per-minute (RPM) and token-per-minute (TPM) limits.
Design a quota-aware dispatcher and checkpoint recovery architecture that absorbs waves of HTTP 429 throttling without triggering cluster-wide retry storms and avoids repeating expensive model calls when a long-document job fails near completion.
Operating constraints & assumptions: - Heterogeneous vendor capabilities: Quota boundaries (account, region, model, token direction), rate-limit headers, idempotency support, async job polling, request cancellation, and usage reporting vary across vendors; never assume features an endpoint does not provide. - Ambiguous network failures: A client timeout or broken connection after sending a payload does not tell you whether the vendor ran or billed that call. - Dependency-preserving decomposition: Long documents may be split into chunk sub-tasks, provided cross-chunk context dependencies and final output semantics are preserved.
Scope & Expectations
- Shared quota accounting & backpressure: Explain how workers coordinate distinct RPM and TPM pools (accounting for active in-flight reservations and optional bounded local leases), isolate tenants fairly, and translate HTTP 429 bursts into jittered delayed retries and upstream workflow admission control.
- Version-pinned chunk checkpoints: Show how completed intermediate outputs are addressed and persisted so late pipeline failures resume cleanly without serving stale outputs when prompts, models, or parameters change.
- Uncertain-call reconciliation & honest guarantees: Detail the write-ahead call lifecycle before and after network dispatch, how recovery adapts to each vendor's lookup/idempotency features, and the exact limits on avoiding duplicate generation and double billing.
Step-by-step walkthrough
Clarify requirements, assumptions, and provider capabilities
This system solves two tightly connected problems inside a DAG (Directed Acyclic Graph) workflow engine (a task runner where steps form a flowchart with no loops, and downstream steps wait for upstream steps to finish):
- Coordinated rate limiting and backpressure (Part 1): Many worker machines share the same external LLM accounts. Provider limits are enforced in RPM (Requests Per Minute) and TPM (Tokens Per Minute). When traffic spikes and a provider returns HTTP 429 (Too Many Requests), the cluster must smoothly slow down new admissions instead of unleashing a retry storm (hundreds of workers retrying together and failing over and over).
- Checkpointing and uncertain-call recovery (Part 2): Individual model calls take 10–60 seconds, and one long document may take dozens of calls. If a workflow fails near the end, we must reuse completed chunk work without repeating it—and if a network connection drops after a request was sent, we must handle the fact that we do not immediately know whether the provider ran and billed that call.
Functional requirements
- Dispatch summarization, embedding, extraction, and inference tasks from DAG nodes to multiple external LLM providers.
- Enforce provider quotas across both request counts (RPM) and token counts (TPM) at the exact quota scope (the unit at which a provider tracks limits, such as an account, region, model, or token type).
- Delay and bound retries on throttled or failed calls while pushing backpressure upstream to workflow admission.
- Share available capacity fairly across tenants so one noisy customer cannot starve others.
- Save versioned intermediate chunk outputs so late failures resume from the last completed step.
- Record every outbound provider call before sending it, and reconcile lost responses using whatever lookup or deduplication features that specific provider actually supports.
Non-functional requirements
- Strict global quota compliance: Combined traffic across all workers must stay within our granted quota for each scope.
- Bounded memory and queues: A surge of HTTP 429s must never cause unbounded thread blocking or unbounded queue growth.
- Deterministic reuse: Completed chunk work is reused if and only if the input bytes, model version, prompt version, parameters, chunking logic, and upstream inputs are identical.
- Complete cost attribution: Every reserved, actual, and uncertain token is tracked per tenant.
Answers assumed for key scoping questions
- How are quota boundaries modeled? Every provider enforces limits at different granularities. We configure a list of quota scopes per provider—for example per
(provider, account, region, model)and per token class (combined TPM, separate input TPM and output TPM, and whether the provider charges the requestedmax_output_tokensupfront at admission). Every outbound call maps to all scopes it consumes. - How do pre-dispatch token estimates reconcile with post-call actuals? Before dispatch, we count input tokens with the model's tokenizer (the tool that splits text into model tokens) or a conservative character-based upper bound, and we reserve
max_output_tokensfor the output. When the response arrives, we settle against the provider's reported actual usage. - How do we handle differing vendor idempotency and lookup features? Capabilities remain strictly provider-dependent. Each provider adapter declares its supported features in configuration—such as idempotency keys (unique client-generated tokens that tell a server to execute a repeated request at most once and return the original result), asynchronous job polling, cancellation, or billing-log lookup. We never assume capabilities a provider lacks.
- When is a cached chunk checkpoint valid to reuse? Only when the checkpoint matches the exact same tenant, input content hash, model ID and version, prompt template version, generation parameters, chunker version, and upstream chunk result hashes.
- Is the 80B daily token figure our granted quota? No—80B daily tokens represents demand for sizing our infrastructure. If granted provider quotas are smaller than demand, excess work waits in fair queues or triggers admission backpressure.
Back-of-the-envelope sizing
Let's translate 80B daily tokens (
86,400seconds or1,440minutes per day) into concrete request rates, concurrent connections, quota scopes, and checkpoint storage.1. Aggregate token demand (sizing input, not granted capacity) 80,000,000,000 tokens / 86,400 s = ~926,000 tokens/s (~55.6M tokens/min average) Peak demand (assume 2x average) = ~1.85M tokens/s (~111M tokens/min peak) 2. Workload split (assumed 40% embeddings, 60% generation) Embeddings: 32B tokens/day = ~22.2M tokens/min average (~44.4M/min peak) Batch 64 chunks x 500 tokens = 32,000 tokens/request 32B / 32,000 = 1.0M requests/day (~12 req/s, ~700 RPM avg) Generation: 48B tokens/day = ~33.3M tokens/min average (~66.7M/min peak) Typical chunk call: 6,000 in + 800 actual out (1,500 max_output_tokens cap) Billed tokens per call = 6,800 tokens (7,500 reserved while in flight) 48B / 6,800 = ~7.06M requests/day (~82 req/s, ~4,900 RPM avg, ~9,800 RPM peak) 3. In-flight concurrency via Little's Law (in_flight = arrival_rate x average_duration) Average generation latency = 30 s (range 10-60 s): Average in flight: 82 req/s x 30 s = ~2,500 concurrent requests (up to ~4,900 if avg hits 60 s) Peak in flight (2x): 164 req/s x 30 s = ~5,000 concurrent requests Tokens reserved in flight at average = 2,500 x 7,500 = ~18.8M tokens (~37.5M at peak) 4. Provider scopes needed (placeholder: 5M TPM and 5,000 RPM per (account, region, model) scope) If provider refunds unused max_output_tokens: 5,000,000 / 6,800 = ~735 RPM/scope (TPM binds well before 5,000 RPM!) Generation scopes needed = 33.3M / 5M -> ~7 scopes average, ~14 scopes peak If provider charges full max_output_tokens at admission (no refund): 5,000,000 / 7,500 = ~667 RPM/scope -> ~8 scopes average, ~15 scopes peak Embedding scopes needed (at 5M TPM) = 22.2M / 5M -> ~5 scopes average, ~9 scopes peak 5. Coordination & checkpoint storage Dispatch rate = ~94 req/s avg (~190 req/s peak) -> trivial for sharded RAM Generation checkpoints: 800 tokens (~3.2 KB) x 7.06M/day = ~23 GB/day (~0.7 TB for 30 days) Attempt write-ahead rows: ~300 B x ~8.1M/day = ~2.4 GB/day Embedding vectors: 64M chunks/day x 6 KB (1,536 float32) = ~384 GB/day (stored in destination index)What these numbers tell us about the architecture
- Tokens—not request counts—are the bottleneck for generation: At 6,800–7,500 tokens per call, a 5M TPM scope runs out of tokens at ~667–735 RPM, less than 15% of its 5,000 RPM limit. Quota accounting must track tokens first.
- In-flight calls hold massive token float: Roughly 19M–37.5M tokens sit inside open 10–60 second connections at any instant—equivalent to 4 to 7 full scopes of per-minute budget! Counting tokens only after calls finish would overshoot quotas every single minute.
- Workers must never sleep on retries: With ~5,000 slow HTTP streams open at peak, holding worker slots during backoff delays would exhaust memory and sockets. Retries belong in a durable delay queue on disk/database, not in sleeping threads.
- Checkpointing is vastly cheaper than recomputing: Storing a day's text checkpoints (~23 GB) costs pennies in object storage, whereas re-running a failed 200,000-token document costs ~317,500 LLM tokens and minutes of scarce quota.
API and internal service contracts
1. External workflow API
POST /v1/workflow-runs Body: { tenant_id, workflow_id, inputs, priority: "interactive" | "batch", token_budget? } -> 202 Accepted { run_id, admission: "ADMITTED" | "QUEUED", estimated_start_at } -> 429 Too Many Requests { retry_after_s } (returned when tenant's queued backlog exceeds its cap) GET /v1/workflow-runs/{run_id} -> 200 { state, pinned_versions, nodes: [{ node_id, state, attempts }], tokens: { reserved, actual, uncertain } } POST /v1/workflow-runs/{run_id}/cancel POST /v1/workflow-runs/{run_id}/revise Body: { updated_versions } -> creates a new run that automatically reuses unchanged chunk checkpoints2. Internal task-to-dispatcher interface
submit_model_op(spec) -> op_id spec = { tenant_id, run_id, node_id, result_key, op_kind: "summarize" | "embed" | "extract" | "infer", model, model_version, prompt_template_id, prompt_version, params_hash, input_refs: [blob_paths], est_input_tokens, max_output_tokens, allowed_scopes: [scope_ids serving this exact model_version], priority, deadline_at }3. Internal quota service interface (sharded by scope group)
lease(scope_ids, dispatcher_id, want: { requests, input_tokens, output_tokens }) -> { lease_id, granted: {...}, expires_at } (short ~2 s local allowance) -> { granted: 0, paused_until } (scope is cooling down after HTTP 429) return_unused(lease_id, unused: {...}) (returns unspent lease allowance before expiry) acquire_permit(scope_id, attempt_id) -> { permit_id, ttl_s: 120 } | NONE heartbeat_permit(permit_id) / release_permit(permit_id) report(attempt_id, scope_id, outcome: "OK" | "THROTTLED" | "ERROR", rate_headers: { retry_after_s?, remaining_tokens?, reset_at? }, usage: { input_tokens, output_tokens } | "UNKNOWN") backlog(scope_id) -> { queued_tokens, effective_tpm, backlog_minutes, level: "GREEN" | "YELLOW" | "RED" }Passing
attempt_idintoreport(...)makes token settlement idempotent (safe to retry without double-counting): if a network hiccup causes a dispatcher to report completion twice, the quota service ignores the second report instead of refunding unused output tokens twice.Data model for quotas, manifests, and write-ahead attempts
scopes -- Configuration and live rate-limit state per quota scope scope_id PK -- e.g. "provA/acct-2/us-east/model-L/tpm" provider, account, region, model limit_kind -- 'RPM' | 'TPM' | 'TPM_IN' | 'TPM_OUT' | 'CONCURRENCY' configured_limit -- Our cluster's allocated share of the account quota effective_limit -- Live rate dynamically adjusted downward on 429s counts_max_output_upfront -- true if provider does not refund unused max_output_tokens paused_until -- Timestamp until which dispatches are halted provider_capabilities -- Explicit feature flags per provider (never assumed) provider PK, supports_idempotency_key (bool), idempotency_window_s, supports_async_job_lookup (bool), supports_client_id_lookup (bool), supports_cancel (bool), usage_reporting ('per_request' | 'aggregate' | 'none') run_manifests -- Freezes exact versions when a workflow run starts run_id PK, tenant_id, workflow_version, chunker_version, node_versions_json -- { node_type -> (model, model_version, prompt_id, prompt_ver, params_hash) } ops -- One row per DAG node in a workflow run (run_id, node_id) PK, tenant_id, result_key, state -- 'WAITING'|'READY'|'QUEUED'|'DELAYED'|'DISPATCHED'|'UNKNOWN'|'SUCCEEDED'|'FAILED' not_before, throttle_attempts, error_attempts, enqueued_at, last_error attempts -- Write-ahead log record written BEFORE every network call attempt_id PK, result_key, run_id, node_id, attempt_no, scope_id, permit_id, idempotency_key, provider_request_id, provider_job_id, state -- 'INTENT'|'SENT'|'RESPONDED'|'THROTTLED'|'FAILED_DEFINITE'|'UNKNOWN' -- |'RECONCILED_FOUND'|'RECONCILED_NOT_FOUND'|'RECONCILED_UNRESOLVABLE' est_input_tokens, max_output_tokens, actual_input_tokens, actual_output_tokens, intent_at, sent_at, finished_at op_results -- Content-addressed, write-once checkpoint table result_key PK -- SHA-256 hash of tenant + versions + input hashes + upstream keys tenant_id, output_blob_path, output_sha256, actual_usage_json, provider, provider_request_id, committed_at, expires_at token_ledger -- Per-tenant cost accounting per minute (tenant_id, scope_id, minute_bucket) PK, reserved_tokens, actual_tokens, uncertain_tokensWhy three separate tables (
ops,attempts,op_results) matter:attemptsis a write-ahead log (WAL)—a durable record written to the database before sending bytes over the network (state = 'INTENT'). If a worker crashes mid-call, the database still knows an external request may be running.op_resultsis decoupled fromops: Checkpoints are keyed byresult_keyrather thanrun_id, so a retried or revised workflow run immediately finds and reuses valid work.configured_limitrepresents our cluster's share, not necessarily 100% of the provider account, because another internal service may share the same billing account.
High-level architecture
Clients | POST /v1/workflow-runs v +--------------------+ backlog level (GREEN / YELLOW / RED) +-----------------------------+ | Run Admission API |<-------------------------------------------| | +---------+----------+ | | v | Quota Service | +--------------------------------------------+ | - Token buckets per scope | | DAG Scheduler (Sharded Postgres) | | - Short 2s worker leases | | 1. result_key in op_results? -> skip node | | - Concurrency permits | | 2. Release READY nodes (<= 5 min/tenant) | | - AIMD effective_limit | +---------+----------------------------------+ | - paused_until & backlog | v +--------------+--------------+ +--------------------------------------------+ due retries ^ | Per-Tenant Fair Queues (per scope group) |<-----------------+ | leases, +---------+----------------------------------+ | | permits, v | | usage reports +--------------------------------------------+ | | | Stateless Dispatchers (Async HTTP workers) |------------------+----------------+ | - Deficit Round Robin across tenants | | | - Write attempt INTENT -> call provider | | +---------+----------------------------------+ | v +----------+---------------+ +--------------------------------------------+ | Durable Delay Queue | | Provider Adapters (capability-driven) | | (ordered by not_before) | +---------+----------------------------------+ +----------^---------------+ v | HTTP 429 / 503 External LLM Providers ---------------------------------------+ | v HTTP 200 responses +--------------------------------------------+ +------------------------------+ | Blob Store + op_results (write-once) | | Background Reconciler | | -> marks node SUCCEEDED, wakes children | | - Resolves UNKNOWN attempts | +--------------------------------------------+ | - Reclaims expired permits | +------------------------------+Life of a single chunk task on the happy path:
- The DAG scheduler computes the node's
result_key, checksop_results, sees a cache miss, and places the node into its tenant's queue. - A stateless dispatcher picks the node in fair tenant order, draws
est_input_tokens + max_output_tokensfrom its local quota lease plus 1 concurrency permit, and writes anattemptsrow in stateINTENT. - The provider adapter sends the HTTP request (attaching an
idempotency_keyif supported) and updates the attempt toSENT. - When the response arrives, the dispatcher writes the output to object storage at
results/<result_key>/<attempt_id>, commitsop_resultswrite-once, releases the permit, callsreport(...)with actual token usage, and marks the DAG nodeSUCCEEDEDso downstream nodes becomeREADY.
- The DAG scheduler computes the node's
Deep dive 1: Shared quota scopes, in-flight reservations, and short leases
Provider rate limits apply to a shared scope, never to an isolated worker process. If 40 stateless dispatchers each assumed they could send 5M TPM, they would collectively blast 200M TPM at the provider and fail 97.5% of calls with HTTP 429. Conversely, dividing quota statically (
5M / 40 = 125k TPMper worker) wastes quota whenever traffic lands unevenly across workers and breaks whenever autoscaling adds or removes instances.1. Multi-scope atomic reservation
A single generation request to
model-Linacct-2 / us-eastcan simultaneously consume multiple provider limits:Scope ID Kind Debit on Dispatch ---------------------------------------- ------------ --------------------------------- provA/acct-2/us-east/model-L/rpm RPM 1 request provA/acct-2/us-east/model-L/tpm_in TPM_IN 6,000 tokens (estimated input) provA/acct-2/us-east/model-L/tpm_out TPM_OUT 1,500 tokens (max_output_tokens) provA/acct-2/us-east/account_tpm TPM 7,500 tokens (if account-wide cap exists) provA/acct-2/us-east/model-L/concurrency CONCURRENCY 1 in-flight permitAll scopes for one
(provider, account, region)live on the same Quota Service shard so a single atomic script checks and deducts all of them together—either all succeed, or none are deducted.2. Token buckets with capped burst size
Each scope uses a token bucket—a counter that refills smoothly at
effective_limit / 60tokens per second up to a maximum cap. Crucially, we cap the bucket capacity at 10 seconds of budget (for example833ktokens on a 5M TPM scope), not a full 60 seconds. Many providers advertise a per-minute limit (5M TPM) while internally enforcing micro-burst windows every 1–10 seconds; capping burst accumulation prevents an idle cluster from dumping a full minute of traffic in one second.3. Bounded local allowances (leases)
To keep the Quota Service off the per-request critical path and survive brief network blips:
- Each dispatcher requests a lease worth ~2 seconds of its active send rate (bounded by a per-dispatcher ceiling). The Quota Service deducts those tokens from the central bucket immediately and sets a 5-second
expires_at. - Dispatchers spend from their local lease in memory for individual requests. Before the 5 seconds expire, the dispatcher returns any unused lease balance via
return_unused(lease_id). - If a dispatcher crashes and never reports back, an expired lease is assumed spent rather than refunded, because the crashed worker may have already sent requests using those tokens. At most 2 seconds of one worker's slice is lost on a crash, and global traffic never exceeds the scope limit.
4. Reserve upfront, settle idempotently on completion
Because ~2,500 calls sit in flight for 30 seconds holding ~19M tokens, tokens are deducted before dispatch, using
est_input_tokens + max_output_tokens. When the response returns:- The tenant's
token_ledgerupdates from reserved to actual (actual_input_tokens + actual_output_tokens). - If
counts_max_output_upfrontisfalse,report(attempt_id, ...)refundsmax_output_tokens - actual_output_tokensback to the central bucket (capped at the 10-second burst ceiling so delayed refunds cannot overfill the bucket). Ifcounts_max_output_upfrontistrue, nothing is refunded to the quota bucket because the provider never refunds that admission charge. - Whenever responses carry provider rate-limit headers (
x-ratelimit-remaining-tokens), the Quota Service setsbucket = min(bucket, provider_remaining), automatically detecting quota consumed by other internal teams sharing the same account and correcting any tokenizer estimation drift.
5. Concurrency permits for slow-provider protection
Per Little's law,
735 req/min (~12.25 req/s) x 30 s = ~368concurrent requests per 5M TPM scope. Giving the scope 600 concurrency permits allows full throughput up to ~49 seconds average latency (600 / 12.25). If the provider degrades to 90-second responses, permits run out and naturally throttle our dispatch rate before sockets pile up. Each permit has a 120-second lease renewed by heartbeats so crashed workers' permits automatically recover.- Each dispatcher requests a lease worth ~2 seconds of its active send rate (bounded by a per-dispatcher ceiling). The Quota Service deducts those tokens from the central bucket immediately and sets a 5-second
Deep dive 2: Turning HTTP 429 surges into smooth backpressure
When a quota runs dry, the classic failure mode is a synchronized retry storm: 50 workers receive HTTP 429 in the same second, sleep for a fixed 5 seconds, wake up together at
t + 5s, slam the provider simultaneously, fail again, and block worker threads while the DAG scheduler keeps pouring new nodes into the queue. We break every link of that chain by treating HTTP 429 as a scope-level congestion signal, not an isolated task error.1. Classify every call outcome accurately
Outcome Meaning System Action ---------------------------------------- --------------------------------- ------------------------------------- HTTP 429 (with or without Retry-After) Quota scope exhausted Scope cooldown + AIMD + delay queue HTTP 500 / 503 / provider "overloaded" Provider server trouble Per-scope circuit breaker + backoff HTTP 400 (bad input / context length) Permanent error for this request Fail node immediately (no retry) Connection refused BEFORE bytes sent Request never left our network Safe retry (no duplicate billing risk) HTTP 502 / 504 from proxy, TCP reset, Uncertain! Provider may still Mark attempt UNKNOWN -> Reconciler or client timeout AFTER bytes sent execute and bill this call (never blind-retry immediately!)2. Adapt the scope rate with AIMD and freeze refills during cooldown
When any dispatcher reports
THROTTLEDto the Quota Service:- Honor
Retry-Afterglobally: If the header specifiesRetry-After: 25, the Quota Service setspaused_until = now + 25son that scope, revokes active leases, and freezes token-bucket refill untilpaused_untilpasses (resuming with only 1 second of tokens in the bucket so dispatchers ramp smoothly instead of firing a 10-second burst the instant the pause ends). - AIMD (Additive Increase, Multiplicative Decrease)—the same feedback loop TCP uses to find safe network bandwidth: cut
effective_limit = max(floor_limit, effective_limit * 0.7)at most once per 10-second window (so 40 already-in-flight calls returning 429 together trigger one 30% cut, not0.7^40). After every 30 seconds with zero 429s, stepeffective_limitback up by+5%ofconfigured_limituntil it reachesconfigured_limit.
3. Delay retries in durable storage with full jitter
The dispatcher immediately releases its concurrency permit and moves the op into the durable
DELAYEDstate with:not_before = now + retry_after_s + random_uniform(0, min(120s, 2s * 2^throttle_attempts))Notice two critical details: - Full jitter (choosing a random delay across the entire
[0, cap]range) spreads wake-up times evenly instead of clumping retries into waves. - We ADD jitter toretry_after_s, nevermax(retry_after_s, jitter): if 200 requests all receiveRetry-After: 30in the same second,max(30, jitter)would still wake most of them att + 30.0s! Adding jitter spreads them across[30s, 30s + backoff]. - After 10 throttle attempts or passingdeadline_at, the node fails cleanly withQUOTA_UNAVAILABLE.4. Re-admit through the token bucket and push pressure upstream
When
now >= not_before, a delayed op is merely marked eligible in its tenant's queue—it must still acquire tokens from the bucket to be dispatched. Even if 5,000 delayed ops become due in the same second, they trickle out strictly ateffective_limit. Meanwhile, the Quota Service computesbacklog_minutes = queued_tokens / effective_tpmand drives upstream admission:Level Backlog Upstream Admission & Scheduler Behavior ------ -------------------- -------------------------------------------------------------------- GREEN < 1 minute Admit interactive and batch workflow runs normally YELLOW 1 to 10 minutes Pause new batch run admissions (`202 QUEUED`); interactive continues RED > 10 min or paused Queue or return `429 Retry-After` to new runs; finish running DAGsFinishing already-started workflows before admitting brand-new ones protects sunk token spend, and capping each tenant's in-queue
READYnodes to ~5 minutes of fair share keeps memory and queue depth bounded. If another region/account serves the exact samemodel_version(allowed_scopes), work may spill over there—provided data-residency rules and any healthcare compliance contract (such as a HIPAA Business Associate Agreement for patient documents) cover that region.- Honor
Deep dive 3: Tenant fairness with token-weighted Deficit Round Robin
On a shared generation scope, one task might be a 1,000-token extraction while another is a 9,300-token reduce summary. Request-count round robin is unfair when request sizes vary by 10x, and a single FIFO queue lets one tenant submitting 10,000 batch documents block every other customer for quarter of an hour.
We schedule per
(scope_group, tenant_id)using Deficit Round Robin (DRR)—a fair-queuing algorithm that grants each active tenant a token credit (weight * quantum, say50,000tokens per round) and dispatches tasks from that tenant's queue until the next task costs more tokens than its remaining credit, saving leftover credit for the next round.Concrete trace on a 5M TPM scope (equal weights, quantum = 50,000 tokens/round): Tenant A dumps 10,000 batch chunks = 68,000,000 tokens Tenant B submits 200 interactive ops = 1,360,000 tokens Naive single FIFO queue: Tenant B sits behind A's 68M tokens -> waits 68M / 5M = ~13.6 minutes! Token-weighted Deficit Round Robin: Both tenants active -> each receives ~2.5M TPM. Tenant B finishes all 1.36M tokens in ~33 seconds! Once B's queue empties, Tenant A automatically gets the full 5M TPM (work-conserving).Three fairness rules close the remaining loopholes:
- Retries spend their own tenant's credit: When Tenant A hits HTTP 429 on 5,000 calls, those delayed ops return to Tenant A's queue and must pay from Tenant A's DRR deficit upon re-dispatch. Tenant A cannot capture extra share of newly recovered capacity by generating more retries.
- Preserve original enqueue order inside each tenant: Within Tenant A's queue, ops sort by
(priority, original_enqueued_at)so a retried chunk finishes its almost-done document before brand-new chunks start. - Per-tenant share caps and uncertain-token budgets: While other tenants are waiting, a single high-tier tenant is capped (for example at 50% of a scope), and
uncertain_tokenscount against the tenant's daily spend limit until reconciled so runaway timeouts cannot bypass billing caps.
Deep dive 4: Version-bound checkpoints and reconciling uncertain calls
1. Decompose long documents while respecting semantic dependencies
A 200,000-token document is broken into a deterministic map-reduce DAG (50 chunks of 4,000 tokens):
Deterministic Chunker (v2) --> Map stage: 50 calls x (4,500 in + 800 out) = 265,000 tokens [independent if stateless] --> Reduce level 1: 5 calls x (8,500 in + 800 out) = 46,500 tokens [each merges 10 map outputs] --> Final reduce: 1 call x (4,500 in + 1,500 out) = 6,000 tokens [merges 5 level-1 outputs] Total = 56 calls, 317,500 tokens. If call #56 fails: without checkpoints we re-spend 317,500 tokens; with checkpoints we re-spend 6,000 (~1.9%).If chunk
isemantically depends on earlier context (for example, page 2 defines which medication "the trial drug" refers to on page 40), we model that dependency explicitly in the DAG—either via overlapping chunk windows plus entity carries, or a sequential chain where nodeitakes nodei - 1's extracted glossary as an upstream input. Dependent nodes are never forced in parallel if doing so alters meaning. Partial streamed text from a broken connection is discarded, never checkpointed as complete.2. Hash-chained, version-bound
result_keyand write-once commitresult_key = sha256( tenant_id, op_kind, provider_model_id, model_version, prompt_template_id, prompt_version, params_hash, chunker_version, transform_version, input_content_hashes[], upstream_result_keys[] <-- forms a cryptographic Merkle/hash chain across the DAG! )Because
upstream_result_keysare hashed into downstream keys, changing a map prompt automatically changes every downstream reduceresult_key, making stale mixes impossible. Includingtenant_idprevents cross-tenant cache leaks.To commit without race conditions when a late duplicate finishes: 1. Write output bytes to
results/<result_key>/<attempt_id>(includingattempt_idguarantees a late second attempt cannot overwrite the bytes of an already-committed first attempt!). 2. ExecuteINSERT INTO op_results (result_key, output_blob_path, ...) VALUES (...) ON CONFLICT (result_key) DO NOTHING. 3. Whichever attempt inserts the row wins permanently; downstream nodes read only that committed blob, keeping the DAG 100% deterministic even when modeltemperature > 0.3. Write-ahead state machine and provider-dependent reconciliation
When the final reduce call times out after bytes were sent, the attempt moves from
SENTtoUNKNOWN(and a background sweeper also moves staleINTENT/SENTrows from crashed dispatchers toUNKNOWNonce client timeout + grace passes):INTENT --(send HTTP)--> SENT --(200 OK)--------------> RESPONDED --> commit op_results --> SUCCEEDED |----(429)-----------------> THROTTLED --> durable delay queue |----(timeout / 502 / crash) v UNKNOWN --> Reconciler checks provider_capabilities:Provider Capability Reconciler Action Strongest Honest Guarantee --------------------------------- ---------------------------------------- ----------------------------------------- Idempotency key (window W) Retry with same key derived from At most 1 execution & charge within W (result_key, reissue_seq) within W (bump reissue_seq if provider caches 429s) Async job API (job_id saved) Poll GET /jobs/{job_id}; fetch output 1 execution per accepted job_id Client-ID request lookup Query by client_id; resend ONLY after No duplicate if lookup waited past max max provider queue+run time confirms miss execution window before declaring miss Usage/billing logs only Cannot fetch lost text; reconcile cost Exact billing attribution; retry re-runs None of the above Bounded resend (e.g. max 1 extra try) Exactly 1 committed DAG result locally; at-least-once execution/billing externallyScaling, failure modes, and architecture summary
Scaling & bottleneck profile
- Quota Service: Sharded in-memory state (such as Redis/Dragonfly with synchronous replication) partitioned by scope group. Because dispatchers lease ~2 seconds of budget at a time, 20 dispatchers generate <50 RPCs/second total regardless of token throughput.
- Stateless Dispatchers: Async event-loop workers (Python
asyncio/ Go / Rust). 5,000 open streaming/long-poll connections at peak easily fit across ~20 small instances (~250 active streams each). - DAG Scheduler & Postgres: Sharded by
tenant_id. ~8.1M ops/day x ~4 state transitions = ~32.4M writes/day (~375 writes/s average), well within 2–4 database shards. - True bottleneck: Granted provider TPM (~14–15 scopes of 5M TPM needed at peak). Shortfalls surface immediately as
backlog_minutes, guiding operators to request quota increases, shift batch runs off-peak, or route extraction to smaller models.
Failure handling summary
Failure Scenario System Response ------------------------------------- ------------------------------------------------------------------- Quota Service shard unreachable Dispatchers spend remaining lease, then fall back to a conservative static rate (50% * configured_limit / live_dispatcher_count) and pause locally on any 429 until the shard recovers. Dispatcher crashes mid-request 120s concurrency permit expires; unspent 2s lease counts as spent; stale INTENT/SENT attempt transitions to UNKNOWN for reconciliation. Object-store write fails post-200 OK Dispatcher retries blob write locally; if process dies, attempt hits UNKNOWN and reconciles via idempotency/job-lookup or bounded rerun. Provider region outage (5xx spike) Per-scope circuit breaker opens; traffic shifts to allowed_scopes in healthy regions or pauses new admissions via RED backlog signal. Model version deprecated mid-run Run fails cleanly or operator triggers `/revise` with new model_version (reusing unaffected upstream stages; never silently swapping models).
Intuition & how it works
Think of this system like coordinating highway ramp meters into a toll tunnel while saving progress at every milepost on a cross-country road trip. Multiple worker servers feed requests into external LLM providers that strictly cap both RPM (Requests Per Minute) and TPM (Tokens Per Minute) per quota scope (the unit at which a provider enforces limits, such as one account + region + model). Instead of letting every worker guess the tunnel's capacity on its own, a central Quota Service hands out short 2-second leases (small pre-approved slices of token budget) and tracks in-flight reservations so slow 10–60 second calls cannot silently exhaust the minute's quota. Meanwhile, long documents are split into a DAG (Directed Acyclic Graph)—a pipeline of chunk steps and merge steps with no loops—where every finished chunk writes a content-addressed checkpoint (a saved output named by a cryptographic hash of its exact input text, model version, prompt version, and upstream hashes) and logs a write-ahead intent record (a database row saved before sending bytes over the network) so lost responses can be reconciled cleanly.
Why do the obvious approaches fail? Giving all N workers the account's full quota multiplies traffic by N and triggers an immediate wall of HTTP 429 (Too Many Requests) errors, while splitting quota statically (quota / N) wastes capacity whenever load is uneven. Worse, if workers handle HTTP 429 by sleeping in a loop and retrying after a fixed delay, threads stay blocked and wake up together in a synchronized retry storm that hammers the still-empty quota. Finally, running a 200,000-token document without versioned checkpoints wastes 98% of paid work when the final step fails, and blindly retrying a timed-out call doubles your bill whenever the provider actually processed the first call behind a dropped connection.
Let's trace a tiny concrete example—a 3-chunk document (c1, c2, c3) plus 1 reduce step running on a scope with a 20,000 TPM budget, where each call reserves 5,000 tokens (4,000 input + 1,000 max output) and actually uses 4,500 tokens:
1. Dispatch & in-flight reservation (t = 0s):
c1, c2, c3 each reserve 5,000 tokens -> 15,000 reserved; 5,000 remains in bucket.
c1 and c2 return 200 OK (4,500 actual tokens each) -> commit op_results[key_c1], op_results[key_c2];
500 unused output tokens per call are refunded (when provider rules count actual output).
2. HTTP 429 surge from shared account usage (t = 12s):
c3 receives HTTP 429 (Retry-After: 10s) because another service shared the account!
- Quota Service pauses the scope for 10s, freezes bucket refill, and cuts effective_limit by 30% (14,000 TPM).
- c3 releases its concurrency permit and enters the durable delay queue for 10s + random jitter (e.g. 14.3s),
freeing the worker immediately instead of sleeping in a thread.
- At t = 26.3s, c3 wakes up, acquires 5,000 tokens from the refilled bucket, succeeds, and commits op_results[key_c3].
3. Late network timeout & recovery on the final reduce call (t = 55s):
- Dispatcher writes attempt a_99 = INTENT -> sends request with idempotency_key(key_reduce) -> SENT.
- Connection drops at t = 95s! Attempt a_99 becomes UNKNOWN; c1, c2, c3 stay safely committed in op_results.
- Reconciler checks provider_capabilities:
* Supports idempotency keys -> replays with the exact same idempotency_key; fetches result with 0 extra charge!
* Supports nothing -> re-runs ONLY `reduce` (4,500 tokens), saving all 13,500 tokens already spent on c1..c3.
Key trade-offs
- Central quota bucket with short leases vs. per-worker static limits: A central token bucket per scope guarantees the cluster's combined rate never exceeds the provider limit and adapts automatically when workers autoscale. Handing out ~2-second local leases keeps the Quota Service off the per-request hot path, trading a tiny amount of temporarily stranded budget (at most 2 seconds of one worker's slice on a crash, expiring after 5 seconds) for low latency and fault tolerance.
- Reserving
max_output_tokensupfront vs. charging only after completion: Deductingest_input_tokens + max_output_tokensbefore dispatch prevents 2,500 slow in-flight requests from overshooting TPM limits—and matches providers that billmax_output_tokensat admission. The trade-off is temporary under-utilization when actual outputs are much shorter thanmax_output_tokens, which we minimize by setting tight per-taskmax_output_tokenscaps rather than one huge default. - Scope-wide AIMD rate reduction vs. isolated per-request retries: Using AIMD (Additive Increase, Multiplicative Decrease)—cutting a scope's
effective_limitby 30% on a 429 window and ramping back up by +5% every 30 clean seconds—stops synchronized retry storms immediately, at the cost of briefly running slightly below peak capacity after a transient throttle burst. - Finishing running DAGs vs. admitting new workflows under backpressure: When queue backlog crosses 1–10 minutes (
YELLOW/RED), the admission layer holds or rejects new runs so half-finished documents can complete. New callers experience explicit queuing early, in exchange for keeping queue memory bounded and never wasting tokens already spent on in-progress workflows. - Token-weighted Deficit Round Robin (DRR) vs. single FIFO queue: DRR (giving each waiting tenant an equal or tier-weighted allowance of tokens per round) prevents a tenant with 10,000 queued chunks—or 10,000 throttled retries—from starving a tenant with 10 interactive tasks, trading slightly more per-tenant queue bookkeeping and a few extra rounds of wait for oversized requests.
- Chunk-level DAGs vs. whole-document calls: Decomposing a 200,000-token document into 4,000-token chunks bounds the blast radius of a failed or uncertain call to ~2% of total tokens, at the cost of extra reduce steps and explicitly modeling cross-chunk semantic dependencies (such as entity definitions from earlier pages).
- Tenant-scoped checkpoint keys vs. global deduplication: Including
tenant_idinsideresult_keygives up cross-tenant cache hits on identical public text, in exchange for eliminating cross-tenant data leakage and cache-timing side channels.
Common mistakes
- Handing each worker process the entire account ceiling (or a rigid
quota / Nslice): Either multiplies traffic by worker count into a 429 storm, or strands capacity whenever traffic is uneven or workers autoscale. - Counting only RPM or charging tokens only on completion: Generation scopes almost always hit TPM long before RPM, and ignoring ~19M–37.5M tokens held by slow 10–60 second in-flight calls overshoots every minute.
- Sleeping inside worker retry loops without jitter—or writing
max(retry_after, jitter): Blocking workers exhausts sockets, andmax(30s, random(0, 10s))wakes almost every throttled worker att = 30.0ssimultaneously instead of adding jitter on top ofretry_after. - Letting due retries bypass the token bucket or jump to the front of a global queue: Wake-up timers must only make a task eligible; the token bucket must still pace dispatches, and retries must pay from their own tenant's fair share.
- Refilling the token bucket at full speed while
paused_untilis active, or non-idempotent usage refunds: Both mistakes overfill the quota bucket and trigger another immediate 429 burst. - Treating post-send timeouts or gateway HTTP 502/504 errors as "definitely did not run": Once bytes leave our socket, the provider may execute and charge the request; immediate blind retries silently multiply token bills.
- Writing retries of the same chunk to the same object-storage path (
results/<result_key>): A slow duplicate attempt finishing second overwrites the already-committed blob and breaks its stored checksum; always includeattempt_idin the blob path and commit via write-once database insertion. - Caching checkpoints by input text alone: Omitting
model_version,prompt_version,params_hash, orupstream_result_keyscauses prompt fixes or model upgrades to silently serve stale or mixed-version outputs.
Follow-up questions
- How should the workflow engine handle a model or prompt template upgrade while a multi-chunk document run is already partially complete? Every workflow run pins its exact model, prompt, chunker, and parameter versions in
run_manifestsat start, and every chunk'sresult_keyhashes both its own versions and itsupstream_result_keys. Runs already in flight normally finish consistently under their pinned manifest so a single reduce summary never mixes two prompt versions, while new runs use the new versions automatically. If an urgent bug fix or model retirement requires updating an in-progress run, the/reviseendpoint creates a new run whose hash chain automatically reuses any upstream stages whose versions and inputs are unchanged (for example, keeping 50 completed map outputs if only the final reduce prompt changed) and recomputes only modified stages plus their downstream dependents, displaying the estimated token cost first. - When rate-limit capacity recovers after a throttle wave, how do you stop a single tenant's backlog of retries from starving everyone else? Throttled operations return to their own tenant's queue, never a global high-priority retry lane, and when their
not_beforetimer expires they must still spend from that tenant's token allowance in Deficit Round Robin. As a result, a tenant with 10,000 throttled operations receives the exact same proportional share of newly refilled bucket tokens as a tenant with 10 operations, while full jitter spreads wake-up times and a per-tenant share ceiling (such as 50% while other tenants wait) plus a backlog cap prevent queue monopolization. Inside that tenant's own queue, operations remain ordered by originalenqueued_atso older half-finished documents finish before newer submissions. - If an upstream model vendor supports neither idempotency keys nor request status queries, what is the strongest execution and billing guarantee you can provide? Internally within our workflow engine, we still guarantee exactly one committed output per
result_keyvia write-onceop_resultsinsertion, so downstream DAG nodes never see conflicting versions even if two attempts complete. Externally at the provider, neither "exactly-once execution" nor "zero duplicate billing" is mathematically possible, because after a dropped response no client protocol can distinguish a lost request from a lost reply—choosing to resend gives at-least-once execution (possible double charge), whereas refusing to resend gives at-most-once execution (failed workflow). We minimize and bound that risk by setting generous client timeouts above p99 provider latency (e.g., 120 seconds for 60-second tasks), keeping calls chunk-sized (~6,000 tokens instead of 200,000), capping resends afterUNKNOWN(e.g., at most 1 retry), and recording uncertain reservations explicitly in the tenant'stoken_ledger.
Follow-up questions
- How should the workflow engine handle a model or prompt template upgrade while a multi-chunk document run is already partially complete?
- When rate-limit capacity recovers after a throttle wave, how do you stop a single tenant's backlog of retries from starving everyone else?
- If an upstream model vendor supports neither idempotency keys nor request status queries, what is the strongest execution and billing guarantee you can provide?
Similar questions
- Million-Service Internal Notification Platform
- Multi-Tenant and Session Isolation for Tool-Using RAG Agents
- High-Scale RAG Ingestion and Low-Latency Serving for 200-File Sessions
- Lifecycle Design for 24-Hour RAG Erasure, 7-Day Chats, and Audits
- Crash Recovery for DAG Workflows with Side Effects and Multi-Day Waits
- Architecting Multi-Tenant Workflows Across Fast I/O and Slow LLM Tasks
More Qualified Health interview questions
- Multi-Tenant and Session Isolation for Tool-Using RAG Agents Hard
- High-Scale RAG Ingestion and Low-Latency Serving for 200-File Sessions Hard
- Lifecycle Design for 24-Hour RAG Erasure, 7-Day Chats, and Audits Hard Pro
- Crash Recovery for DAG Workflows with Side Effects and Multi-Day Waits Hard Pro
- Architecting Multi-Tenant Workflows Across Fast I/O and Slow LLM Tasks Hard Pro
- Decoupling Live LLM Token Streams from Validated DAG Commits Hard Pro
- Safe Cancellation and Crash Recovery for Streaming Tool-Using Agents Hard Pro
- Cycle Validation and Durable Runtime Bounds for Editable Workflow DAGs Hard Pro
- Million-Service Internal Notification Platform Medium Pro