We are designing a resource quota guard for CI (Continuous Integration) that enforces fairness, queuing, and budget limits.
The system should manage multiple jobs (tasks) that request certain resources (e.g., CPU, memory, GPU, etc.) and run on a set of workers (nodes).
We have constraints:
Fairness: No user/team/project should monopolize resources. We want to ensure that over a sliding window (e.g., 24 hours) each user/team gets a fair share.
Queuing: Jobs that cannot run immediately should be queued. The queue should be ordered by priority (which might be based on user/team priority, job age, etc.) but also consider fairness.
Budgets: Each user/team has a budget (e.g., total CPU hours, total GPU hours) that they cannot exceed in a given time window (e.g., monthly). We must not allow jobs to run if they would exceed the budget.
We assume:
We have a set of users/teams, each with:
A budget for each resource type (per time window, e.g., per month) and a current usage (which we track and reset at the end of the window).
A weight or share for fairness (could be the same for all, or different based on agreement). For simplicity, let's assume each user has a weight w_u.
We have a set of workers, each with a set of resources (e.g., CPU cores, memory, GPUs). Resources are discrete (like integer cores) or continuous (like memory in GB). We'll assume discrete for scheduling simplicity.
Jobs are submitted by users and have:
Resource requirements (for each resource type, the amount needed).
Estimated duration (or we can use a maximum duration for safety).
Priority (could be a function of user priority, job age, etc.)
The guard must:
a) When a job is submitted, decide whether to admit it (i.e., schedule it now or put in queue) without exceeding any budget for the user (if it would run in the current window) and without violating the worker resource constraints.
b) When a worker becomes available (or periodically), assign jobs from the queue to workers, respecting:
- The worker's available resources.
- The user's remaining budget for the current window.
- Fairness: we want to ensure that over the window, each user gets approximately their fair share of resources.
Approach:
We'll break the problem into two parts: admission control (when a job is submitted) and scheduling (when resources become available).
Admission Control (on job submission):
Check if the user's remaining budget for any resource (considering the job's requirements and estimated duration) is sufficient. If not, reject the job immediately (or put in a rejected state?).
Also check if there are any workers that can satisfy the job's resource requirements (at least one worker with enough free resources). If not, we might still put the job in queue if we expect resources to free up? But note: if no worker can ever run it (because requirements are too high for any worker) then we should reject.
However, note that the job might be queued and run later when resources free up and the user's budget might be consumed by other jobs in the meantime. So we cannot just check current free resources.
Instead, we can do:
For each user, we have a "pending" resource usage for the current window: the sum of resources for jobs that are queued or running (and we know the estimated duration). We can compute the total expected usage for the user if all queued jobs run (but note: queued jobs might not run if resources don't become available). This is tricky.
Alternatively, we can admit jobs to the queue without checking resource availability at submission time, but then when scheduling we must check the user's budget and the worker's resources. However, if we admit a job that will never run (because the user's budget will be exceeded by other jobs that run first), then we are just filling the queue with jobs that will eventually be rejected. So we want to avoid that.
Proposed:
Maintain for each user:
current_used_resources: resources used by running jobs (for each resource type, in terms of current usage, i.e., if a job uses 4 CPU for 1 hour, then at any time it is using 4 CPU until it finishes).
pending_resources: the sum of resources for all jobs (queued and running) that belong to the user, but note: for queued jobs we don't know when they will run. We can only count the resources if we assume they will run? But that might overcommit.
We can do a conservative estimate: for each user, we look at the queued jobs (in order of the queue) and assume they will run in that order. Then we can simulate the future: when a worker becomes available, we assign the first job in the queue that fits and that the user has budget for. But that simulation is complex and must be updated as jobs finish.
Given the complexity, we might take a simpler approach:
On job submission, we check:
If the user's current_used_resources + the job's resources (for the duration of the job) would exceed the user's budget for any resource (if the job were to run now), then we reject the job. But note: the job might run later when some of the user's current jobs finish, so the current_used_resources might go down. However, we are concerned with the total usage in the window, so if the user already has a lot of usage, we might not want to admit more even if current load is low because the new job would add to the total.
Actually, the budget is about total consumption over the window, not about instantaneous usage. So we need to track:
total_consumed_resources[user][resource] = sum over all finished jobs in the window (or running jobs, we count the resources multiplied by their duration so far?).
But note: for a running job, we have already consumed some resources (from start time until now). For a queued job, we haven't consumed any yet.
So we can maintain for each user:
total_consumed: the total amount of resource consumed so far in the window (for each resource type). For a running job, we update this as time passes? Or we can compute at the end of the job? That's not real-time.
Alternatively, we can track:
- For each running job: we know its start time and resource requirements. Then the consumed resource up to now is (current_time - start_time) * resource_requirement. But then when we admit a new job, we need to estimate how much of the currently running jobs will finish before the new job starts? That's too complex.
Given the difficulty, we might define the budget as: the total resource-seconds (or resource-hours) that the user can consume in the window. Then for a job that we are about to admit (to run now or in the future) we must ensure that:
But note: if the job is queued, we don't know when it will run. However, if we admit it to the queue, we are committing to run it eventually (unless we reject it later). So we must be sure that even if it runs at the worst possible time (when the user has already used almost all budget) it won't exceed. Therefore, we should do:
Let pending_jobs = all queued jobs (including the new one) and running jobs for the user.
We need to simulate the execution of these jobs in some order (the order they will run) and see if the total consumption (for each resource) would exceed the budget.
This is a bin packing problem with time. We can try to schedule the user's jobs (both running and queued) in a way that minimizes the peak resource usage? But we care about total consumption, not peak.
Actually, the budget is about total resource-time. So regardless of when the jobs run, the total resource-time consumed by the user's jobs is the sum of (resource_requirement * duration) for each job. Therefore, we can compute:
total_consumption_if_all_jobs_run = sum_{job in (running and queued)} (job.resource * job.estimated_duration)
Then if total_consumption_if_all_jobs_run + total_consumed_so_far (from finished jobs in the window) > budget, then we cannot admit the new job because even if we run all the user's jobs (including the new one) we would exceed the budget.
But note: we might not run all queued jobs if resources are not available. However, we are admitting the job to the queue with the intention of running it if possible. So we must be conservative and assume we will run it. Therefore, we check:
if (total_consumed_so_far + sum_{job in (running and queued for user)} (job.resource * job.estimated_duration)) > budget[user][resource] for any resource, then reject.
However, note that for running jobs, we have already consumed some portion of their resource-time. So we should not double count.
Let:
- For each running job: consumed_so_far = (current_time - job.start_time) * job.resource.
- Then the remaining resource-time for that job is job.resource * job.estimated_duration - consumed_so_far.
So for the user, the total consumption if all jobs (running and queued) run to completion would be:
But note: total_consumed_so_far already includes the consumed_so_far for running jobs? We need to be consistent.
Let's define:
total_consumed_so_far[user][resource] = sum over all finished jobs in the current window (resource_consumed) +
sum over running jobs (resource_requirement * (current_time - start_time))
Then when we admit a new job, we compute:
potential_total_consumption = total_consumed_so_far[user][resource] +
(for each running job: resource_requirement * estimated_duration) [but note we already counted the consumed part?]
+ (for each queued job including the new one: resource_requirement * estimated_duration)
But wait, for running jobs we have already counted the consumed part in total_consumed_so_far, and we are going to add the entire job's resource*estimated_duration? That would double count the consumed part.
Instead, we can compute:
total_consumption_if_all_jobs_run = total_consumed_so_far[user][resource] (which includes consumed part of running jobs) +
sum_{running job} (resource_requirement * (estimated_duration - (current_time - start_time))) + // the remaining part
sum_{queued job} (resource_requirement * estimated_duration)
Alternatively, we can track:
For each user, we have:
- total_consumed: from finished jobs and the consumed part of running jobs.
- For each running job, we know the remaining resource-time (resource * (estimated_duration - elapsed)).
- For each queued job, we know the full resource-time.
Then when admitting a new job, we add its resource-time to the queued jobs and check:
total_consumed + sum(running remaining) + sum(queued resource-time) <= budget
This seems correct.
So at admission:
Let user_total = user.total_consumed[resource] +
sum_{running job of user} (job.resource * (job.estimated_duration - (now - job.start_time))) +
sum_{queued job of user} (job.resource * job.estimated_duration) +
(new_job.resource * new_job.estimated_duration)
If for any resource, user_total > budget[user][resource], then reject.
But note: the queued jobs might not run in the current window if the window ends before they start. We are being conservative by assuming they will run in the current window.
We also need to check worker resource availability? Not at admission time because the job is going to the queue. But we might want to check if there is at least one worker that can run the job (in terms of resource capacity). If not, we might reject because the job will never run. However, if we have autoscaling, we might add workers. So maybe we don't reject based on worker availability at admission.
So admission control:
- Check budget as above. If exceeds, reject.
- Optionally, check if there exists at least one worker that has enough resources (capacity) to run the job. If not, and we don't plan to add workers, then reject.
Then if both checks pass, admit to queue.
Scheduling (when a worker becomes available or periodically):
We have a queue of jobs (ordered by some priority, but we want to enforce fairness). The idea of fairness is that over the window, each user gets a share proportional to their weight.
We can use a deficit round-robin or similar. But note: we have multiple resource types and multiple workers.
Alternatively, we can think of the fairness as: at any time, the amount of resources allocated to a user (running jobs) should be proportional to their weight, but also considering their budget (they cannot exceed budget).
However, the budget is a hard limit, and fairness is about distribution when there is contention.
We can do:
For each user, compute a "fair share" of resources. But resources are multi-dimensional.
One approach: we can compute a score for each user that represents how much they have used relative to their fair share and budget.
Let:
fair_share[user] = (user.weight / total_weight) * total_cluster_resources[resource] for each resource.
But note: the cluster resources might vary because of worker availability.
Alternatively, we can use a weighted fair queuing for the queue. But we have multiple resources.
Given the complexity, we might simplify:
We want to ensure that over the window, each user gets at least their fair share of the total resources (subject to their budget). But note: if a user has a high budget, they might want to use more, but we also have to be fair to others.
Actually, the fairness constraint is: no user should get more than their fair share of resources when there is contention. But if a user has a high budget and there is no contention, they can use more.
So we can think of the cluster as having a total capacity for each resource. We want to allocate resources to users in proportion to their weights, but also not exceed their budget.
We can do:
At scheduling time, for each user, compute:
usage_rate[user][resource] = (current_used_resources[user][resource] / elapsed_time_in_window) [if we are in the middle of the window]
Then the fair share rate is (user.weight / total_weight) * total_cluster_resources[resource].
We want to prevent a user from having a usage rate that exceeds their fair share rate by too much (unless they have budget left and others don't).
However, this is a moving target and hard to enforce at job scheduling time.
Another idea: we can use a concept of "credits" for each user. Each user gets credits at a rate proportional to their weight. When they run a job, they consume credits (based on resource and duration). They cannot run a job if they don't have enough credits. But note: the budget is a hard limit, so we can set the total credits per window to be the budget? But budget is in resource-time, and credits would be in resource-time too.
System Overview
The guard sits between CI job submissions and execution, acting as a central admission controller and scheduler that makes decisions based on:
Fairness: Prevents any user/team from monopolizing resources
Budget constraints: Enforces hard caps on consumption
Queue management: Prioritizes work fairly while maximizing utilization
1. Core Concepts & Terminology
Entities
User/Team: Consumer identity with associated weights, budgets, and quotas
Resource Types: CPU cores, memory (GB), GPU, build minutes, storage, etc.
Workers/Agents: Execution nodes with fixed/variable capacities
Jobs: CI tasks with resource requests, duration estimates, priorities
Time Windows
Budget Window: Monthly/quarterly hard caps (e.g., 10,000 CPU-hours/month)
Fairness Window: Sliding window for fair-share calculations (e.g., 24 hours)
Queue Aging Window: Time-based priority boost for long-waiting jobs
2. Data Structures
class User:
id: str
weight: float # Relative share (sum to 1.0 across all users)
budgets: Dict[ResourceType, float] # Per resource, per budget window
priority: int # Optional business priority override
class Worker:
id: str
capacity: Dict[ResourceType, float] # Total resources
allocated: Dict[ResourceType, float] # Currently allocated
tags: List[str] # For affinity/anti-affinity
class Job:
id: str
user_id: str
resource_requests: Dict[ResourceType, float]
estimated_duration: timedelta
actual_duration: timedelta # Updated on completion
priority: int # Base priority
submitted_at: datetime
queue_position: int # Dynamic
class QuotaState:
# Per user, per resource
consumed_budget: Dict[str, Dict[ResourceType, float]] # Current window
consumed_fairness: Dict[str, Dict[ResourceType, float]] # Sliding window
queued_resource_time: Dict[str, Dict[ResourceType, float]] # Sum of (req * est_duration) for queued jobs
class FairnessScore:
# Dynamic per user
deficit: float # How far behind fair share
last_calculated: datetime
3. Admission Control (On Job Submission)
Step 1: Budget Check (Reject if fails)
def check_budget(user_id, job):
for resource, amount in job.resource_requests.items():
# Current consumed + (job req * estimated duration) + other queued jobs
total_potential = (
state.consumed_budget[user_id][resource] +
job.resource_requests[resource] * job.estimated_duration.hours +
state.queued_resource_time[user_id][resource]
)
if total_potential > user.budgets[resource]:
return False, "Budget exceeded"
return True, "OK"
Step 2: Feasibility Check
Verify at least one worker can satisfy job.resource_requests (accounting for current allocations)
Check for required tags/affinities
If no worker currently available but autoscaling possible → queue with "resource pending" flag
Step 3: Fairness Pre-check (Soft)
Calculate if admitting this job would push user too far below fair share (prevent starvation):
fair_share = (user.weight / total_weights) * cluster_resources[resource] * fairness_window_hours
if (consumed_fairness[user_id][resource] +
job.resource_requests[resource] * job.estimated_duration.hours) > fair_share * 1.2:
# User already ahead, but we might still admit if queue empty
return "QUEUE_WITH_LOW_PRIORITY"
Decision:
Reject: Budget exceeded or impossible to schedule
Admit-High: Fits budget & resources & user is behind fair share
Admit-Low: Fits budget but user is ahead (lower queue priority)
Smaller jobs get slight boost to improve throughput
Queue is maintained as a priority heap keyed by -score (max-heap).
5. Scheduling Algorithm (When Worker Free)
Trigger Conditions:
Worker reports available capacity
Periodic rebalancing (every 30s)
Job completion
Selection Process:
def schedule_for_worker(worker):
candidates = []
for job in queue:
if job.fits_on(worker) and not exceeds_budget(job):
candidates.append(job)
if not candidates:
return None
# Pick highest priority candidate
return max(candidates, key=lambda j: j.queue_score)
for job in running_jobs:
elapsed = now - job.last_update
for resource, amount in job.resource_requests.items():
consumed_budget[job.user][resource] += amount * elapsed.hours
consumed_fairness[job.user][resource] += amount * elapsed.hours
job.last_update = now
Rolling fair window:
Remove entries older than fairness_window (24h) from consumed_fairness
Recalculate fairness scores
Check for budget overruns (if job runs longer than estimated):
if consumed_budget[user][resource] > user.budgets[resource]:
# throttling or kill policy
throttle_user(user) # or kill longest-running job
7. Handling Edge Cases
A. Budget Exceeded During Runtime
Soft kill: After grace period (e.g., 5min over), kill job with lowest priority
Throttling: Reduce concurrency for user to 0 until window slides
B. Worker Failure/Scaling
Re-allocate job to queue with queued_resource_time restored
Adjust consumed_budget downward for elapsed time only (not full estimate)
C. Priority Inversions
Allow admin override (break fairness) for critical jobs (security patches)
Such jobs count double against fair share deficit
D. Multi-Cluster/Region
Extend Worker with cluster_id
Fairness computed per-cluster or globally based on policy
Deadline-aware: Schedule time-sensitive jobs first
This design provides strong budget guarantees, provable fairness within sliding windows, and responsive queuing while remaining implementable. The key insight is separating hard budget checks (monthly) from soft fairness enforcement (24h sliding window) with a composite queue priority that self-corrects over time.
Let's define:
For each user and each resource, we have:
credit_balance[user][resource] = (user.weight / total_weight) * (total_cluster_resources[resource] * window_duration) - total_consumed_so_far[user][resource]
Then when scheduling a job, we require that the user has enough credit_balance to cover the job's resource * estimated_duration.
But note: the total_cluster_resources[resource] * window_duration is the total resource-time available in the window if the cluster is fully utilized. And we are distributing that by weight.
However, this does not account for the fact that the cluster might not be fully utilized. We want to allow users to use more if there is idle capacity? But then fairness might be violated.
Alternatively, we can set the credit allocation to be:
credit_allocation[user][resource] = (user.weight / total_weight) * (max_available_resource_time_in_window)
where max_available_resource_time_in_window = sum_{worker} (worker.resource * window_duration) [assuming workers are always available].
But if a worker is down, then the max available is less.
We can update the credit allocation dynamically based on the current available resources? That would be complex.
Given the complexity, let's step back.
We have two constraints:
Budget: total consumption in window <= budget.
Fairness: over the window, each user gets at least their fair share (proportional to weight) of the cluster resources, but not more than their budget.
Actually, the budget might be higher or lower than the fair share. So we want:
For each user and resource:
total_consumed[user][resource] <= min(budget[user][resource], fair_share[user][resource])
But note: if the user's budget is higher than the fair share, they cannot exceed the fair share when there is contention? That's the fairness part.
However, if there is no contention (i.e., the cluster is underutilized), then we might allow the user to use more than their fair share? But then we are not being fair to others? Actually, fairness is about sharing when there is scarcity. So we can allow overuse when there is idle capacity.
So we need to define:
Let available_resource_time_in_window = sum_{worker} (worker.resource * window_duration) - (sum of resource-time already consumed by all users in the window)
Then we can allocate the available resource-time to users in proportion to their weights, but also respecting their remaining budget.
This is getting very complex.
Given the time, we might choose a simpler heuristic:
We'll enforce the budget strictly (no job will run if it would cause the user to exceed budget).
For fairness, we'll use a weighted fair queuing on the queue. That is, when multiple users have jobs queued, we schedule jobs from users in proportion to their weights, but also considering the user's current usage (so that users that have used less get higher priority).
We can define a priority for each job:
priority(job) = job.arrival_time + (some function of user's deficit)
But we want to avoid starvation.
Alternatively, we can use a deficit round-robin:
For each user, maintain a deficit[user] (for each resource? or one deficit per user?).
When a job from user u is scheduled, we decrease deficit[u] by (job.resource * job.estimated_duration) * (total_weight / user.weight) [so that we are accounting for the user's share].
Then when selecting the next job, we pick the user with the highest deficit (most behind their fair share) and then the oldest job from that user.
But note: we have multiple resources. We can combine them by using a weighted sum? Or we can do per-resource deficit? That might be too complex.
Given the complexity of multiple resources, we might simplify by choosing a primary resource (like CPU) for fairness and queuing, and then for scheduling we also check other resources.
Alternatively, we can use a single composite score for the job's resource requirements, e.g., normalized by the cluster's total resources.
Let's define:
normalized_resource(job) = sum_{resource} (job.resource[resource] / cluster_total[resource]) [or weighted by importance]
Then the user's deficit is increased by normalized_resource(job) * (total_weight / user.weight) when the job runs.
Then when picking the next job, we pick the user with the highest deficit, and within that user the oldest job that fits on the available worker.
But note: we also have to check the user's budget and the worker's resources.
Steps for scheduling:
When a worker becomes free (or periodically), we look at the queue and try to assign a job.
We consider the jobs in the queue in an order that respects fairness:
For each user, compute a score that includes:
- The user's current deficit (how much they are behind their fair share) -> higher deficit means higher priority.
- The job's priority (maybe age) within the user.
Then we sort the users by deficit (descending) and within the same deficit by some user priority (if any). Then for each user in that order, we try to schedule their oldest job (or highest priority job) that fits on the worker and that the user has budget for.
How to compute deficit?
Let:
total_weight = sum of all user weights.
Let fair_share_rate = (user.weight / total_weight) * total_cluster_resources[primary_resource] [per unit time?]
But we are dealing with resource-time (not rate). So we can track:
user_consumed_resource_time[user] = total_consumed_so_far[user][primary_resource] [for the window]
user_fair_share_resource_time = (user.weight / total_weight) * (total_cluster_resources[primary_resource] * elapsed_time_in_window)
Then deficit[user] = user_fair_share_resource_time - user_consumed_resource_time[user]
But note: we are scheduling jobs that will consume more. So when we schedule a job with resource r and duration d, we decrease the deficit by r*d.
However, we are using the primary resource for deficit. We could also use a composite.
Alternatively, we can use:
deficit[user] = (user.weight / total_weight) * (total_cluster_resource_time_available_in_window) - user_consumed_resource_time[user]
where total_cluster_resource_time_available_in_window = sum_{worker} (worker.primary_resource * window_duration) [fixed at the beginning of the window?]
But if the window is sliding, we update the fair share as time passes.
Given the complexity, let's assume we have a fixed window (e.g., monthly) and we reset at the beginning of the window.
Then:
at start of window:
user_fair_share[user] = (user.weight / total_weight) * (total_cluster_primary_resource * window_duration)
Then deficit[user] = user_fair_share[user] - user_consumed[user]
When a job runs, we subtract job.primary_resource * job.estimated_duration from deficit[user].
But note: the job might not use the full duration if it finishes early. We can update when the job finishes.
However, for scheduling we don't know the actual duration, only estimated. So we use estimated.
Then the scheduling algorithm:
while there are free resources on a worker and jobs in the queue:
For each user, compute current deficit (as above, using estimated duration for running jobs? or actual? We can use estimated for queued jobs and for running jobs we use the remaining estimated duration?).
Actually, for running jobs, we have already deducted their full estimated duration when they started? Or we update as they run?
Let's decide:
When a job starts, we deduct its full estimated resource-time from the user's deficit.
If the job finishes early, we add back the unused portion? But then the deficit would become larger (more positive) which is okay because we want to allow the user to run more if they finish early.
Alternatively, we can deduct only the actual consumption when the job finishes. But then at scheduling time we are using estimated, which might be inaccurate.
Given the complexity, we can use:
At scheduling time for a queued job, we check:
if (user_consumed[user] + job.resource * job.estimated_duration) > user_budget[user] -> skip this job for now (but it might be the only job for the user, then we might have to run it if there's no other job? But we cannot exceed budget, so we skip).
And we also check the worker's resources.
Then we pick the job from the user with the highest deficit (most behind) that fits and within budget.
But note: the deficit is computed using the fair share for the entire window. If the window is long (monthly) then the deficit changes slowly.
However, we want to be fair in the short term too? Maybe we can have a shorter sliding window for fairness (like 24 hours) and a longer window for budget (monthly).
Given the problem statement: "fairness, queuing, and do not exceed budgets", we might have two time windows:
- Budget: monthly (or weekly) hard limit.
- Fairness: over a sliding window (e.g., 24 hours) we want to ensure that each user gets their fair share.
So we need to track two things:
For each user and resource:
- monthly_consumed: for budget.
- fair_window_consumed: for fairness (over the last 24 hours, for example).
But note: the fair_window_quota is not a fixed quota, it's a rate. We want to ensure that over the last 24 hours, the user has not exceeded their fair share.
Actually, we can compute:
Let fair_share_last_24h = (user.weight / total_weight) * (total_cluster_primary_resource * 24 hours)
Then we require:
fair_window_consumed[user] + job.resource * job.estimated_duration <= fair_share_last_24h
But that would be too restrictive because the user might have used less in the last 24h and we want to allow them to catch up.
Instead, we use the deficit approach for the fairness window:
deficit_fair[user] = fair_share_last_24h - fair_window_consumed[user]
Then we require that the job's resource-time does not exceed the deficit_fair? That would mean we only allow the user to run jobs up to their fair share for the last 24h. But if they have a high deficit (i.e., they haven't used their fair share) then they can run more.
Actually, we want to allocate the available resource-time (in the fairness window) to users in proportion to their weights. So if a user has a high deficit (meaning they are behind), they should get priority.
So we don't prevent a user from running if they are over their fair share? We want to prevent them from getting too far ahead.
Therefore, we can allow a user to run a job only if:
fair_window_consumed[user] + job.resource * job.estimated_duration <= fair_share_last_24h * (1 + tolerance)
And we use the deficit to prioritize.
Given the complexity, let's simplify the requirement:
We want to enforce:
- Do not exceed budget (monthly).
- Fairness: over a sliding window (e.g., 24h), each user gets at least their fair share (proportional to weight). But we don't want to let a user get too far ahead.
So we can do:
For each user, track:
- monthly_consumed: total resource-time consumed in the current month.
- fair_consumed: total resource-time consumed in the last 24h (or since the start of the fairness window).
Then when scheduling a job:
if monthly_consumed + job.resource * job.estimated_duration > monthly_budget: reject.
if fair_consumed + job.resource * job.estimated_duration > (user.weight/total_weight) * (total_cluster_primary_resource * 24h) * (1 + tolerance):
then we might still allow if there is no other job waiting? But then we are violating fairness.
Instead, we use the deficit to decide who gets the resource when there is contention.
So the scheduling algorithm:
When a worker is free, we look at all queued jobs that:
- fit on the worker (resource requirements <= worker's free resources)
- do not cause the user to exceed monthly budget (if run now, with estimated duration)
Among these, we pick the job from the user with the largest deficit in the fairness window.
How to compute deficit for fairness window?
Let:
fair_share_24h = (user.weight / total_weight) * (total_cluster_primary_resource * 24*3600) [if we are in seconds]
deficit = fair_share_24h - fair_consumed[user]
But note: fair_consumed[user] is the total resource-time consumed by the user in the last 24h. We need to update it as time passes (for running jobs) and when jobs finish.
Then we pick the user with the highest deficit (most behind) and then the oldest job (or highest priority) from that user that fits.
However, we have multiple resources. We can use a primary resource for fairness (e.g., CPU) and then for scheduling we also check other resources.
But what if a job uses a lot of GPU but little CPU? Then using CPU for fairness might not be fair. We can use a composite:
fair_share_24h for a composite resource:
composite_resource(job) = sum_{resource} (job.resource[resource] / cluster_total[resource])
Then the fair_share_24h for the user is (user.weight/total_weight) * (sum_{resource} (cluster_total[resource] * 24h))? That doesn't make sense because resources are in different units.
Alternatively, we can define a weight for each resource and then compute a normalized resource-time.
Given the complexity, let's assume we are only concerned with one resource (like CPU) for fairness and budget. For other resources (like GPU) we only check budget and worker capacity.
But the problem says "resource quota guard", so we have multiple resources.
Given the time, I propose:
We will handle multiple resources for budget and worker capacity, but for fairness we pick a primary resource (say CPU) and use that for deficit calculation.
Steps:
Data structures:
For each user u:
- weight[u]
- budget[u][resource] (for each resource type)
- monthly_consumed[u][resource] (updated when jobs finish and periodically for running jobs)
- fair_consumed[u] (for the primary resource, over the last 24h)
For each job j:
- user
- resource_requirements[resource]
- estimated_duration
- start_time (if running)
For each worker w:
- capacity[resource]
Queue: list of jobs, ordered by arrival time? But we will reorder based on user deficit.
Admission:
When a job j is submitted by user u:
For each resource r:
potential_consumption = monthly_consumed[u][r] +
sum_{running jobs of u} (job.resource[r] * (estimated_duration - (now - job.start_time))) +
sum_{queued jobs of u} (job.resource[r] * job.estimated_duration) +
j.resource[r] * j.estimated_duration
if potential_consumption > budget[u][r]:
reject job.
Also, check if there exists at least one worker w such that for all resources r: w.capacity[r] >= j.resource[r]. If not, and we don't plan to add workers, then reject.
Otherwise, admit to queue.
Scheduling:
Periodically (or when a worker becomes free), for each free worker w:
Consider all queued jobs j such that:
- j fits on w (for all r: j.resource[r] <= w.free_capacity[r])
- for user u=j.user:
monthly_consumed[u][r] + j.resource[r] * j.estimated_duration <= budget[u][r] for all r.
Among these jobs, we want to pick one that maximizes fairness.
We compute for each user u that has at least one fitting job:
deficit[u] = fair_share_24h[u] - fair_consumed[u]
where fair_share_24h[u] = (u.weight / total_weight) * (total_cluster_primary_resource * 24*3600)
Then we pick the user with the largest deficit (if positive, meaning they are behind; if negative, they are ahead and we might skip them?).
Then from that user, we pick the oldest job (or highest priority) that fits on w.
Then we assign that job to w, and update:
w.free_capacity[r] -= j.resource[r] for all r.
For user u:
monthly_consumed[u][r] += j.resource[r] * j.estimated_duration [we will adjust when job finishes?]
fair_consumed[u] += j.resource[primary_resource] * j.estimated_duration
We also record the job as running with start_time = now.
When a job finishes:
For user u:
For each resource r:
actual_consumed = j.resource[r] * (finish_time - start_time)
monthly_consumed[u][r] -= (j.resource[r] * j.estimated_duration) [we remove the estimated, then add actual?]
monthly_consumed[u][r] += actual_consumed
fair_consumed[u] -= j.resource[primary_resource] * j.estimated_duration
fair_consumed[u] += actual_consumed for primary resource.
But note: we don't want to adjust monthly_consumed by the estimated and then actual because we already added the estimated when the job started. So we can do:
monthly_consumed[u][r] += (actual_consumed - j.resource[r] * j.estimated_duration) [the delta]
Alternatively, we can track:
monthly_consumed[u][r] = sum of (resource * actual_duration) for finished jobs in the window + for running jobs: resource * (current_time - start_time)
Then we don't need to adjust when a job finishes? We update running jobs periodically.
It might be simpler to update monthly_consumed and fair_consumed periodically (e.g., every minute) for all running jobs by adding (resource * time_since_last_update). Then when a job finishes, we stop updating it.
So:
We have a background process that every, say, 1 minute:
For each running job j:
elapsed = now - last_update_time
For each resource r:
monthly_consumed[j.user][r] += j.resource[r] * elapsed
fair_consumed[j.user] += j.resource[primary_resource] * elapsed
Then set last_update_time = now.
When a job starts, we set its last_update_time to now (or the start time) and then the next update will account from then.
When a job finishes, we do one last update from the last_update_time to finish_time.
Then we don't need to adjust when the job finishes? We already accounted for the actual time.
But then when we admit a job, we use estimated_duration to check budget. That might be inaccurate if the job runs longer. We can allow overrun if the user has budget? But we don't want to exceed budget.
So we need to be conservative: use the maximum duration (or a high estimate) for budget check.
This is a reasonable approach.
However, note: the fair_consumed is only for the primary resource. We might want to use a composite for fairness. But for simplicity, we use primary.
Also, note that the fairness window is sliding (24h). So we need to subtract old consumption that falls out of the window.
We can maintain for each user a circular buffer of their job completions (with resource-time and timestamp) for the last 24h for the primary resource. Then fair_consumed[u] is the sum of resource-time for jobs that finished in the last 24h plus the running jobs' consumption in the last 24h.
Alternatively, we can update fair_consumed in the same way as monthly_consumed but with a sliding window. That is, we keep a record of when each resource-time was consumed and subtract the ones that are older than 24h. That's complex.
Given the complexity, we might fix the fairness window to be the same as the budget window? But the problem says "fairness" and "budget" separately, so they might have different windows.
Let's assume:
- Budget window: monthly (or weekly) -> we reset monthly_consumed at the beginning of the month.
- Fairness window: last 24 hours (sliding) -> we need to subtract consumption that is older than 24h.
We can do:
For each user, we maintain a list of events (job start and job finish) with timestamps and resource-time for the primary resource.
Then fair_consumed[u] = sum of resource-time for events in the last 24h.
But that requires storing a lot of data.
Alternatively, we can approximate: we update fair_consumed every minute by adding the resource-time used in the last minute for running jobs, and when a job finishes, we add the full resource-time at the finish time. Then we also subtract the resource-time that was added 24h ago? We can use a circular buffer for the per-minute contributions.
Given the complexity, we might choose a fixed window for fairness (like the current day) and reset at midnight. Then we don't have sliding window, we have a fixed window (from midnight to now). Then fair_consumed[u] is the consumption since midnight. That's easier.
But the problem says "sliding window", so we should do sliding.
Given the time, let's assume we do:
We maintain for each user:
fair_consumed[u] = current consumption in the last 24h (for primary resource).
We update it every minute by:
for each running job j:
fair_consumed[u] += j.resource[primary] * (1/60) [if we update every minute]
And when a job finishes, we add the remaining resource-time (from last update to finish) and then we also need to subtract the resource-time that is exactly 24h old? We can keep a queue of the per-minute contributions for each user and subtract the ones that are 24h old.
This is getting very complex for an interview question.
Given the constraints, I think we should outline the high-level design and note the complexities.
Summary:
We have:
- Admission control: check budget (using estimated duration for all jobs including queued) and worker capacity.
- Scheduling: use a weighted fair queuing based on a deficit calculated for a fairness window (last 24h) for a primary resource.
- Tracking consumption: we track monthly_consumed (for budget) and fair_consumed (for fairness) for each user.
- Updates:
* When a job starts: we don't immediately add to consumption because we already added the estimated when admitting? Actually, we added the estimated to the potential_consumption check, but we haven't added to the actual consumed. We need to add to the actual consumed when the job runs.
So when a job starts, we add the estimated resource-time to monthly_consumed and fair_consumed? But then if the job runs longer, we will have to adjust.
Instead, we do:
At admission, we only check the budget without adding anything.
When the job starts, we add the estimated resource-time to the user's monthly_consumed and fair_consumed. Then we have a background process that updates the running jobs' consumption (by actual time) and adjusts.
But then if a job runs longer than estimated, we will have over-committed the budget.
So we need to use the maximum possible duration for budget check, and then if the job runs longer, we might exceed the budget. We cannot allow that.
Therefore, we must either:
a) Kill the job if it exceeds the budget, or
b) Use a conservative estimate (like the maximum possible duration) for budget check.
We'll assume we use a conservative estimate (the job's maximum allowed duration, or a high estimate).
Given the time, I think we have to leave some details.
Final design:
Components:
1. Admission Controller:
- On job submission:
* Check if the user's potential total consumption (including the new job and all queued/running jobs, using estimated duration) exceeds the monthly budget for any resource. If yes, reject.
* Check if there is at least one worker that can satisfy the job's resource requirements. If not, reject (or if we have autoscaling, we might wait? but then we don't know when workers will be added, so we reject).
* Otherwise, admit to the queue.
2. Scheduler:
- Triggered when a worker becomes free or periodically.
- For each free worker, consider all queued jobs that:
a) Fit on the worker (resource-wise).
b) For the user, the monthly_consumed (including the job's estimated resource-time) does not exceed the monthly budget.
- Among these, compute for each user a fairness deficit for the primary resource:
deficit[u] = fair_share_24h[u] - fair_consumed[u]
where fair_share_24h[u] = (u.weight / total_weight) * (total_cluster_primary_resource * 24h)
- Pick the user with the largest deficit (if positive, meaning they are behind). If no user has positive deficit, then we pick the user with the smallest deficit (least ahead) to avoid letting some users get too far ahead? Actually, we want to give priority to those who are behind, so we pick the largest deficit (most positive). If all deficits are negative, then we are in a situation where all users have exceeded their fair share? That shouldn't happen if we are enforcing the fair_consumed update correctly? But note: the fair_consumed is for the last 24h, and the fair_share_24h is for 24h. If a user has used more than their fair share in the last 24h, their deficit is negative. We don't want to schedule them until their deficit becomes positive? That would mean we only schedule users that are behind. But if all users are ahead, then we have over-committed the cluster? Actually, the fair_share_24h is based on the total cluster resource, so if we schedule jobs such that the total consumption in 24h exceeds the total cluster resource * 24h, then all users will have negative deficit. That's impossible because the cluster can only provide so much. So if we have a job that fits and the user is within budget, we should schedule it even if the user is ahead? But then we are not being fair.
We want to ensure that over the 24h window, no user exceeds their fair share. So we should not schedule a job for a user if it would cause their fair_consumed to exceed fair_share_24h? But then if all users are below, we can schedule any. But if some are above and some below, we should schedule the ones that are below.
So we can set a condition:
if fair_consumed[u] + j.resource[primary] * j.estimated_duration > fair_share_24h[u]:
then we do not schedule this job for now (unless there are no other jobs?).
But then we might have a situation where a user is above their fair share but there is idle capacity and other users have no jobs. We might want to allow the user to use the idle capacity? But then we are violating fairness.
Given the requirement of fairness, we should not allow a user to exceed their fair share in the window, even if there is idle capacity? That might be too strict.
Alternatively, we can allow overuse if the cluster is underutilized? But then how do we define underutilized?
We can define:
total_consumed_last_24h = sum_{all users} fair_consumed[u]
total_fair_share = sum_{all users} fair_share_24h[u] = total_cluster_primary_resource * 24h
Then if total_consumed_last_24h < total_fair_share, we have idle capacity. Then we can allow users to use more than their fair share? But then we are not being fair because some users might use the idle capacity and others not.
Given the complexity, let's stick to:
We only schedule a job for user u if:
fair_consumed[u] + j.resource[primary] * j.estimated_duration <= fair_share_24h[u]
And we pick the user with the largest deficit (which is positive) that has a job that fits and meets the above condition.
If no user meets the condition, then we don't schedule any job until the fairness window slides (so that old consumption falls off) or until a job from a user with positive deficit arrives.
3. Updating consumption:
We have a background process that every minute:
For each running job j:
elapsed = now - j.last_update
For each resource r:
monthly_consumed[j.user][r] += j.resource[r] * elapsed
fair_consumed[j.user] += j.resource[primary] * elapsed
j.last_update = now
When a job finishes:
We update from the last_update to finish_time (as above) and then remove the job.
For the fairness window, we also need to subtract consumption that is older than 24h. We can do:
For each user, we maintain a list of (timestamp, resource_time) for the primary resource for the last 24h.
Every minute, we add the resource_time for the last minute for running jobs.
And we subtract the resource_time that is exactly 24h old.
Alternatively, we can compute fair_consumed[u] on the fly by summing the resource-time for all events (job runs) in the last 24h. But that might be expensive.
Given the complexity, we might approximate the fairness window by:
fair_consumed[u] = monthly_consumed[u][primary] [if the budget window is longer than 24h and we reset monthly_consumed at the beginning of the month, then monthly_consumed is for the current month, not last 24h]
That doesn't work.
We need a separate tracking for the last 24h.
We can do:
For each user, we have a queue of (timestamp, resource_time) for the primary resource.
When we update running jobs, we push (now, resource_time_used_in_this_update) to the queue.
Then we remove from the front of the queue while the timestamp is older than 24h.
Then fair_consumed[u] = sum of resource_time in the queue.
This is O(1) per user per update if we maintain the sum.
This is a very complex system.
Given the interview setting, we might not need to go into such detail. We can outline the main ideas and note the challenges.
Let's write a high-level design:
We have:
- Job submission:
* Check budget (conservative, using estimated duration for all user jobs including queued) and worker capacity.
* If passes, enqueue.
- Scheduler:
* When a worker is free, consider jobs that fit and for which the user's monthly budget would not be exceeded (using estimated duration).
* Rank the users by their deficit in the fairness window (for a primary resource).
* Pick the job from the highest deficit user that fits.
- Tracking:
* monthly_consumed[user][resource]: updated in real-time for running jobs (by adding resource*elapsed_time) and when jobs finish.
* fair_consumed[user]: for the primary resource, maintained by a sliding window of 24h. We use a queue of (timestamp, resource_time) per user and a running sum.
- Background: every minute, update all running jobs by adding resource*elapsed to the respective consumptions and push to the fair_consumed queue (for primary resource). Then remove old entries from the fair_consumed queue (older than 24h) and subtract from fair_consumed.
This design enforces budget strictly and tries to enforce fairness by giving priority to users who are behind their fair share.
However, note: the budget check at scheduling uses estimated duration. If the job runs longer, we might exceed the budget. We can:
- Kill the job if it exceeds the budget (by monitoring the actual consumption and stopping when the budget would be exceeded).
- Or, we can use a conservative estimate (the maximum possible duration) so that we don't exceed.
We'll assume we use a conservative estimate.
Also, note that the fairness window is for the primary resource only. We might want to consider multiple resources for fairness. We can extend by having a fair_consumed for each resource and a fair_share for each resource, and then combine them by a weight. But that's more complex.
Given the time, we'll present the design with one primary resource for fairness.
Let's write the answer accordingly.
We'll also note that we might have multiple workers and we need to consider the total cluster resources for the primary resource for the fair_share_24h.
Implementation details:
- We need to track the total cluster primary resource capacity (sum of primary resource over all workers). This is fixed unless workers are added/removed.
- When a worker is added or removed, we update the total_cluster_primary_resource and adjust the fair_share_24h for all users?
Actually, the fair_share_24h is based on the total cluster capacity at the time of the window? We can fix it for the window? Or update dynamically.
We can update the total_cluster_primary_resource when workers change, and then the fair_share_24h for the remaining time in the window changes. That might cause users to suddenly have a higher or lower fair share.
To avoid complexity, we can fix the total_cluster_primary_resource for the fairness window at the beginning of the window? But then if we add workers, we are not accounting for the extra capacity.
Alternatively, we can use the current total_cluster_primary_resource and update the fair_share_24h as:
fair_share_24h[u] = (u.weight / total_weight) * (current_total_cluster_primary_resource * remaining_time_in_window)
But then the fair_share_24h changes as time passes and as workers change.
Given the complexity, we assume the cluster is fixed for the window.
We'll assume the cluster size is fixed for the fairness window.
This is a very complex system, and in practice, there are existing systems like Kubernetes with resource quotas and fair queuing (e.g., YARN, Kubernetes with priority and fairness). We are designing a simplified version.
Let's write the answer in a structured way.
We'll have:
- Introduction
- Data Structures
- Admission Control
- Scheduling
- Tracking and Updates
- Handling of Overruns and Failures
- Scaling and Worker Changes
- Conclusion
Given the time, we'll write a concise design.
Note: This is a high-level design and might not cover all edge cases.
Let's begin.
I'll design a comprehensive Resource Quota Guard for CI that balances fairness, queuing, and budget enforcement across multiple dimensions (users/teams, resources, time windows).