Cost-Aware Job Scheduler Design
Overview
The CostAwareScheduler is a distributed job orchestration system that schedules jobs on a cluster (e.g., Kubernetes, cloud VMs/GPUs) while enforcing budgets (hard spending limits), priorities (weighted scheduling), and throttling (rate/concurrency limits). It optimizes for cost efficiency by estimating job costs upfront, tracking real-time spend, and favoring low-cost/high-priority jobs.
Key assumptions:
Costs : Billed per resource-second (e.g., 0.001 / C P U − s e c , 0.001/CPU-sec, 0.001/ C P U − sec , 0.01/GPU-sec). Jobs declare estimated costs.
Users/Groups : Hierarchical budgets (user < team < org).
Cluster : Heterogeneous nodes with varying costs (spot vs. on-demand).
Scalability : Handles 10k+ jobs/sec using Redis for state, Kafka for events.
Core Models
Job
yaml Copy code
job:
id: uuid
user_id: string
group_id: string # Optional hierarchy
priority: enum(HIGH=3, MED=2, LOW=1) # Weighted score
estimated_cost: float # USD, based on reqs * duration
actual_cost: float # Updated on completion
resources: {cpu: int, gpu: int, mem_gb: int}
duration_estimate: int # Seconds
queue_time: timestamp
status: PENDING | RUNNING | COMPLETED | FAILED
Budget
Per entity (user/group/org), stored in Redis with TTL refresh:
yaml Copy code
budget:
entity_id: string
total_budget: float # e.g., $1000/month
spent: float # Cumulative actual_cost
reset_period: enum(HOURLY | DAILY | MONTHLY)
hard_limit: bool # Reject if exceeded
Throttle
Per entity, sliding-window counters:
yaml Copy code
throttle:
entity_id: string
max_concurrent: int # e.g., 10 jobs running
max_rps: int # Jobs started per second
window_size: int # Seconds for RPS
current_concurrent: int
recent_starts: deque[timestamps] # For sliding window
Architecture
code Copy code
[Job Submit API] --> [Admission Controller] --> [Priority Queue (Redis Sorted Set)]
|
v
[Scheduler Loop] <-- [Budget/Throttle Service] <-- [Cost Estimator]
| |
v v
[Cluster Dispatcher] --> [Workers/Nodes] --> [Cost Reporter (heartbeat)]
^ |
| +--> [Metrics DB (Prometheus)]
+--------------------------------------+
Admission Controller : Validates on submit (budget check with estimate, throttle RPS).
Priority Queue : Redis ZSET, score = priority * (1 / estimated_cost) + (1 / queue_time) (prioritizes high-pri/low-cost/oldest).
Scheduler : Goroutine loop (every 1s), dequeues eligible jobs.
Services :
Budget Service : Atomic increments (INCRBY spent estimated_cost).
Throttle Service : Check/add to concurrent count; evict old timestamps.
Cost Estimator : ML model or heuristic: cost = resources * rates * duration_estimate * overprovision_factor(0.2).
Observers : Webhooks for budget near-exhaust (90%), priority boosts.
Scheduling Algorithm
Fair-Share Priority with Cost Guardrails (inspired by YARN + Kubernetes Priority).
Dequeue Candidate : Pop highest-score job from ZSET.
Pre-flight Checks (parallel):
Budget : remaining = total - spent >= estimated_cost. If no, requeue with penalty score decay.
Throttle : concurrent < max_concurrent AND recent_starts_in_window < max_rps.
Resources : Fit on cheapest available node (bin-packing via Ray/SchedulerX).
Dispatch if all pass:
Reserve budget: INCRBY spent estimated_cost (refund on failure).
Increment concurrent.
Launch pod/task.
On Completion/Failure :
Report actual_cost via heartbeat.
Atomic: DECR spent (estimated - actual) for refunds.
Decrement concurrent; pop from recent_starts.
Preemption : High-pri jobs can evict low-pri if cluster >80% util and budget allows. Evicted jobs requeue with +10% cost estimate.
Pseudocode (Scheduler Loop):
python Copy code
while True:
job = priority_queue.pop_highest()
if not budget_check(job.user_id, job.estimated_cost) or not throttle_check(job.user_id):
job.score *= 0.9 # Decay
priority_queue.push(job)
continue
node = cheapest_fit_node(job.resources)
if node:
dispatch(job, node)
budget_reserve(job.user_id, job.estimated_cost)
throttle_inc_concurrent(job.user_id)
else:
priority_queue.push(job) # Wait for capacity
sleep(1)
Handling Edge Cases
Scenario Behavior Budget Exhaust Reject new jobs; notify via email/Slack. Running jobs complete (no kill). Over-estimate Refund excess on completion; cap refunds at 50% to prevent gaming. Priority Inversion Time-weighted boost: score += age_minutes / 60. Throttling Burst Token bucket for RPS; soft throttle warns at 80%. Cost Drift If actual > 2x estimate 5x in row, user quota halved. Hierarchy Propagate budgets: user_spent rolls up to group. Check all levels. Failures Retry 3x with exponential backoff; charge partial cost.
Monitoring & APIs
Metrics : Budget utilization (%), queue depth by prio, throttle hits/sec, cost variance (PromQL).
APIs :
POST /jobs: Submit with admission.
GET /budgets/{id}: View remaining.
PATCH /budgets/{id}: Admin top-up.
GET /throttles/{id}: Debug counters.
UI : Dashboard with pie charts (spend by user/prio), Gantt for queues.
Implementation Notes
Tech Stack : Go/Rust for core (low-latency), Redis+etcd for state, Kafka for async events.
Cost : ~$50/mo for 1k-node cluster (Redis HA).
Extensibility : Plugins for custom estimators, ML for prio auto-tune.
This design balances fairness, cost control, and performance. Prototype testable in 2 weeks on k8s-minikube. Questions?