Production-Grade Agent Scheduler: Fair Multi-Tenant Scheduling & Fault Recovery
This article details a production-grade Agent Scheduler design covering multi-tenant fairness via Weighted DRF, reliable dispatch using Outbox pattern and fencing tokens, fault takeover with attempt epochs, tool gateway for side-effect safety, and phased rollout from single-cell to multi-cell deployments.
Reading font

1. Why Agents Need a Dedicated Scheduler
Traditional web services are short-lived, stateless, and homogeneous. Agent workloads differ in five key ways:
Execution duration varies widely : from 500 ms to tens of minutes involving planning, multiple model calls, browser interaction, and code execution.
Resources are multi-dimensional and heterogeneous : tasks need CPU, memory, sandbox slots, specific GPUs, regions, browsers, internal data sources, or privileged tool proxies.
Resource consumption spans beyond request lifecycle : API returns while task still consumes compute, tokens, and external API quotas.
Side effects are not simply retryable : model calls may be idempotent; payments, emails, ticket creation, and DB writes often are not.
Multi-tenant competition is real : bulk offline jobs from one tenant must not starve high-priority interactive requests, yet strict priorities must not cause permanent starvation.
The scheduler manages task lifecycle, resource commitments, and execution authority . It does not replace Kubernetes; Kubernetes places Worker pods, while the application scheduler places tasks into Worker slots and governs task state, tenant fairness, budgets, and business side effects.
2. Overall Architecture: Control Plane Decides, Data Plane Executes, Ledger Adjudicates
2.1 Control Plane vs Data Plane
Control plane: admission service, scheduler, quota/budget logic, reconciler — decides "whether to accept, when to dispatch, where resources are accounted". Data plane: Workers, sandboxes, browsers, model/tool gateways.
Two key consequences:
Scheduler can lose in-memory state and recover from the authoritative ledger; in-memory queues are accelerators, not sources of truth.
Workers may disappear due to OOM, scale-down, or network partition; their heartbeats and self-reported resources are observational evidence only, cannot override conditionally protected state in the ledger.
2.2 Storage Boundaries
PostgreSQL (or equivalent strong-consistency store) stores tasks, attempts, reservations, budget entries, Outbox, and audit events. It decides task acceptance, which attempt is currently valid, which result is eligible for commit.
etcd for leader election and connection topology, but leader election success does not mean the old leader has lost write rights . Old leader may recover after GC pause or network partition; critical writes must still be rejected by database fencing tokens.
Redis for token buckets, hot indexes, short-term caches, fast rejection; must not solely guarantee "request durably accepted". Two-step modify-Redis-then-write-DB creates phantom counts on crash; cached quotas must be reconcilable from ledger.
2.3 Worker Capability Model
Workers are not homogeneous. Scheduling decisions differentiate at least:
Static labels (region, GPU type, arch) — hard filters, cannot be offset by scores.
Allocatable resources (CPU, memory, GPU, sandbox slots, browser slots) — vector capacity with reservation accounting.
Security/compliance capabilities (data residency, trusted env, tool permissions) — hard filters and audit conditions.
Dynamic health (heartbeat, connection, run queue, isolation state) — decides if new tasks can be received.
Affinity (cache, data location, dedicated model proxies) — scoring among feasible candidates.
Labels, compliance, and capabilities filter first; fragmentation, data affinity, and fault domain score only among candidates satisfying hard constraints.
2.4 Cell Boundaries and Capacity Model
A Cell is a failure isolation domain with its own ledger, scheduling leadership, and resource pool. Boundaries should align with data residency, network zones, and replaceable Worker sets. A task belongs to a single Cell for its lifetime; cross-Cell migration is an explicit handoff with new fencing tokens, not a normal retry.
Start conservatively: publish allocatable_memory_mb after subtracting system reserves, DaemonSets, fragmentation buffer, and failure redundancy. sandbox_slots should reflect actual isolatable execution concurrency, not a simple mapping from CPU cores. Capacity ledger aims for a conservative, reconcilable upper bound, not precise OS simulation.
3. Define Correctness Contracts First: What the System Guarantees and Does Not
"Exactly once" is often mistaken as a single scheduler capability. It should be decomposed into four layers:
Admission durability : API success means task and its idempotency info are written to a recoverable ledger.
Attempt at-least-once : For recoverable tasks, failures can spawn new execution attempts; dispatch messages and ACKs may repeat.
Result at-most-once : Ledger accepts only one terminal result from the currently valid attempt; late or duplicate results cannot overwrite new state.
External side-effect business idempotency : Scheduler cannot promise exactly-once for payments, emails, tickets. Tool side must support business idempotency keys, result queries, or compensation flows.
When an external call is "sent but response lost", do not blindly retry. Enter UNKNOWN, query tool side using business idempotency key, then decide success, failure, compensation, or manual intervention. Better to preserve uncertainty explicitly than to cause duplicate charges or notifications for the sake of apparent automation.
4. Domain Model: Task, Attempt, Reservation, and Execution Tokens
Long tasks cannot rely on a single table with a status column. Minimum objects: task: tenant, priority, deadline, resource request, budget, version — one logical business task and its final semantics. attempt: attempt_id, attempt_epoch, Worker, lease, checkpoint — one fail-able, retryable execution. reservation: Worker, resource vector, state, expiry — preemption and actual running resource accounting. budget_ledger: reserved, actual consumed, released, reason — auditable accounting for tokens, cost, tool calls. outbox_event: event type, payload, delivery status, idempotency key — reliably deliver ledger facts to Workers.
4.1 Client Idempotency Is Mandatory
Task table must include tenant_id, idempotency_key, and normalized request request_hash with a unique constraint on the first two. Submission behavior must be stable:
New key: create new task.
Same key, same hash: return existing task_id and current state.
Same key, different hash: return 409 Conflict.
Concurrent unique-key collision: read existing record, compare hash; do not treat DB conflict as success. idempotency_key solves client submission retries; it cannot replace Worker attempt epochs or serve as the sole business idempotency key for external operations.
4.2 Dual Epochs: Attempt Epoch and Scheduler Epoch
Each dispatch generates a unique attempt_id and monotonically increasing attempt_epoch — answers "which attempt of this task is eligible to report".
Scheduler, upon gaining leadership, obtains a monotonically increasing scheduler_epoch — a fencing token answering "which generation of scheduler made resource and dispatch decisions that remain valid". The two cannot substitute each other: former isolates retries, latter isolates old leaders.
4.3 Minimal Schema and Constraints
DDL (not unique implementation) shows where correctness-critical constraints belong. Production systems add partitioning, indexes, archival per query patterns.
CREATE TABLE tasks ( task_id uuid PRIMARY KEY, tenant_id text NOT NULL, idempotency_key text NOT NULL, request_hash bytea NOT NULL, state text NOT NULL, priority integer NOT NULL, queue_deadline timestamptz NOT NULL, run_deadline timestamptz, cancel_requested boolean NOT NULL DEFAULT false, attempt_epoch bigint NOT NULL DEFAULT 0, version bigint NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (tenant_id, idempotency_key) ); CREATE TABLE task_attempts ( attempt_id uuid PRIMARY KEY, task_id uuid NOT NULL REFERENCES tasks(task_id), attempt_epoch bigint NOT NULL, scheduler_epoch bigint NOT NULL, worker_id text NOT NULL, state text NOT NULL, lease_until timestamptz NOT NULL, checkpoint_ref text, version bigint NOT NULL DEFAULT 0, UNIQUE (task_id, attempt_epoch) ); CREATE TABLE reservations ( reservation_id uuid PRIMARY KEY, attempt_id uuid NOT NULL UNIQUE REFERENCES task_attempts(attempt_id), worker_id text NOT NULL, resource_json jsonb NOT NULL, state text NOT NULL, expires_at timestamptz NOT NULL );DB constraints cannot cover all business rules but must enforce what cannot rely on "caller discipline": one task per tenant+idempotency key; unique attempt epoch per task; at most one valid reservation per attempt. State transitions still use conditional updates because ORM "read-then-write" loses races during concurrent cancel, timeout, and takeover.
4.4 API Contract: Let Caller Know What Was Accepted
Submit API receives idempotency key, resource declaration, deadline, budget, side-effect class; returns not "execution started" but "durably admitted" task_id.
{ "idempotency_key": "client-generated-opaque-key", "priority": 60, "queue_deadline": "2026-11-18T10:00:00Z", "resource_request": { "cpu_milli": 1000, "memory_mb": 2048, "sandbox_slots": 1 }, "required_labels": { "region": "ap-southeast" }, "budget": { "max_tokens": 80000, "max_tool_calls": 12 }, "side_effect_class": "idempotent-write" }Query API should distinguish state, cancel_requested, current attempt, failure reason codes, displayable progress; must not leak internal Worker IDs, tool credentials, or raw exception stacks. Cancel returns "cancel intent persisted"; final stop confirmed via state subscription or query.
5. State Machine: State, Resources, and Attempt Must Transition Together
State machine must describe not only business state but also how resource counts and attempts change. Recommended main states and transitions: PENDING → DISPATCHING on reservation success + dispatch event: create attempt, write reservation=HELD, write Outbox. DISPATCHING → RUNNING on current attempt ACK: reservation becomes RUNNING. DISPATCHING → PENDING on ACK timeout/reject: close attempt, release reservation. RUNNING → SUCCEEDED on normal completion: accept unique result, release resources, settle budget. RUNNING → PENDING on recoverable interrupt with valid checkpoint: persist checkpoint, close attempt, release resources. RUNNING → FAILED on non-retryable error/exhaustion: write error classification and audit, release resources.
Non-terminal → CANCELLED on cancel: persist cancel intent, block new dispatch; release resources after stop confirmed.
Queued → EXPIRED on queue deadline: close unstarted attempt, return quota.
Running → TIMED_OUT / BUDGET_EXCEEDED on deadline/budget: persist stop intent, then isolate or wait for stop. RUNNING → UNKNOWN on external side-effect result unknown: freeze auto-retry, enter query/compensation/manual handling. SUCCEEDED, FAILED, CANCELLED, EXPIRED, TIMED_OUT, BUDGET_EXCEEDED are terminal. UNKNOWN is a protective state, not a synonym for failure: must have explicit owner and timeout policy.
Every transition emits immutable audit event with old/new state, reason code, actor, task/attempt/scheduler epochs, idempotency key. Thus pending_count, running resources, budget balances can be rebuilt from ledger, not from potentially lost in-memory history.
5.1 State Transition Implementation Rules
Every write path must declare its compare conditions. Rules covering common concurrency races:
Dispatch : precondition state=PENDING, not cancelled, not expired, version matches. Failure means already handled by another loop, cancel, or expiry.
ACK : current attempt, state=DISPATCHING, reservation not expired. Failure means duplicate ACK, late ACK, or old executor.
Complete : current attempt, state=RUNNING, epoch/version match. Failure means result stale, cannot overwrite ledger.
Cancel : non-terminal and cancel_requested=false. Failure means idempotent repeat cancel, can return current state.
Lease reclamation : attempt still valid and lease_until < now(). Failure means Worker renewed or already taken over by another recovery flow.
Budget deduction : budget account version matches and sufficient allowance. Failure means concurrent consumption used allowance, call should reject or wait.
Do not use "last write wins". For every conditional update affecting 0 rows, log reason and re-read authoritative state: may be normal duplicate message or early signal of fencing defect.
5.2 Checkpoint Validity Conditions
Checkpoint is not an arbitrary object store link. Must save at least task/attempt epoch, runtime version, input snapshot digest, completed tool call business idempotency keys, integrity checksum. Before recovery, verify checkpoint compatible with current task definition; when Agent tools or prompt versions changed, explicitly decide reject recovery, run compatibility adaptation, or re-run from safe boundary. Otherwise "recoverable" only brings corrupted state into new attempt.
6. Admission and Backpressure: Reject at Persistence Boundary
Unconditionally accepting 50,000 tasks collapses memory, DB connections, or cancel channels. Admission service works in order: auth + tenant validation, request size + capability check, deadline/budget validation, rate limiting, queue and global watermark check, finally short transaction to commit task.
Starter implementation locks tenant quota row in one PostgreSQL transaction, checks pending_count < pending_limit, inserts task, writes audit event, increments count, writes Outbox. On successful dispatch, cancel, expiry, or terminal state, must return queue or run counts via conditionally protected transactions.
Under high concurrency, single hot tenant quota row becomes lock contention point. Only after confirming this is a bottleneck, introduce sharded counters or quota token pre-allocation; tokens must have expiry, return, deduplication, and ledger reconciliation paths. Async flush to DB for surface throughput directly weakens scheduling correctness boundary.
Recommended response semantics:
Queue/tenant quota full: HTTP 429 or gRPC RESOURCE_EXHAUSTED with bounded Retry-After.
Authoritative ledger unavailable: 503 Service Unavailable, do not just accept into process memory.
Request idempotency conflict: 409 Conflict.
Admission success: return stable task_id; subsequent query/subscribe uses it.
Queue quota, run quota, and cost budget should be modeled independently. Former protects backlog size, second limits occupied resources, third controls future consumption; collapsing three into one "concurrency number" leaves system unable to explain rejection reasons when busy.
6.1 Degradation Order: Protect Correctness Channels First
Under storage pressure, least sacrificial are existing task completion commits, cancels, and budget settlements. Degrade in order: tighten low-priority new submissions, pause non-critical stats aggregation and index refresh, limit expensive query and debug interfaces. Task state commits and cancel messages should have independent connection pools, rate budgets, monitoring; otherwise "reject new traffic" may cut off safe exit path for running tasks.
7. Multi-Tenant Fairness: Pick Runnable Candidates First, Then DRF
FIFO lets short interactive tasks get stuck behind long tasks; strict priority may starve low-priority forever. Suitable starter model: tenant-isolated queues + cross-tenant Weighted Dominant Resource Fairness (Weighted DRF) + intra-tenant priority aging .
For tenant i , define dominant share s_i = max_r (u_{i,r} / (w_i * C_r)) where w_i is tenant weight, u_{i,r} is tenant's allocated amount on resource r , C_r is allocatable capacity of resource r in pool. Each round prioritize tenant with smaller s_i that has runnable candidates .
Implementation details determine real fairness:
u must include running resources plus valid reservations not yet ACKed, else continuous dispatch oversells during ACK window.
GPU, region pools should use actual contended capacity, not whole Cell total.
Tasks first filtered by labels, compliance, budget, capacity; infeasible queue-head tasks skipped, not blocking whole tenant.
Guaranteed minimums prevent small tenants being squeezed; idle time allows borrowing; reclaiming borrowed resources is the legitimate use of preemption.
Example: pool has 100 sandbox slots, 200 CPU. A uses 20 slots + 20 CPU, B uses 10 slots + 80 CPU; equal weight → A dominant share 20%, B 40% → prioritize A's runnable tasks. If A's task needs GPU not in pool, skip it, don't halt scheduling loop.
7.1 Prevent Head-of-Line Blocking and Intra-Tenant Starvation
Within a tenant, allow backfill from limited scan window to avoid a task waiting for scarce GPU blocking subsequent CPU tasks. But unlimited backfill lets large tasks never run; combine with max wait for large tasks, reservation windows, or capacity watermark protection.
Internal priority can use aging function: effective_priority = base_priority + aging_factor * wait_time . Since key changes over time, ordinary max-heap cannot be built once and never re-sorted. Use time buckets, periodic rebuild, or recalculate and validate on pop. Cross-tenant fairness and intra-tenant aging are different layers: former decides which tenant gets opportunity, latter decides which task within that tenant runs.
7.2 From Theory to Engineering: Single Scheduling Loop Boundaries
DRF is theoretical starting point for multi-resource fairness, not automatic by putting formula in sort function. Discrete GPUs, non-migratable tasks, guaranteed resources, preemption, label partitions weaken theoretical properties; treat as transparent, observable heuristic. Single scheduling loop can be written as:
func ScheduleOnce(now time.Time) (Decision, bool) { for _, tenant := range eligibleTenantsByWeightedShare(now) { for _, task := range tenant.RunnableWindow(now, 32) { if task.CancelRequested || now.After(task.QueueDeadline) { persistTerminalIntent(task) continue } candidates := filterByLabelsCapacityHealthAndBudget(task) if len(candidates) == 0 { recordUnschedulableReason(task) continue } worker := scoreByFragmentationAffinityAndFaultDomain(candidates, task) if reserveAttemptAndWriteOutbox(task, worker, now) { return Decision{TaskID: task.ID, WorkerID: worker.ID}, true } } } return Decision{}, false }RunnableWindowmust be bounded to avoid one huge tenant making each loop a full queue scan; recordUnschedulableReason must distinguish "temporary capacity shortage", "label missing", "budget insufficient", "quota limit" — latter usually should not retry indefinitely. Scheduler should write decision reasons to events or traces to explain "why this task didn't run".
7.3 Guarantees, Borrowing, and Fairness Product Semantics
Weights, guarantees, hard limits express different commitments: weight affects relative share during contention; guarantee is minimum service target when resources idle or reclaimable; hard limit is safety/commercial boundary never exceeded regardless of cluster idleness. Don't misinterpret "VIP higher weight" as "VIP preempts everything". Product must clarify: what resources low-tier tenants borrow, when they can be reclaimed, how interrupted task experience is compensated.
8. Atomic Reservation and Reliable Dispatch: Outbox Guarantees Recoverability, Not Non-Duplication
After scheduler picks Worker, cannot modify in-memory queue then async persist. Correct binding transaction commits together:
Conditional update task with task_id + version + state=PENDING to DISPATCHING.
Create new attempt with incremented attempt_epoch.
Establish resource reservation for that Worker.
Write Outbox event containing dispatch command.
Independent dispatcher sends command at-least-once. Outbox solves "transaction committed but process crashes before sending"; inherently allows duplicate delivery. Worker must deduplicate on (task_id, attempt_id, attempt_epoch): first command persists local takeover record and starts executor; duplicate returns same-semantic ACK; old epoch rejected; newer epoch arrives → isolate old executor first.
ACK write-back also needs state and epoch conditions. Only current DISPATCHING attempt can turn reservation from HELD to RUNNING. ACK timeout does not prove Worker never started; after old attempt closed, late ACK rejected, old Worker must stop or be blocked by gateway.
8.1 Minimum Fields for Dispatch Message and ACK
Dispatch command at minimum: task_id, attempt_id, attempt_epoch, scheduler_epoch, resource reservation summary, lease expiry, checkpoint reference, short-lived execution token. ACK must echo same identity fields, Worker local takeover timestamp, rejection reason. Omitting any epoch field makes troubleshooting unable to distinguish new task, retry, or zombie execution.
Worker takeover record should persist before starting executor; otherwise crash after start but before record makes re-delivered command look like fresh work causing double-start. Local record can be in Worker's lightweight WAL or reliable local DB, retention covering dispatch retry and lease window.
9. High Availability and Takeover: Election Is Not Enough, Must Fence
Single Cell can start with Active-Standby scheduler. Leader decides, standby does not write dispatch decisions; on failover, rebuild from ledger and Worker snapshots. Key is not "how many replicas" but whether old leader can lose write rights.
Each successful leadership acquisition obtains strictly increasing scheduler_epoch from authoritative store. Critical writes use that token, attempt epoch, and version as conditions. Example completion write-back:
UPDATE task_attempt SET state = 'COMPLETED', result_ref = :result_ref, version = version + 1 WHERE task_id = :task_id AND attempt_id = :attempt_id AND attempt_epoch = :attempt_epoch AND scheduler_epoch = :scheduler_epoch AND state = 'RUNNING' AND version = :expected_version;Zero rows affected → do not blindly retry overwrite; treat as stale message, log audit. New leader takes new token, rebuilds PENDING queue, scans incomplete attempts and undelivered Outbox, requests online Workers to report full attempt snapshots. Brief silence only puts Worker into SUSPECT, stops new dispatch; only after lease expiry, isolation, and policy judgment can replacement attempt be created.
Releasing ledger slots does not mean old process stopped. RTO determined by election, ledger recovery, Outbox replay, Worker reporting, isolation actions — cannot promise fixed seconds via a single lease TTL.
9.1 Failure Matrix: Write "What Happens" Into Design
Matrix rows cover: API crash before submit, API crash after commit, Outbox dispatcher crash, ACK lost, leader pause/resume, Worker network partition, tool response lost. Each row defines observable phenomenon, system action, and outcome that must not happen. Matrix serves as design spec and drill checklist; every row should have automated tests, metrics, runbooks, not just exist in architecture docs.
10. Tool Gateway: Last Boundary Against Zombie Side Effects
Worker rejecting old commands is insufficient: old Worker may hold external API credentials, bypass scheduler to call payment, email, business services. For external writes, tool gateway must be sole egress:
Worker holds no long-lived high-privilege credentials for direct business system access.
Obtain short-lived token before execution, bound to task_id, attempt epoch, tenant, allowed tools, quota, expiry.
Gateway verifies attempt still holds execution rights.
Each business write carries stable business idempotency key (e.g., tenant_id + business_operation_id), not attempt ID which changes on retry.
Gateway supports query-by-business-key for timed-out or lost-result calls.
DB conditional updates, Worker epoch validation, and tool gateway authorization must work together to cover zombie execution window.
10.1 Side-Effect Classification: Avoid Treating All Tools as Same
Recommend marking tool/step side-effect class in task definition: read_only (search, query, retrieve) → retry within limits. idempotent_write (create/update with business idempotency key) → query or retry same business key. compensatable_write (reversible reservation) → query then compensate or escalate to manual. irreversible_write (payment, external notification, irreversible approval) → result unknown → UNKNOWN, prohibit auto-replay.
This table maintained jointly by business and platform. Scheduler picks recovery strategy based on declaration; it cannot infer from a network timeout whether business op is safe to redo.
11. Cancel, Preemption, Budget: Persist Intent First, Wait for Fact Confirmation
Cancel request first writes cancel_requested, reason, root task ID to ledger, then notifies Worker and subtasks via Outbox. When dynamically creating subtasks, creation transaction must check root task cancel flag to avoid race producing orphan tasks. For tasks with already-sent non-cancellable external calls, UI shows "cancel requested", not false "cancelled".
Preemption only when recovery capability exists: task interruptible, verified checkpoint, actually borrowing reclaimable resource, recovery cost acceptable. Flow: evaluate gain vs victim cost, persist PREEMPT_REQUESTED, wait for Worker to write versioned checkpoint and confirm stop, then release resources. Timeout → isolate Worker, handle as lost-contact.
To avoid preemption storms: minimum run protection, cooldown window, tenant-level preemption rate, recent-preemption penalty. Cannot assume evicting arbitrary task instantly frees resources for arriving high-priority task: heterogeneous GPUs, node constraints, checkpoint duration, physical cleanup all limit preemption gain.
Budget includes queue deadline, single run deadline, total run deadline, token/cost ceiling, tool call count. Model gateway atomically reserves budget before call, settles by actual usage after, releases remainder; streaming calls continuously check. Relying on Worker reporting usage every few seconds cannot stop multiple concurrent requests from overspending between report intervals.
Budget reservation needs failure handling. If gateway crashes after reservation, unsettled reservation must not lock quota forever; conversely, before auto-release on timeout must confirm corresponding external request won't keep incurring cost. For vendors without precise real-time usage, platform should describe budget policy as "control max exposure and reconcile post-facto", not promise absolute no-overspend.
12. Observability, Reconciliation, and Failure Verification
Logs, metrics, traces must always carry task_id, attempt_id, attempt_epoch, scheduler_epoch, tenant_id. Beyond end-to-end latency, record breakdown: submit→admit, queue, match decision, wait ACK, execute, result commit.
More importantly, continuously verify invariants:
At most one valid running attempt per task → unique constraint, ledger scan, Worker snapshot reconciliation.
Old attempt cannot rewrite terminal state → conditional update row count and rejection events.
Reservation matches actual run → Worker full snapshot vs reservation comparison.
Pending/inflight counts rebuildable → periodic recompute from ledger diff.
Every external write has business idempotency key → tool gateway audit and reject keyless requests.
Budget reservation, consumption, release conserved → budget sub-ledger reconciliation.
These invariants should define alert actions. E.g., "ledger running attempts mismatch Worker snapshots" not just ordinary alert: first restrict new dispatch on affected Workers, then launch conditional-update reconciliation; "old epoch tool call rejected" is expected fence hit, but rate spike signals Worker isolation or lease parameter imbalance.
12.1 Describe Service with SLOs, Not Just a P99
Scheduler SLOs at minimum layered:
Admission SLO : quota-compliant requests with healthy ledger get "accepted/explicitly rejected" within target time.
Interactive Task Queue SLO : under specified capacity and tenant model, target priority task queue latency percentiles.
Correctness SLO : valid attempt overlap count zero, illegal terminal rewrite zero, critical ledger reconciliation diff zero within defined time.
Recovery SLO : time to resume dispatch after failure, time to reconcile incomplete tasks, time for unsafely-recoverable tasks to enter manual queue.
Cost SLO : budget-exceed request interception rate, max unsettled reservation lifetime, anomalous cost reconciliation cycle.
Every SLO needs preconditions: workload ceiling, available Worker ratio, external tool health. Writing these conditions helps readers judge fit better than a context-free "P99 less than X".
Verification starts not from fictional performance numbers but fixed workload, random seed, task duration distribution, model/tool latency, DB config, code version. Compare FIFO, strict priority, Weighted DRF on same trace. Inject at minimum:
Noisy tenant continuous submit → verify high-priority SLO and low-priority max wait.
Unavailable GPU at queue head → verify bounded backfill and large-task wait ceiling.
Kill leader or dispatcher after Outbox write → verify task recoverable and Worker no double-start.
Pause Worker network then restore → verify old attempt commit affects 0 rows, old token rejected by gateway.
Tool executed but response lost → verify task enters UNKNOWN not auto-replay.
Concurrent model calls same task → verify budget not double-reserved or overspent without audit.
Alternating high-priority requests trigger preemption → verify cooldown and checkpoint success rate.
"At most one valid attempt per task" does not mean physical world never runs two processes simultaneously; during failure window old process may not yet be dead. Real acceptance criterion: old process has no acceptable result commit rights and no external tool execution rights.
12.2 Minimum Pre-Launch Drill Set
Before functional canary, run at least one end-to-end drill: submit task with idempotency key and deliberately drop API response; kill dispatcher after dispatch transaction commit; disconnect Worker from control plane before external call; inject object storage failure during checkpoint write; simulate gateway crash after budget reservation. Each drill leaves task/attempt event trail, ledger snapshot, tool-side audit proving system behavior matches design, not just "test passed".
13. Phased Rollout Roadmap
Phase 1: Reliable Ledger. Single Cell, transactional admission, Task/Attempt, Outbox, Worker heartbeat, conditional updates, no-preemption scheduling. First prove task recoverable, duplicate messages don't double-account, old attempt cannot commit.
Phase 2: Isolation and Fairness. Introduce queue/run quotas, bounded backfill, Weighted DRF, budget gateway, reconciliation invariants; tune weights, scan windows, rejection policies per real observations.
Phase 3: Controlled Preemption. Only after checkpoint success rate, recovery time, restart cost, preemption gain quantifiable, canary enable.
Phase 4: Multi-Cell. When single Cell DB writes, scheduling loop, connections, or fault domain become explicit bottlenecks, split by tenant and resource pools. Cross-Cell migration must define task ownership, fencing token authority, tool token switch, handoff protocol; cannot just change routing via consistent hashing.
Conclusion
High-quality Agent Scheduler is not a more complex priority queue. It is a protocol suite facing uncertainty: admission success means recoverable; dispatch can repeat but attempt has epoch; leader can switch but old leader fenced; Worker can revive but tool gateway accepts only current execution rights; external result unknown → system preserves uncertainty and resolves via query or compensation.
When platform can answer at every step of reject, execute, lose-contact, takeover, cancel, recover — "who is executing, where is resource accounted, why is result valid, how are side effects verified" — it has the engineering foundation for production.
References
Ghodsi et al., Dominant Resource Fairness: Fair Allocation of Multiple Resource Types, NSDI 2011
Kubernetes Scheduling Framework
Kubernetes Pod Priority and Preemption
The Transactional Outbox Pattern
For questions about attribution, corrections or content rights, please contactand we will review it promptly.