Resources: CPU, Memory, GPU, specialized hardware, or abstract "credits" (dollars).
Scope: Is this per user? Per repository? Per organization? Let's assume a hierarchy (Org -> Project -> User).
Budgets: Hard limits (stop immediately if exceeded) vs. Soft limits (alert/warn). The prompt says "Do not exceed," implying hard limits.
Step 2: High-Level Components
Interceptor/Admission Controller: Sits before the CI job starts. It checks with the Guard.
Quota Service (The Guard): The brain. Maintains state (who used what, who is waiting).
Queue: A priority queue or FIFO queue for pending jobs.
Usage Tracker: Monitors actual resource consumption (hard part in distributed systems).
Repository: Persistent storage for historical data and configuration.
Step 3: The Algorithm (Fairness & Queuing)
Queuing: A simple FIFO isn't enough for fairness because a large org might spam the queue. We need "Weighted Fair Queuing" or "Round Robin" across distinct tenants.
Fairness Strategy:
Stratified Concurrency: Limit active jobs per tenant. E.g., Tenant A max 5 concurrent, Tenant B max 5 concurrent.
Global Budget Fairness: If Tenant A has used 90% of the monthly budget, throttle them harder than Tenant B who used 10%.
Admission Logic:
Job Request arrives.
Check Hard Budget (Is the account negative?). If yes -> Reject.
Check Concurrency (Are they running too many?). If yes -> Queue.
Check Global Capacity (Is the system full?). If yes -> Queue (wait for slot).
If Fair & Space exists -> Run.
Step 4: The Budget (Do Not Exceed)
Pre-check: We estimate the cost. If (current_usage + estimated_cost) > budget, reject or ask for manual override.
Real-time check: This is hard. If a job runs longer than expected, it might overdraw.
Solution: Use a "Token Bucket" or "Leaky Bucket" approach, or simply a hard timeout.
Cost Attribution: We need a sidecar or a monitoring agent that reports usage back to the Quota Service periodically.
Step 5: Technical Design Details (Pseudo-code/Logic)
I should provide a code structure or API design.
ReleaseQuota(job_id, actual_cost): Updates the counter.
Refining the "Fairness" aspect:
How to prevent starvation? If Tenant A has 1000 jobs and Tenant B has 1, Tenant B shouldn't wait forever behind A's backlog.
Priority Queue: Weighted by recent usage (Least recently used gets priority).
Refining the "Do Not Exceed" aspect:
Distributed race conditions are the enemy. If two jobs check the budget ($10 left) at the exact same time, both might start.
Solution: Atomic operations in Redis (Lua scripts) or Database Optimistic Locking.
Drafting the response structure:
Objective: Define what we are solving.
Architecture Diagram (Mental Model): API Gateway -> Quota Service -> Resource Pool.
Key Components:
Admission Control (The Gatekeeper).
The Scheduler (The Queue Manager).
The Meter (The Accountant).
The Algorithms (The "Secret Sauce"):
Budget enforcement (Atomic check-and-decrement).
Fairness (Weighted Round Robin / Hierarchical Token Bucket).
Queuing (Priority queues).
Data Model: Tables/Structs.
Code Example: Python/Go snippet for the core logic.
Edge Cases: What happens when a runner dies?
Self-Correction/Critique during drafting:Initial thought: Just use a database counter.
Critique: Too slow for high-throughput CI. Need Redis/In-memory cache for the fast path. Use DB only for persistence/reconciliation.
Initial thought on Fairness: FIFO queue.
Critique: Bad for fairness. One user can DoS others. Must use "Tenant-based Queueing" (separate virtual queues for each tenant, then select fairly from them).
Final Polish:
Make sure to emphasize the "Hard Budget" part. CI costs money (cloud minutes). Overrun is bad.
Make sure to mention "Graceful degradation" - if the quota service is down, should CI stop? (Usually yes, fail-safe, or readonly mode).
Let's write it out.
Structure:
Core Concept: The "Bouncer" analogy.
Architecture: Control Plane (Decision) vs Data Plane (Execution).
Mechanism 1: Hard Budgets: The "Credit System" with atomic locks.
Mechanism 3: Execution Guard: Watchdogs and Heartbeats.
Implementation Guide: Code snippets using Redis.
(Self-Correction on "Fairness"): A common algorithm is CFS (Completely Fair Scheduler) from Linux, or simpler "Fair Share" scheduling used in HPC (High Performance Computing) or AWS Batch. I will suggest Hierarchical Token Buckets (HTB) or Weighted Round Robin across tenant queues.
Let's refine the "Do not exceed" part. This is tricky. If I estimate a job takes 5 mins, but it takes 50, I broke the budget.
Strategy:
Reservation: Reserve max possible units.
Incremental Consumption: Deduct as you go.
Hard Kill: If credits run to 0 during execution, kill the pod.
Okay, ready to generate.
Designing a Resource Quota Guard for a Continuous Integration (CI) system requires balancing three competing goals: strict budget adherence (Finance/Management goal), system stability (Ops goal), and developer velocity (User goal).
Here is a comprehensive design for a CI Resource Quota Guard, broken down into architecture, core algorithms, and implementation strategies.
1. High-Level Architecture
The system acts as a middleware layer between the CI Trigger (webhook/event) and the CI Runner (execution engine). It functions as a Stateful Admission Controller.
The Core Components:
The Gate (API): Intercepts job requests. Returns 200 OK (Accepted), 202 Accepted (Queued), or 429/403 (Over Budget).
The Ledger (State Store): A high-speed, atomic storage (e.g., Redis) tracking current usage and historical burn rate.
The Scheduler (Queue Manager): Holds deferred jobs and decides which job pops next based on fairness policies.
The Observer (Telemetry): Monitors active jobs to reconcile estimated costs vs. actual costs.
2. The Three Core Algorithms
A. Hard Budget Enforcement (The "Do Not Exceed" Rule)
To ensure you never exceed a budget (e.g., Monthly Cloud Spend), you must move from "metering" (counting after the fact) to "reservation" (counting upfront).
Cost Estimation: When a job arrives, the Guard calculates an estimated cost (e.g., estimated_minutes * runner_cost).
Atomic Check-and-Decrement:
The Guard queries the Ledger for the remaining budget.
Action: Immediately deduct EstimatedCost from the budget atomically.
Overdraft Protection: If the job finishes under the estimate, the difference is credited back (Refund). If it goes over, the excess is deducted (Overage), but the next job will see a lower budget.
Strict Mode: If the budget hits zero, all subsequent jobs are rejected immediately with a clear error message: "Monthly CI Budget Exhausted. Contact admin."
B. Fairness (The "No Hogging" Rule)
Fairness ensures that one heavy user (or a burst of commits from one team) doesn't starve others. We implement Hierarchical Fair Scheduling.
Hierarchy: Root -> Teams -> Projects.
Weights: Assign weights to queues (e.g., Team A: 50%, Team B: 50%).
Algorithm: Use Deficit Round Robin (DRR) or Fair Queueing.
If Team A has 100 jobs queued and Team B has 1 job, the Guard cycles between them, ensuring Team B’s job runs quickly while Team A’s queue drains steadily.
Implementation: Maintain a "Virtual Time" for each queue. The job with the earliest "Virtual Finish Time" runs next.
C. Queuing (The "Backpressure" Valve)
When concurrency limits are reached (e.g., "Max 50 runners"), jobs must wait.
Priority Queuing: Not all jobs are equal. Main branch builds > Nightly builds > PR linting.
Aging: A job waiting in the queue for too long should get a temporary priority boost to prevent starvation.
Dead Letter Queue (DLQ): If a job waits longer than TTL (Time To Live), it is moved to DLQ and failed automatically to prevent running stale tests.
concurrency:current: Integer. Total active jobs across the system.
concurrency:team:{team_id}: Integer. Active jobs per team.
queue:{priority}:{team_id}: Sorted Set (ZSET).
Score: Submission timestamp (for FIFO/Fairness).
Member: Job ID.
job:{job_id}:meta: Hash.
estimated_cost: Float.
actual_cost: Float (initially 0).
start_time: Timestamp.
4. The Workflow (Lifecycle of a Job)
Phase 1: Admission (The Intercept)
Incoming: User pushes code -> CI Trigger -> Guard API.
Check Concurrency:
Is concurrency:current < Global Limit?
Is concurrency:team:{id} < Team Limit?
Check Budget:
Estimate cost (e.g., 5 credits).
WATCH budget:monthly:remaining.
If remaining < 5: REJECT (Budget exceeded).
MULTI -> DECRBY 5 -> EXEC.
Decision:
If Slots open AND Budget OK -> TRIGGER RUNNER.
If Slots full OR Budget OK -> ENQUEUE.
Phase 2: Queuing (The Wait)
Job is pushed to queue:{priority}:{team_id}.
Background Worker (The Popper):
Loops constantly.
Checks if slots are available.
Applies Fairness logic (Round Robin across team queues).
Pops job -> TRIGGER RUNNER.
Phase 3: Execution & Reconciliation (The Run)
Heartbeat: The runner sends heartbeats to the Guard to extend the "hard timeout" (safety net).
Completion:
Runner sends JobFinished event with actual_duration.
Reconcile:
actual_cost = duration * rate
delta = actual_cost - estimated_cost
INCRBY budget:monthly:remaining {delta} (Refund or Deduct extra).
5. Implementation Logic (Pseudo-Code)
Here is the logic for the Admit function, which is the critical path.
python
class QuotaGuard:
def admit_job(self, job):
# 1. Calculate Cost
estimated_cost = self.estimate_cost(job)
# 2. Check Hard Budget (Atomic Transaction)
# We use a Lua script in Redis to ensure this is atomic
# Script: check if value > 0, then decrement, else return fail
budget_ok = redis.execute_script("""
local remaining = redis.call('GET', KEYS[1])
if tonumber(remaining) >= tonumber(ARGV[1]) then
redis.call('DECRBY', KEYS[1], ARGV[1])
return 1
else
return 0
end
""", keys=['budget:monthly:remaining'], args=[estimated_cost])
if not budget_ok:
raise QuotaExceededError("Monthly budget exhausted.")
# 3. Check Concurrency
current_load = redis.get("concurrency:current")
if current_load < MAX_GLOBAL_CONCURRENCY:
# Check Team Fairness/Weight limits here...
# If space available, run immediately
redis.incr("concurrency:current")
self.dispatcher.launch(job)
return "RUNNING"
# 4. Queue if busy
else:
# Add to sorted set (score = timestamp for FIFO)
redis.zadd(f"queue:{job.priority}:{job.team_id}", {job.id: time.time()})
return "QUEUED"
def finish_job(self, job, actual_duration):
actual_cost = actual_duration * RATE
estimated_cost = job.estimated_cost
# 1. Adjust Budget (Reconcile)
delta = estimated_cost - actual_cost
if delta != 0:
redis.incrby("budget:monthly:remaining", delta) # Refund if over-estimated
# 2. Free Slot
redis.decr("concurrency:current")
# 3. Trigger Scheduler to pop next job
self.scheduler.pop_next()
6. Advanced Considerations
Bursting: If you use cloud providers, you might allow bursting over the concurrency limit for a short time if the queue depth is too high, but this costs extra.
Preemption (Priority Kill): If a "Critical" build comes in (e.g., Production Hotfix) but the system is full of "Low Priority" builds, the Guard can cancel/evict a low-priority running job, pause it, and re-queue it to make room.
Budget Smoothing: To prevent the CI from halting completely on the 20th of the month, implement a "Burn Rate Limiter." If the daily burn rate is too high, artificially throttle concurrency even if the monthly budget is technically still available.