CI Resource Quota Guard Design
Overview
The CI Quota Guard is a stateless, scalable middleware service that sits between CI job submitters (e.g., Jenkins, GitLab Runners, GitHub Actions) and the underlying compute cluster (e.g., Kubernetes, AWS Batch). It enforces fairness via weighted round-robin scheduling, queuing for oversubscribed resources, and strict budget enforcement to prevent overuse.
Key guarantees:
- Fairness: Tenants (users/projects) get resources proportional to their budget shares.
- Queuing: Jobs wait in a durable queue instead of failing/rejecting.
- Budgets: Hard caps on concurrent jobs, CPU/memory, and time-based usage (e.g., CPU-hours/day).
- No overspend: Real-time monitoring kills violating jobs; budgets reset on schedules (daily/weekly).
Assumptions:
- Cluster provides resource availability signals (e.g., via Prometheus or K8s API).
- Jobs declare requests (CPU, RAM, estimated duration).
- Tenants are identified by ID (user/project/org).
Core Requirements
| Feature | Description | Enforcement |
|---|
| Budgets | Per-tenant: max_concurrent_jobs, max_cpu_cores, max_ram_gb, cpu_hours_per_day | Cumulative tracking + admission control |
| Fairness | Proportional allocation (e.g., tenant A: 40% budget → ~40% slots) | Weighted Deficit Round-Robin (DRR) queuing |
| Queuing | Global queue with per-tenant sub-queues; TTL for stale jobs | Redis/Kafka for durability; auto-dispatch on free slots |
| Overages | Never exceed budgets or cluster capacity | Kill jobs + penalize tenant (temp quota reduction) |
| Observability | Metrics/logs for queue depth, usage, wait times | Prometheus/Grafana export |
| Scalability | Handle 10k+ jobs/sec, 1M+ tenants | Horizontal pods + sharded queues |
High-Level Architecture
[CI Clients] --> [Quota Guard API] --> [Durable Queue (Redis/Kafka)]
|
v
[Resource Poller] <--> [Compute Cluster (K8s/AWS Batch)]
^ |
| v
[Quota DB (Postgres/Etcd)] <-- [Job Monitor (sidecar/enforcer)]
- API Gateway: Validates/authenticates submissions, performs admission checks.
- Durable Queue: Holds pending jobs; partitioned by tenant for locality.
- Resource Poller: Watches cluster free capacity + tenant quotas every 5s.
- Quota DB: Tracks budgets, current usage (running/queued CPU projection).
- Job Monitor: Per-job sidecar or cluster webhook enforces runtime limits.
Data Models
Tenant:
id: string
budgets:
max_concurrent: int (e.g., 10)
max_cpu: float (e.g., 32.0 cores)
cpu_hours_per_day: float (e.g., 1000)
weight: float (for fairness, e.g., budget_total / sum_all_budgets)
reset_schedule: cron (e.g., "0 0 * * *") # Daily reset
Job:
id: uuid
tenant_id: string
req_cpu: float
req_ram_gb: float
est_duration_min: int # For projection
priority: int (0-10, overrides weight for urgent jobs)
status: pending/running/completed/killed
queued_at: timestamp
Key Algorithms
1. Admission Control (on Submit)
Reject if any check fails; else enqueue.
function admit(job):
tenant = get_tenant(job.tenant_id)
projected_cpu = sum(running_jobs_cpu) + sum(queued_jobs_cpu) + job.req_cpu
if projected_cpu > tenant.max_cpu or
len(running + queued) >= tenant.max_concurrent or
projected_cpu_hours_today() > tenant.cpu_hours_per_day:
reject("Quota exceeded")
enqueue(job)
- Projection:
queued_cpu = sum(job.req_cpu * (est_duration / avg_cluster_util)) (dampened for conservatism).
2. Queuing & Fairness (Dispatch)
Global scheduler uses Weighted Deficit Round-Robin (DRR) for tenant selection:
- Each tenant has a "deficit" (owed resources based on weight).
- Poll free cluster slots (e.g., 4 CPU free).
- Cycle tenants; serve job if deficit > 0 and quota allows.
class DRRScheduler:
tenants_deficits = {} # tenant_id -> deficit (float)
function dispatch(free_cpu):
for tenant in round_robin_order:
if tenants_deficits[tenant] <= 0: continue
job = dequeue_highest_priority(tenant.queue)
if job and can_admit(job) and job.req_cpu <= free_cpu:
schedule_job(job)
tenants_deficits[tenant] -= job.req_cpu * tenant.weight
free_cpu -= job.req_cpu
if free_cpu <= 0: break
else:
tenants_deficits[tenant] += quantum # Accumulate deficit
- Quantum: Fixed size (e.g., 1 CPU) for fairness.
- Priority Boost: Urgent jobs (priority > 5) jump queue within tenant.
- Starvation Prevention: Max queue time (e.g., 2h) → force-dispatch or expire.
3. Budget Tracking & Enforcement
- DB Updates:
- Enqueue:
queued_cpu += job.req_cpu
- Start:
running_cpu += job.req_cpu; queued_cpu -=
- End:
running_cpu -=; total_used_cpu_hours += actual_duration
- Daily Reset: Cron job zeros
used_cpu_hours.
- Runtime Guard:
- Sidecar/container limits: K8s
resources.limits.
- Overuse (>110%): SIGKILL + tenant penalty (
max_concurrent -= 2 for 1h).
- Cluster Capacity: Never dispatch if cluster free < 10% headroom.
Implementation Stack
| Component | Tech | Rationale |
|---|
| API/Queue | Go + Gin + Redis Streams | Low-latency, durable queues |
| DB | CockroachDB (distributed Postgres) | ACID quotas, sharding by tenant |
| Scheduler | Go cron + Kubernetes CronJob | Reliable polling |
| Monitoring | Prometheus + OpenTelemetry | Queue depth, wait time P99, budget % |
| Cluster Integration | K8s Admission Webhook + Metrics Server | Native enforcement |
Deployment & Ops
- HA: 3+ replicas, leader-election for scheduler.
- Config: YAML budgets loaded from GitOps.
- Migration: Start with soft quotas (warnings), harden to hard.
- Cost: ~$0.01/1000 jobs processed.
Edge Cases Handled
- Budget Exhaust: Queue indefinitely (fairness preserves order).
- Tenant Bankruptcy: Auto-pause new submits until reset.
- Job Failure: Release resources immediately; retry up to 3x (queued).
- Overestimation: Penalize tenants with >20% overrun (reduce future quantum).
- Hotspot Tenants: Weight auto-adjusts if one tenant dominates queue.
This design ensures a reliable, fair CI system that scales to enterprise loads. Questions or refinements? 🔍