Each class has:
- soft_limit
- hard_limit (>= soft_limit)
- priority (a number, higher is more important)
We maintain:
- active_connections per class
- a queue (waiting requests) per class (FIFO)
When a connection is released (from class X, so active[X] decreases by 1), we:
Step 1: Check if there is any class with waiting requests that is below its hard_limit. Among these, pick the class with the highest priority. If multiple, pick the one with the longest waiting queue? or the one that has been waiting the longest? We can do:
candidate_classes = [C for C in priority_classes if active[C] < hard_limit[C] and queue[C] not empty]
Then sort by:
primary: priority (descending)
secondary: queue length? or maybe the age of the first request in the queue? We can track the timestamp of the first request in each queue.
Step 2: If there is a candidate, assign the connection to that class (pop the first request from that class's queue, and assign the connection). Then active[that_class] increases by 1.
Step 3: If no candidate, then the connection becomes idle.
When a request comes for class A:
If active[A] < soft_limit[A] and there is an idle connection, assign immediately (and active[A]++).
Else if active[A] < hard_limit[A] and there is an idle connection, assign immediately (but note: we are above soft_limit, so we are using spillover).
Else (no idle connection or active[A] already at hard_limit) then put the request in the queue for A.
But note: if there is an idle connection and we have a request for A that is above soft_limit, we might want to check if there is a higher priority class waiting? But we are processing the request immediately if there is an idle connection. That might starve higher priority classes that are waiting.
So we should not assign immediately to a class above soft_limit if there is a higher priority class waiting? But then we are making the request for A wait even though there is an idle connection? That might be acceptable if we want to prioritize.
Alternatively, we can have:
When a request comes, if there is an idle connection, we don't assign immediately. Instead, we put the request in the queue and then trigger a check (like when a connection is released) to assign the idle connection to the highest priority waiting request.
But then we are queuing even when there are idle connections? That might increase latency for low priority classes when there are idle connections and high priority classes are not requesting? Actually, if a high priority class is not requesting, then the low priority class should get the idle connection.
So let's change:
We have a global set of idle connections.
When a request comes for class A:
if there is an idle connection, we consider:
if active[A] < soft_limit[A]:
assign immediately.
else:
# We are above soft_limit, so we are in spillover.
# But we should check if there is a higher priority class waiting? But we are processing the request now, so we don't know about future requests.
# We can check the current queues: if there is a class B with higher priority that has waiting requests and active[B] < hard_limit[B], then we should not assign to A? But note: B's requests are already waiting, so they came before? Not necessarily.
This becomes complex.
Let's simplify:
We always queue the request if:
- active[A] >= hard_limit[A], OR
- active[A] >= soft_limit[A] and there is no idle connection.
But if there is an idle connection and active[A] >= soft_limit[A] (but < hard_limit[A]), we can assign immediately? But then we might be assigning to A while a higher priority class B is waiting and active[B] < hard_limit[B]? But B's requests are already queued, so they came earlier? Not necessarily.
To be fair, we can use:
When a request comes, we put it in the queue for its class.
Then, whenever a connection becomes available (either because a client released it or because we just started and have idle connections), we run the assignment algorithm:
While there are idle connections and there is a class with a waiting request that is below its hard_limit:
pick the class with the highest priority (and if tie, the one with the longest waiting time for the first request in the queue) and assign one connection to that class (pop the first request, assign the connection).
So we don't assign immediately when a request comes. We always queue and then the idle connections are assigned by the above algorithm.
But then if there are idle connections and a request comes for a class that is below soft_limit, we don't assign immediately? We put it in the queue and then the assignment algorithm will assign it immediately because it's the only waiting request? But if there are multiple classes, the assignment algorithm will pick the highest priority.
This is acceptable.
Steps:
Request for class A:
1. Add the request to the queue of class A.
2. Trigger the assignment algorithm (if there are idle connections and waiting requests).
Connection release (from class X):
1. active[X]--
2. The connection becomes idle.
3. Trigger the assignment algorithm.
Assignment algorithm:
while idle_connections > 0 and there exists a class C with queue[C] not empty and active[C] < hard_limit[C]:
choose the class C with the highest priority (and if tie, the one with the oldest first request in the queue?).
pop the first request from queue[C]
assign the connection to that request (so active[C]++, idle_connections--)
This way, we always assign idle connections to the highest priority waiting class that is below its hard limit.
But note: what if a class is below soft_limit? It might not be the highest priority, but it is below soft_limit. Should we give it priority over a class above soft_limit? We already have the priority field. We can set the priority of a class to be higher if it is below soft_limit? But that would be dynamic.
Alternatively, we can have two queues: one for classes below soft_limit (with higher priority) and one for above? But that complicates.
We can adjust the priority value of a class based on how far it is from its soft_limit? But that might be too dynamic.
Let's keep it simple: the priority is fixed per class. The soft_limit and hard_limit are adaptive, but the priority is fixed (e.g., user: 100, analytics: 50, admin: 200).
Then the assignment algorithm will always give the connection to the highest fixed priority class that is below its hard_limit.
This means that if a high priority class is above its soft_limit but below hard_limit, it will still get the connection over a low priority class that is below soft_limit? Yes.
That might be acceptable because we want to prioritize the high priority class even if it is using spillover.
However, we might want to guarantee that a class gets at least its soft_limit. But note: the soft_limit is adaptive and might be set to the expected minimum. But if the high priority class is using more than its soft_limit, then the low priority class might not get its soft_limit? But that's the point of priority: high priority gets more.
But we also want to avoid starvation of low priority classes. So we can have:
We adjust the soft_limits and hard_limits based on usage. If a low priority class is constantly waiting, we might increase its soft_limit and decrease the high priority's soft_limit? But then we are adapting.
So the adaptive limits part:
We periodically (say every 5 minutes) adjust the soft_limits (and maybe hard_limits) of each class.
How to adjust?
We want to achieve:
- Classes with high priority should get more connections.
- But we also want to avoid that a class hogs all connections and causes others to starve.
We can use a feedback loop:
For each class, we look at:
wait_time_avg: average wait time for requests in the last period.
queue_length_avg: average queue length.
If a class has high wait time and long queue, we want to increase its limit (soft and hard) so that it can get more connections.
But we have a global total_max_connections. So we need to redistribute the total.
We can set:
total_soft_limit = total_max_connections (or less, to leave room for spillover? but we have hard_limits that can be above soft_limit).
Actually, we can set:
sum(soft_limits) = total_max_connections * (1 - spillover_reserve)
where spillover_reserve is a fraction (say 0.1) that we leave for spillover? But then the hard_limits can be up to soft_limit + spillover_capacity, and the spillover_capacity is taken from the spillover_reserve? Not exactly.
Alternatively, we can think of:
total_max_connections = N
We set soft_limits such that sum(soft_limits) <= N.
And we set hard_limits such that:
hard_limit[C] = soft_limit[C] + spillover_capacity[C]
and we require that max_possible_total = sum(hard_limits) >= N? But we cannot exceed N at any time.
Actually, we cannot guarantee that we can meet all hard_limits because the total active connections cannot exceed N.
So we adjust soft_limits based on demand, but we must have:
sum(soft_limits) <= N
and then we set hard_limits as:
hard_limit[C] = min(soft_limit[C] + spillover_buffer, N) # but then we might have sum(hard_limits) > N, which is okay because we cannot exceed N.
But note: the assignment algorithm only assigns if active[C] < hard_limit[C] and there are idle connections. The idle connections are N - total_active. So even if hard_limit[C] is set to 100, if total_active is N, we cannot assign.
So the hard_limit is only a per-class cap that is enforced when there are idle connections? Actually, we enforce:
We only assign to C if active[C] < hard_limit[C] and there are idle connections.
But if total_active is N, there are no idle connections, so we don't assign anyway.
Therefore, the hard_limit is only relevant when there are idle connections.
So we can set:
soft_limits: the minimum guaranteed when the pool is fully utilized? Not exactly, because when the pool is fully utilized (total_active = N) we might have a class that is above its soft_limit and another below? But we don't take from one class to give to another. So the soft_limit is not a guarantee when the pool is full.
Actually, the soft_limit is the limit that we try to enforce when there is no spillover (i.e., when total_active < N). But when total_active = N, we are not assigning any more, so the soft_limit doesn't matter.
So the soft_limit is only a limit for when there are idle connections? No, we assign to a class if active[C] < hard_limit[C] and there is an idle connection. So if a class is above soft_limit but below hard_limit, it can still get connections if there are idle connections.
Therefore, the soft_limit is not a hard limit. It's just a threshold for when we consider the class to be in "spillover" mode? But we don't change behavior based on soft_limit vs hard_limit in the assignment algorithm? We only check hard_limit.
Then what is the point of soft_limit? We might want to use it for adaptive adjustment.
Let's redefine:
We have two limits per class:
min_limit: the minimum number of connections we want to guarantee for this class (adaptive). This is the soft_limit.
max_limit: the maximum number of connections this class can use (adaptive). This is the hard_limit.
And we require:
min_limit <= max_limit
And we want:
sum(min_limit) <= total_max_connections (we cannot guarantee more than total_max_connections)
But note: when the pool is not full, a class can use up to max_limit.
In the assignment algorithm, we only enforce max_limit.
Then why have min_limit? We use it for adaptive adjustment: we want to increase min_limit for classes that are undersupplied (high wait time) and decrease for those that are oversupplied? But note: if a class is above its min_limit, it might still be below max_limit and get connections.
Actually, we can adjust both min and max limits.
We can set:
Initially:
min_limit = initial_share (based on priority weights)
max_limit = min_limit + spillover_buffer (same for all classes? or based on priority?)
Then periodically, we adjust:
For each class, we compute a score:
score = (wait_time_avg * weight1) + (queue_length_avg * weight2) - (active_connections_avg * weight3)
We want to increase min_limit for classes with high score (meaning they are having trouble) and decrease for those with low score.
But we must keep sum(min_limit) <= total_max_connections.
We can do:
total_min = sum(min_limits)
For each class, we compute a desired_min_limit:
desired_min_limit[C] = min_limit[C] * (1 + adjustment_factor * (score[C] - avg_score))
Then we normalize so that sum(desired_min_limit) = total_min (or maybe we allow sum(desired_min_limit) to be up to total_max_connections?).
Then we set min_limit[C] = desired_min_limit[C] (rounded to integer).
And then we set max_limit[C] = min_limit[C] + spillover_buffer (which could be a fixed number or a fraction of min_limit).
But note: if we increase min_limit for one class, we have to decrease for others because sum(min_limit) cannot exceed total_max_connections? Actually, we can set sum(min_limit) to be less than total_max_connections, and then the remaining connections are available for spillover (i.e., for any class up to max_limit). But then the max_limit might be above min_limit, and the sum of max_limits might be above total_max_connections.
So we can set:
total_min = sum(min_limits) <= total_max_connections
Then the spillover capacity is total_max_connections - total_min, and we distribute that as extra to classes? Or we set max_limit[C] = min_limit[C] + spillover_share[C] where sum(spillover_share) = total_max_connections - total_min.
But then we are guaranteeing that each class gets at least min_limit, and then the remaining connections are shared according to max_limit? Not exactly, because the assignment algorithm will assign to the highest priority class that is below max_limit, regardless of min_limit.
Alternatively, we can set:
We adjust min_limits and max_limits independently, but we must have:
sum(min_limits) <= total_max_connections
and for each class: min_limit[C] <= max_limit[C]
And then in the assignment algorithm, we only enforce max_limit.
Then the min_limit is just a target for adaptation? We don't enforce it in the assignment algorithm? Then why have it?
We want to guarantee that a class gets at least min_limit connections when the pool is fully utilized? But we don't have a mechanism to take from one class to give to another. So if a class is above min_limit, it doesn't give up connections to a class below min_limit.
Therefore, the min_limit is not a guarantee. It's just a target for adaptation.
So maybe we don't need min_limit and max_limit. We can just have one adaptive limit per class, and we adjust it based on demand, and we enforce that limit (with spillover allowed?).
Let's simplify:
Each class has an adaptive limit L[C] (which is the soft limit we adjust).
We also have a global total_max_connections N.
We assign a connection to class C if:
active[C] < L[C] and total_active < N -> assign immediately? But we want to prioritize.
But then we have the same problem: if we assign immediately, we might assign to a low priority class even if a high priority class is waiting.
So we go back to the queuing mechanism.
Let's define:
Each class has:
- adaptive_limit (the soft limit, which we adjust)
- priority (fixed)
We have a global pool of N connections.
We maintain:
- active[C] for each class
- queue[C] for each class (waiting requests)
When a request comes for class C:
if active[C] < adaptive_limit[C] and there is an idle connection:
assign immediately? But then we are not using the priority.
We want to prioritize, so we don't assign immediately. We always queue and then the assignment algorithm (when a connection is released or when there are idle connections) will assign to the highest priority class that is below its adaptive_limit and has waiting requests.
But then what is the adaptive_limit for? It's the limit that we try to enforce for the class. If a class is above its adaptive_limit, we don't assign more connections to it even if there are idle connections? But then we might have idle connections and a class above adaptive_limit waiting? Actually, if a class is above adaptive_limit, we don't put it in the candidate set for assignment.
So:
Assignment algorithm:
while idle_connections > 0 and there exists a class C with queue[C] not empty and active[C] < adaptive_limit[C]:
pick the class with the highest priority (and if tie, the one with the oldest first request in the queue).
assign.
Then a class can only get a connection if it is below its adaptive_limit.
But then what about spillover? We want to allow a class to exceed its adaptive_limit if there are idle connections and no other class is waiting? But then we are not giving priority to other classes.
We can change:
We allow a class to exceed its adaptive_limit only if:
- active[C] < (adaptive_limit[C] + spillover_buffer) [so we have a hard limit that is adaptive_limit + spillover_buffer]
- and there are no classes with higher priority that are below their adaptive_limit and have waiting requests.
But then we are mixing two conditions.
Alternatively, we can have:
We have two sets of limits:
adaptive_limit: the normal limit, below which the class gets priority.
spillover_limit: the maximum the class can ever reach (adaptive_limit + spillover_buffer).
And we adjust adaptive_limit based on demand.
Assignment algorithm:
while idle_connections > 0:
candidate_classes = []
# First, try to assign to classes that are below their adaptive_limit (with priority)
for each class C with queue[C] not empty and active[C] < adaptive_limit[C]:
candidate_classes.append(C)
if candidate_classes:
choose the one with highest priority (and if tie, the one with the oldest first request)
assign.
else:
# Then, try to assign to classes that are below their spillover_limit and have waiting requests.
for each class C with queue[C] not empty and active[C] < spillover_limit[C]:
candidate_classes.append(C)
if candidate_classes:
choose the one with highest priority (and if tie, the one with the oldest first request)
assign.
else:
break # no more assignments
This way, we first try to satisfy the adaptive limits (the preferred allocation) and then if no one is below adaptive_limit, we allow spillover.
Then we adjust adaptive_limit based on:
For each class, we look at:
- If the class has a non-empty queue for a significant portion of time, we want to increase its adaptive_limit.
- If the class rarely uses its adaptive_limit, we want to decrease it.
But note: we also have priority. We might want to adjust adaptive_limit keeping in mind the priority? For example, a high priority class should have a higher adaptive_limit.
We can set:
Initial adaptive_limit[C] = (priority[C] / total_priority) * total_max_connections
Then we adjust:
Let demand[C] = average active[C] over the last period + average queue length[C]?
Then we want adaptive_limit[C] to be proportional to demand[C]? But we also want to respect priority.
We can do:
desired_adaptive_limit[C] = (priority[C] / total_priority) * total_max_connections * (1 + adjustment_factor * (demand[C] - avg_demand))
Then we normalize so that sum(desired_adaptive_limit) <= total_max_connections.
But note: we also have spillover_buffer. We can set spillover_buffer as a fixed number (say 10% of adaptive_limit) or as a fixed number per class.
Then spillover_limit[C] = adaptive_limit[C] + spillover_buffer[C]
And we adjust spillover_buffer? Probably not, we keep it fixed or adjust slowly.
Also, we must ensure that adaptive_limit[C] <= spillover_limit[C] and spillover_limit[C] <= total_max_connections? Not necessarily, because we cannot exceed total_max_connections.
Actually, we cannot have adaptive_limit[C] > total_max_connections. And spillover_limit[C] should be at most total_max_connections.
Observability:
We expose:
- For each class:
active_connections
queue_length
adaptive_limit
spillover_limit
wait_time (average, maybe percentiles)
rejected_requests? (if we reject when queue is full? we don't have a queue limit? we might need to set a max queue length per class to avoid memory issues)
We also expose:
total_active_connections
total_idle_connections
total_queued_requests
And we can expose the adjustment history.
Implementation:
We'll use:
PriorityClass:
name: str
priority: int
adaptive_limit: int
spillover_buffer: int # or we can compute spillover_limit directly
spillover_limit: int # = adaptive_limit + spillover_buffer
queue: collections.deque of (request_id, timestamp) # we keep the request and the time it arrived
ConnectionPool:
total_max_connections: int
priority_classes: dict[name -> PriorityClass]
idle_connections: set of connection_ids # or just a count? we need to assign a connection to a request, so we need to know which connection.
We also need to track:
active_connections: dict[name -> count] # we can get from PriorityClass? but we need to update when we assign and release.
But note: when we assign a connection to a class, we need to know which connection (from the idle pool) and then when the class releases, we return that connection to the idle pool.
We'll have:
connections: a set of all connection objects (or ids) that we manage.
assignment: dict[connection_id -> class_name] # so we know which class is using which connection.
Steps for assignment:
When we assign a connection to a class C:
connection = idle_connections.pop()
assignment[connection] = C
active_connections[C] += 1 # we can also get from PriorityClass, but we need to update the PriorityClass.
When a connection is released (by the client of class C):
connection = ... (we get from the client)
class_name = assignment[connection]
del assignment[connection]
active_connections[class_name] -= 1
idle_connections.add(connection)
Then run assignment algorithm.
But note: the request is queued in class C. When we assign, we pop the first request from queue[C] and then assign the connection to that request.
We need to track which request is using which connection? Not necessarily. We just need to know that when a request gets a connection, we remove it from the queue and assign the connection to that request.
We can have:
Request:
id
class_name
timestamp
And when we assign, we return the connection to the request.
But the pooler doesn't care about the request id. We just have a queue of requests (with timestamp) per class.
So:
PriorityClass has:
queue: deque of timestamps (or we can store the request object if we need more info)
When we assign, we pop the leftmost timestamp (which is the oldest) and then we assign a connection to that request.
We don't need to keep the request after assignment.
Adaptive adjustment:
We run a background thread that every, say, 5 minutes:
For each class, compute:
avg_active = average active_connections[C] over the last period (we need to sample or keep a moving average)
avg_queue = average queue length[C] over the last period.
Then we compute a demand score:
score[C] = avg_queue * alpha + avg_active * beta # we want to increase limit if queue is long or if active is high? But if active is high, it means the class is using a lot, so we might want to increase limit? But if active is high and queue is low, then the class is using its limit and not having trouble? Actually, if active is high and queue is low, then the class is getting connections and not waiting. So we might not want to increase.
Alternatively, we can use:
score[C] = avg_queue # because if queue is long, we need more connections.
But if a class has a high queue, it might be because its limit is too low. But if its priority is low, we might not want to increase it.
So we adjust based on priority:
desired_adaptive_limit[C] = (priority[C] / total_priority) * total_max_connections * (1 + adjustment_factor * (score[C] - avg_score))
Where avg_score = average of score over all classes.
Then we set:
new_adaptive_limit[C] = desired_adaptive_limit[C] (rounded to integer)
And then we adjust so that sum(new_adaptive_limit) <= total_max_connections.
We can do:
total_desired = sum(desired_adaptive_limit)
if total_desired > total_max_connections:
scale_factor = total_max_connections / total_desired
for each class:
new_adaptive_limit[C] = int(desired_adaptive_limit[C] * scale_factor)
Then set adaptive_limit[C] = new_adaptive_limit[C]
And then set spillover_limit[C] = adaptive_limit[C] + spillover_buffer[C]
But note: we might want to set a minimum adaptive_limit (at least 1) and maximum (at most total_max_connections).
Spillover handling:
In the assignment algorithm, we first try classes with active[C] < adaptive_limit[C]. Then if none, we try with active[C] < spillover_limit[C].
This is the spillover handling: we allow the class to exceed its adaptive_limit (up to spillover_limit) if there are idle connections and no other class (with higher priority) is waiting and below adaptive_limit.
Rejection:
We might want to set a maximum queue length per class. If the queue for a class is full, then we reject the request.
We can have:
max_queue_length per class (maybe based on priority? or fixed).
Then when a request comes and the queue for that class is already at max_queue_length, we reject.
Instrumentation:
We track:
For each class:
- current adaptive_limit
- current spillover_limit
- active_connections
- queue_length
- wait_time: we can compute average wait time for completed requests? or current wait time for the first in queue?
We also track:
total_active_connections
total_idle_connections
total_queued_requests
We can expose these as metrics.
Also, we want to log when a class exceeds its adaptive_limit (spillover event) and when we adjust limits.
Observability:
We expose metrics in Prometheus format.
We also provide a way to get the current configuration (adaptive_limits, spillover_limits) and the current state (active, queues).
We might also want to expose historical data for the adaptive adjustment.
Configurability:
We need to configure:
total_max_connections
priority_classes: list of dict with:
name
priority
initial_adaptive_limit (or we compute from priority)
spillover_buffer (or we set a global spillover_buffer)
max_queue_length
adaptive_adjustment_interval (in seconds)
adaptive_adjustment_parameters (alpha, beta, adjustment_factor)
Summary:
We have:
PriorityClass:
name
priority
adaptive_limit
spillover_buffer
spillover_limit (computed)
queue (deque of request timestamps)
max_queue_length
ConnectionPool:
total_max_connections
priority_classes: dict
idle_connections: set of connection_ids
assignment: dict[connection_id -> class_name]
active_connections: dict[name -> int] (or we can get from PriorityClass? but we need to update when assign/release)
We also have:
total_idle_connections = len(idle_connections)
Assignment algorithm:
def assign_connection():
while idle_connections and there exists a class with queue not empty and active[class] < spillover_limit[class]:
candidate_classes = [C for C in priority_classes if queue[C] and active[C] < spillover_limit[C]]
if not candidate_classes: break
# First, filter by adaptive_limit
preferred = [C for C in candidate_classes if active[C] < adaptive_limit[C]]
if preferred:
# choose the one with highest priority, and if tie, the one with the oldest first request
chosen = max(preferred, key=lambda C: (C.priority, -queue[C][0])) # assuming we store timestamps and older is smaller
else:
# then choose from all candidate_classes (which are below spillover_limit) by priority and age
chosen = max(candidate_classes, key=lambda C: (C.priority, -queue[C][0]))
# assign a connection to chosen
connection = idle_connections.pop()
assignment[connection] = chosen.name
active_connections[chosen.name] += 1
# remove the first request from chosen.queue
chosen.queue.popleft()
Request handling:
def request_connection(class_name):
C = priority_classes[class_name]
if len(C.queue) >= C.max_queue_length:
reject_request()
return
C.queue.append(timestamp) # or request_id, timestamp
# try to assign immediately? No, we run assign_connection (which will use idle connections if available)
assign_connection()
Connection release:
def release_connection(connection_id):
class_name = assignment[connection_id]
del assignment[connection_id]
active_connections[class_name] -= 1
idle_connections.add(connection_id)
assign_connection()
Adaptive adjustment:
def adjust_limits():
# compute scores for each class
# we need to have recorded metrics for the last period (say 5 minutes). We can store:
# for each class: a list of active_connections samples and queue_length samples? or we can compute moving averages.
# Let's assume we have:
# metrics[class_name] = {
# 'active_samples': list of (timestamp, active_count),
# 'queue_samples': list of (timestamp, queue_length)
# }
# We compute average over the last period.
# Then compute score[C] = avg_queue[C] # or we can use a combination.
# Then compute desired_adaptive_limit as above.
# Then normalize to sum <= total_max_connections.
# Then set adaptive_limit[C] = new_value.
# Then set spillover_limit[C] = adaptive_limit[C] + spillover_buffer[C]
# Log the adjustment.
We also need to handle the case when we adjust limits downward, and there are active connections above the new adaptive_limit? That's okay because we don't force release. The active connections can stay until the client releases. But new requests will be limited by the new adaptive_limit.
This is a complex design. We'll implement a simplified version for the purpose of this exercise.
We'll assume:
- We have a fixed set of connections (ids from 1 to total_max_connections).
- We don't have actual queries, just requests for connections.
We'll implement in Python (pseudo-code) with the main components.
Let's code:
PriorityClass:
__init__(self, name, priority, initial_adaptive_limit, spillover_buffer, max_queue_length)
ConnectionPool:
__init__(self, total_max_connections, priority_classes_config)
# We create PriorityClass objects.
# Initialize:
# idle_connections = set(range(1, total_max_connections+1))
# assignment = {}
# active_connections = {name: 0 for name in priority_classes}
# We also start a background thread for adaptive adjustment.
We'll also have:
metrics: for each class, we record:
- active_connections over time (we sample every minute? or every time we assign/release? we can sample periodically)
- queue_length over time
For simplicity, we might record:
For each class:
active_history: list of (timestamp, active_count)
queue_history: list of (timestamp, queue_length)
But then we have to store a lot of data. Alternatively, we can compute moving averages with a time window.
We can do:
For each class, we keep:
active_sum: sum of active counts over the last N samples? or over the last period.
queue_sum: sum of queue lengths over the last period.
last_sample_time: when we last sampled.
We sample every, say, 10 seconds. Then for the last 5 minutes, we have 30 samples.
We can have a background thread that every 10 seconds records the current active and queue for each class.
Then when adjusting, we take the average over the last 30 samples.
We'll implement:
ConnectionPool:
def sample_metrics(self):
for each class:
active = self.active_connections[class.name]
queue = len(class.queue)
current_time = time.time()
class.active_history.append((current_time, active))
class.queue_history.append((current_time, queue))
# remove old samples (older than adjustment_interval)
Then in adjust_limits, we compute:
avg_active = average of active in the last adjustment_interval
avg_queue = average of queue in the last adjustment_interval
score = avg_queue # we can use only queue, because if queue is long, we need more connections.
total_priority = sum(C.priority for C in self.priority_classes)
desired = {}
for C in self.priority_classes:
desired[C.name] = (C.priority / total_priority) * self.total_max_connections * (1 + self.adjustment_factor * (score[C.name] - avg_score))
Then normalize.
But note: we have to compute avg_score = average of score over all classes.
This is a basic design. There are many variations and improvements.
Given the complexity, we might want to start with a simpler version:
- Fixed limits and no adaptive adjustment, just priority queuing.
- Then add adaptive adjustment.
But the problem asks for workload-aware with adaptive limits.
We'll provide the design as above.
Let's write the code structure.
We'll write in Python, but note that this is a design and might not be production-ready.
We assume we are using asyncio? or threads? We'll do a thread-safe version.
We'll use:
threading.Lock for the pool.
Steps:
class PriorityClass:
def __init__(self, name, priority, initial_adaptive_limit, spillover_buffer, max_queue_length):
self.name = name
self.priority = priority
self.adaptive_limit = initial_adaptive_limit
self.spillover_buffer = spillover_buffer
self.spillover_limit = initial_adaptive_limit + spillover_buffer
self.queue = deque()
self.max_queue_length = max_queue_length
# metrics
self.active_history = [] # list of (timestamp, active_count)
self.queue_history = [] # list of (timestamp, queue_length)
class ConnectionPool:
def __init__(self, total_max_connections, priority_classes_config, adjustment_interval=300, adjustment_factor=0.1):
self.total_max_connections = total_max_connections
self.priority_classes = {}
for config in priority_classes_config:
pc = PriorityClass(
name=config['name'],
priority=config['priority'],
initial_adaptive_limit=config.get('initial_adaptive_limit', (config['priority'] / sum(c['priority'] for c in priority_classes_config)) * total_max_connections),
spillover_buffer=config.get('spillover_buffer', 10), # default 10
max_queue_length=config.get('max_queue_length', 100)
)
self.priority_classes[pc.name] = pc
self.idle_connections = set(range(1, total_max_connections+1))
self.assignment = {} # connection_id -> class_name
self.active_connections = {name: 0 for name in self.priority_classes}
self.lock = threading.Lock()
# adaptive adjustment
self.adjustment_interval = adjustment_interval
self.adjustment_factor = adjustment_factor
self.last_adjustment = time.time()
self.sampled_metrics = {name: {'active': [], 'queue': []} for name in self.priority_classes}
# we will sample every, say, 10 seconds and keep the last 5 minutes (30 samples)
# start background thread for sampling and adjustment
def sample_metrics(self):
with self.lock:
current_time = time.time()
for name, pc in self.priority_classes.items():
active = self.active_connections[name]
queue = len(pc.queue)
pc.active_history.append((current_time, active))
pc.queue_history.append((current_time, queue))
# remove old samples (older than 5 minutes)
cutoff = current_time - 300
pc.active_history = [t for t in pc.active_history if t[0] >= cutoff]
pc.queue_history = [t for t in pc.queue_history if t[0] >= cutoff]
def adjust_limits(self):
with self.lock:
current_time = time.time()
if current_time - self.last_adjustment < self.adjustment_interval:
return
# Compute average active and queue for each class over the last 5 minutes (from history)
# But note: we have been sampling every 10 seconds, so we have about 30 samples.
# If we don't have enough samples, we skip.
for name, pc in self.priority_classes.items():
if len(pc.active_history) < 5: # need at least 5 samples
return
# Compute average queue for each class
avg_queue = {}
for name, pc in self.priority_classes.items():
avg_queue[name] = sum(q for _, q in pc.queue_history) / len(pc.queue_history)
avg_score = sum(avg_queue.values()) / len(avg_queue)
total_priority = sum(pc.priority for pc in self.priority_classes.values())
desired_adaptive = {}
for name, pc in self.priority_classes.items():
desired_adaptive[name] = (pc.priority / total_priority) * self.total_max_connections * (1 + self.adjustment_factor * (avg_queue[name] - avg_score))
# Normalize so that sum(desired_adaptive) <= total_max_connections
total_desired = sum(desired_adaptive.values())
if total_desired > self.total_max_connections:
scale = self.total_max_connections / total_desired
for name in desired_adaptive:
desired_adaptive[name] = desired_adaptive[name] * scale
# Round to integers and set new adaptive_limits
for name, pc in self.priority_classes.items():
new_adaptive = int(desired_adaptive[name])
# Ensure at least 1 and at most total_max_connections
new_adaptive = max(1, min(new_adaptive, self.total_max_connections))
pc.adaptive_limit = new_adaptive
pc.spillover_limit = new_adaptive + pc.spillover_buffer
# Ensure spillover_limit does not exceed total_max_connections? Not necessary because we check in assignment.
self.last_adjustment = current_time
self.log_adjustment(desired_adaptive, avg_queue)
def log_adjustment(self, desired_adaptive, avg_queue):
# log the adjustment
for name, pc in self.priority_classes.items():
print(f"Class {name}: adaptive_limit set to {pc.adaptive_limit} (desired: {desired_adaptive[name]:.2f}), avg_queue: {avg_queue[name]:.2f}")
def assign_connection(self):
while self.idle_connections:
candidate_classes = []
for name, pc in self.priority_classes.items():
if len(pc.queue) > 0 and self.active_connections[name] < pc.spillover_limit:
candidate_classes.append(pc)
if not candidate_classes:
break
# First, try classes below adaptive_limit
preferred = [pc for pc in candidate_classes if self.active_connections[pc.name] < pc.adaptive_limit]
if preferred:
# sort by priority (descending) and then by the timestamp of the first request (ascending)
preferred.sort(key=lambda pc: (-pc.priority, pc.queue[0]))
chosen = preferred[0]
else:
candidate_classes.sort(key=lambda pc: (-pc.priority, pc.queue[0]))
chosen = candidate_classes[0]
# assign
connection = self.idle_connections.pop()
self.assignment[connection] = chosen.name
self.active_connections[chosen.name] += 1
chosen.queue.popleft() # remove the first request
def request_connection(self, class_name):
with self.lock:
pc = self.priority_classes[class_name]
if len(pc.queue) >= pc.max_queue_length:
# reject
return None # or raise exception
pc.queue.append(time.time()) # store the request time
# try to assign
self.assign_connection()
# if the request was assigned immediately, then it's not in the queue anymore.
# but we don't return the connection immediately? Actually, we are just queuing the request.
# We need to return the connection to the caller? In a real pool, we would block until we get a connection.
# In this design, we are simulating: the request_connection method returns a connection if available, otherwise it queues and returns None? But then the caller has to wait?
# We need to change: the request_connection should block until a connection is assigned, or return a connection if available.
# We can do:
# We return a connection if we can assign one immediately? But then we might assign and then the caller gets it.
# Actually, in a connection pool, the caller asks for a connection and blocks until one is available (or timeout).
# So we need to have a condition variable per class? or a global one?
# We can do:
# When we assign, we remove the request from the queue and then we signal that the request has been fulfilled.
# But then the request_connection method must wait until its request is at the head of the queue and then get a connection.
# Alternatively, we can have:
# request_connection returns a connection object (or None if rejected). But then we have to wait.
# We'll change the design: the request_connection method is called by a thread and it will block until a connection is assigned to it.
# We can use a condition variable for each class? or one for the whole pool.
# Given the complexity, let's assume we have a method that blocks:
# def get_connection(self, class_name, timeout=None):
# with self.lock:
# # if we can assign immediately (there is an idle connection and the class is below adaptive_limit or spillover_limit and the class has no queue? actually, we are queuing)
# # But note: we are queuing, so we add to the queue and then wait until we are assigned.
# We need a way to wait for a connection for a specific request.
# We can store in the queue: (timestamp, condition_variable) for each request.
# Then when we assign, we pop the first request and notify its condition.
# This is getting complex.
# Given the scope, we'll assume that the request_connection method is non-blocking and returns a connection if available, otherwise queues and returns None? But then the caller has to retry? That's not typical.
# Alternatively, we can have:
# The request_connection method returns a Future? or we use callbacks.
# Since this is a design, we'll leave the blocking mechanism as an exercise.
# For now, we'll just queue and then the assignment algorithm will assign when a connection is available.
# But then the caller doesn't get the connection until we assign? We need to return the connection to the caller.
# We change:
# In request_connection, we add the request to the queue and then call assign_connection. If assign_connection assigns a connection, then we remove the request from the queue and return the connection? But then we are assigning to the first request in the queue, which might not be the current request if there are multiple.
# So we need to wait until our request is at the head and then we get the connection.
# We can do:
# with self.lock:
# if we can assign a connection to this class (active[class] < spillover_limit and there is an idle connection) and there is no queue for this class? But we just added to the queue.
# Actually, the assignment algorithm runs after we add to the queue, so it might assign to our request if we are the only one and conditions are met.
# But then we need to wait until the assignment algorithm assigns to our request? How do we know?
# We can have a condition variable per class. When we add to the queue, we wait on the class's condition. When the assignment algorithm assigns a connection to that class, it notifies all waiting threads for that class? But then only the first in the queue gets the connection.
# We can do:
# In request_connection:
# with self.lock:
# if len(pc.queue) >= pc.max_queue_length: reject
# my_request = (time.time(), threading.Condition(self.lock)) # but we cannot have a condition per request? We can have one condition per class.
# Actually, we can have:
# pc.condition = threading.Condition(self.lock)
# Then in request_connection:
# with pc.condition:
# while True:
# if we can get a connection immediately (without queue? but we are in the queue now) - we are already in the queue.
# We wait until we are at the head and there is an idle connection and we are below spillover_limit.
# This is complex and beyond the scope.
# Given the time, we'll assume that the request_connection method is called and it returns a connection if available, otherwise it returns None and the caller will retry later? That's not ideal.
# Alternatively, we can design the pool to be used with callbacks or futures.
# Since this is a design, we'll leave the blocking/waiting mechanism as an implementation detail.
# For the purpose of this exercise, we'll just queue and then the assignment algorithm will assign when possible, and we assume that the caller will check back or we have a separate mechanism to deliver the connection.
# We'll change the request_connection to:
# It returns a connection if one is available immediately (without queueing) and if not, it queues and returns None? Then the caller must try again.
# But then we are not using the queue? We are queuing but not waiting.
# Let's stick to the queuing mechanism and assume that the pool is used in an asynchronous way.
# We'll provide:
# async def get_connection(self, class_name):
# # similar but with async/await
# Given the complexity, we'll stop here and assume that the queuing and assignment algorithm is the core.
We also need to handle connection release:
def release_connection(self, connection):
with self.lock:
if connection not in self.assignment:
raise Exception("Connection not assigned")
class_name = self.assignment[connection]
del self.assignment[connection]
self.active_connections[class_name] -= 1
self.idle_connections.add(connection)
self.assign_connection()
And we need to start the sampling and adjustment thread.
This is a very high-level design and there are many edge cases.
Given the constraints, we provide the design and the code structure.
Note: This is not production code and has not been tested.
We might want to:
- Use a priority queue for the waiting requests? But we have per-class queues and then we choose the class by priority and then FIFO within the class.
- We might want to have a global queue with priority? But then we lose per-class limits? We can have a global queue where each request has a class and we only assign if the class is below its limit.
- The current design uses per-class queues and then chooses the class with the highest priority that has waiting requests and is below spillover_limit.
This design should work for the requirements.
Let me know if you have any questions.</think>
"""
Workload-aware database connection pooler with:
- Priority classes (e.g., OLTP, Analytics, Admin)
- Adaptive connection limits based on real-time workload
- Spillover handling with borrowing and queuing
- Comprehensive observability and instrumentation
"""
import asyncio
import time
import logging
from collections import defaultdict, deque
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple, Deque
from enum import Enum
import statistics
from prometheus_client import Counter, Gauge, Histogram, Summary
# ============== TYPES AND ENUMS ==============
class PriorityClass(Enum):
"""Connection priority classes"""
CRITICAL = 100 # Admin/migrations (highest priority)
INTERACTIVE = 70 # User-facing OLTP queries
BACKGROUND = 40 # Reports, batch jobs
ANALYTICS = 20 # Long-running analytical queries
BEST_EFFORT = 10 # Low-priority maintenance
@dataclass
class ClassConfig:
"""Configuration for a priority class"""
priority: PriorityClass
min_connections: int = 1
max_connections: int = 10
target_utilization: float = 0.7 # Target utilization (0.0-1.0)
queue_timeout: float = 5.0 # Seconds
max_queue_size: int = 100
borrow_from: List[PriorityClass] = field(default_factory=list) # Allowed source classes for borrowing
spillover_threshold: float = 0.9 # When to consider spillover (utilization > threshold)
# ============== INSTRUMENTATION ==============
class ConnectionMetrics:
"""Centralized metrics collection"""
def __init__(self):
# Prometheus metrics
self.connections_active = Gauge(
'pool_connections_active',
'Active connections by priority class',
['priority_class']
)
self.connections_available = Gauge(
'pool_connections_available',
'Available connections by priority class',
['priority_class']
)
self.queue_size = Gauge(
'pool_queue_size',
'Queue size by priority class',
['priority_class']
)
self.wait_time = Histogram(
'pool_wait_time_seconds',
'Connection wait time',
['priority_class'],
buckets=(0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0, 30.0)
)
self.spillover_events = Counter(
'pool_spillover_total',
'Spillover events by source and target class',
['source_class', 'target_class']
)
self.borrow_events = Counter(
'pool_borrow_total',
'Connection borrow events',
['source_class', 'target_class']
)
self.rejection_events = Counter(
'pool_rejection_total',
'Connection request rejections',
['priority_class', 'reason']
)
self.limit_adjustments = Counter(
'pool_limit_adjustments_total',
'Adaptive limit adjustments',
['priority_class', 'direction']
)
self.system_load = Gauge(
'pool_system_load',
'System load indicator (0-1)',
['metric']
)
# Internal tracking
self.wait_times: Dict[PriorityClass, List[float]] = defaultdict(list)
self.limit_history: Dict[PriorityClass, List[Tuple[float, int]]] = defaultdict(list)
self.spillover_history: List[Dict] = []
# ============== CONNECTION POOL CORE ==============
class ConnectionPool:
"""Workload-aware connection pool with priority classes"""
def __init__(
self,
total_max_connections: int,
class_configs: Dict[PriorityClass, ClassConfig],
system_monitor=None,
metrics: Optional[ConnectionMetrics] = None
):
self.total_max_connections = total_max_connections
self.class_configs = class_configs
self.metrics = metrics or ConnectionMetrics()
self.system_monitor = system_monitor
# Connection tracking
self._available: Dict[PriorityClass, Deque[int]] = {
pc: deque(maxlen=cfg.max_connections)
for pc, cfg in class_configs.items()
}
self._in_use: Dict[PriorityClass, Set[int]] = {
pc: set() for pc in class_configs
}
self._queues: Dict[PriorityClass, Deque[Tuple[float, asyncio.Future]]] = {
pc: deque() for pc in class_configs
}
self._borrowed: Dict[int, Tuple[int, PriorityClass, float]] = {} # conn_id -> (original_class, current_class, borrow_time)
# Adaptive control
self._current_limits: Dict[PriorityClass, int] = {
pc: cfg.min_connections for pc, cfg in class_configs.items()
}
self._load_window: Deque[Dict] = deque(maxlen=60) # 60 samples of load data
self._adaptive_lock = asyncio.Lock()
self._last_adjustment = time.time()
# Initialize connections
self._connection_counter = 0
self._initialize_connections()
# Start background tasks
self._monitor_task: Optional[asyncio.Task] = None
self._shutdown = False
def _initialize_connections(self):
"""Initialize connections according to minimum requirements"""
total_allocated = 0
for pc, cfg in self.class_configs.items():
for _ in range(cfg.min_connections):
if total_allocated < self.total_max_connections:
conn_id = self._create_connection(pc)
self._available[pc].append(conn_id)
total_allocated += 1
def _create_connection(self, priority_class: PriorityClass) -> int:
"""Create a new connection (simulated)"""
self._connection_counter += 1
conn_id = self._connection_counter
# In reality, this would create actual DB connection
return conn_id
async def get_connection(self, priority_class: PriorityClass) -> int:
"""Get a connection for the given priority class"""
start_time = time.time()
cfg = self.class_configs[priority_class]
async with self._adaptive_lock:
# Fast path: check if we can satisfy immediately
if self._available[priority_class]:
conn_id = self._available[priority_class].popleft()
self._in_use[priority_class].add(conn_id)
self._update_metrics()
return conn_id
# Check if we can borrow from other classes
borrowed_conn = await self._try_borrow(priority_class)
if borrowed_conn:
return borrowed_conn
# Need to queue
if len(self._queues[priority_class]) >= cfg.max_queue_size:
self.metrics.rejection_events.labels(
priority_class=priority_class.name,
reason='queue_full'
).inc()
raise ConnectionError(f"Queue full for {priority_class.name}")
# Create future and queue
future = asyncio.Future()
self._queues[priority_class].append((start_time, future))
self.metrics.queue_size.labels(priority_class=priority_class.name).set(
len(self._queues[priority_class])
)
try:
# Wait for connection with timeout
conn_id = await asyncio.wait_for(future, timeout=cfg.queue_timeout)
self._in_use[priority_class].add(conn_id)
wait_time = time.time() - start_time
self.metrics.wait_time.labels(priority_class=priority_class.name).observe(wait_time)
self.metrics.wait_times[priority_class].append(wait_time)
return conn_id
except asyncio.TimeoutError:
# Remove from queue
self._queues[priority_class].remove((start_time, future))
self.metrics.queue_size.labels(priority_class=priority_class.name).set(
len(self._queues[priority_class])
)
self.metrics.rejection_events.labels(
priority_class=priority_class.name,
reason='timeout'
).inc()
raise ConnectionError(f"Connection timeout for {priority_class.name}")
async def _try_borrow(self, target_class: PriorityClass) -> Optional[int]:
"""Try to borrow a connection from lower priority classes"""
cfg = self.class_configs[target_class]
# Check allowed source classes
allowed_sources = cfg.borrow_from or [
pc for pc in PriorityClass
if pc.value < target_class.value
]
for source_class in sorted(allowed_sources, key=lambda x: x.value, reverse=True):
source_cfg = self.class_configs[source_class]
# Only borrow if source has excess capacity
source_excess = len(self._in_use[source_class]) - source_cfg.min_connections
if source_excess > 0 and self._available[source_class]:
conn_id = self._available[source_class].popleft()
self._in_use[target_class].add(conn_id)
self._borrowed[conn_id] = (source_class, target_class, time.time())
self.metrics.borrow_events.labels(
source_class=source_class.name,
target_class=target_class.name
).inc()
self.metrics.spillover_events.labels(
source_class=source_class.name,
target_class=target_class.name
).inc()
logging.info(
f"Borrowed connection {conn_id} from {source_class.name} "
f"to {target_class.name}"
)
return conn_id
return None
def release_connection(self, conn_id: int):
"""Release a connection back to the pool"""
# Find which class owns this connection
owner_class = None
borrowed_info = None
for pc in self.class_configs:
if conn_id in self._in_use[pc]:
owner_class = pc
break
if not owner_class:
# Check borrowed connections
if conn_id in self._borrowed:
borrowed_info = self._borrowed.pop(conn_id)
owner_class = borrowed_info[1] # Current class
else:
logging.warning(f"Released unknown connection {conn_id}")
return
# Remove from in_use
self._in_use[owner_class].remove(conn_id)
# If borrowed, return to original class
if borrowed_info:
original_class = borrowed_info[0]
self._available[original_class].append(conn_id)
else:
self._available[owner_class].append(conn_id)
# Try to satisfy queued requests
self._fulfill_queues()
self._update_metrics()
def _fulfill_queues(self):
"""Fulfill queued connection requests based on priority"""
# Get all classes with queued requests
queued_classes = [
(pc, len(queue))
for pc, queue in self._queues.items()
if queue
]
# Sort by priority (highest first)
queued_classes.sort(key=lambda x: self.class_configs[x[0]].priority.value, reverse=True)
for pc, _ in queued_classes:
cfg = self.class_configs[pc]
queue = self._queues[pc]
while queue and self._available[pc]:
start_time, future = queue[0] # Peek at oldest request
# Check if we can fulfill
if len(self._in_use[pc]) < self._current_limits[pc]:
# Fulfill this request
queue.popleft()
conn_id = self._available[pc].popleft()
self._in_use[pc].add(conn_id)
future.set_result(conn_id)
wait_time = time.time() - start_time
self.metrics.wait_time.labels(priority_class=pc.name).observe(wait_time)
self.metrics.wait_times[pc].append(wait_time)
else:
break # Cannot fulfill more for this class
def _update_metrics(self):
"""Update all metrics"""
for pc in self.class_configs:
self.metrics.connections_active.labels(
priority_class=pc.name
).set(len(self._in_use[pc]))
self.metrics.connections_available.labels(
priority_class=pc.name
).set(len(self._available[pc]))
self.metrics.queue_size.labels(
priority_class=pc.name
).set(len(self._queues[pc]))
# ============== ADAPTIVE LIMITS ==============
async def _adaptive_control_loop(self, interval: float = 10.0):
"""Background task for adaptive limit adjustment"""
while not self._shutdown:
await asyncio.sleep(interval)
async with self._adaptive_lock:
await self._collect_system_load()
await self._adjust_limits()
self._cleanup_old_metrics()
async def _collect_system_load(self):
"""Collect system and database load metrics"""
if self.system_monitor:
load = await self.system_monitor.get_load()
self._load_window.append(load)
# Update metrics
for metric_name, value in load.items():
self.metrics.system_load.labels(metric=metric_name).set(value)
async def _adjust_limits(self):
"""Adjust connection limits based on workload"""
current_time = time.time()
# Only adjust periodically (every 5 minutes)
if current_time - self._last_adjustment < 300:
return
if len(self._load_window) < 10: # Need enough samples
return
# Calculate utilization for each class
utilizations = {}
for pc in self.class_configs:
total_possible = self._current_limits[pc] + len(self._available[pc])
if total_possible > 0:
util = len(self._in_use[pc]) / total_possible
else:
util = 0
utilizations[pc] = util
# Get system load indicators
avg_cpu = statistics.mean(
sample.get('cpu_percent', 0) for sample in self._load_window
) if self._load_window else 0
avg_connections = statistics.mean(
sample.get('connection_count', 0) for sample in self._load_window
) if self._load_window else 0
# Adjust limits based on multiple factors
adjustments = {}
total_current = sum(self._current_limits.values())
for pc in self.class_configs:
cfg = self.class_configs[pc]
util = utilizations[pc]
wait_time_avg = statistics.mean(self.metrics.wait_times[pc][-10:]) if self.metrics.wait_times[pc] else 0
# Adjustment factors
util_factor = 0
wait_factor = 0
priority_factor = pc.value / 100.0
# utilization-based adjustment
if util > cfg.spillover_threshold:
util_factor = 0.1 # Need more connections
elif util < cfg.target_utilization * 0.5:
util_factor = -0.1 # Too many connections
# Wait time adjustment
if wait_time_avg > cfg.queue_timeout * 0.8:
wait_factor = 0.1
elif wait_time_avg < 0.1:
wait_factor = -0.1
# System load adjustment (reduce all if system overwhelmed)
system_factor = 0
if avg_cpu > 80 or avg_connections > self.total_max_connections * 0.9:
system_factor = -0.2
# Calculate adjustment
adjustment = (util_factor + wait_factor) * priority_factor + system_factor
adjustments[pc] = adjustment
# Apply adjustments while respecting constraints
new_limits = {}
total_adjustment = 0
# First pass: calculate raw adjustments
for pc in self.class_configs:
current = self._current_limits[pc]
raw_adjustment = int(current * adjustments[pc])
new_limit = max(
self.class_configs[pc].min_connections,
min(
self.class_configs[pc].max_connections,
current + raw_adjustment
)
)
new_limits[pc] = new_limit
total_adjustment += (new_limit - current)
# Second pass: ensure total doesn't exceed max
total_new = sum(new_limits.values())
if total_new > self.total_max_connections:
# Scale down proportionally
scale = self.total_max_connections / total_new
for pc in new_limits:
new_limits[pc] = max(
self.class_configs[pc].min_connections,
int(new_limits[pc] * scale)
)
# Apply changes
for pc in self.class_configs:
old_limit = self._current_limits[pc]
new_limit = new_limits[pc]
if new_limit != old_limit:
direction = "increase" if new_limit > old_limit else "decrease"
self.metrics.limit_adjustments.labels(
priority_class=pc.name,
direction=direction
).inc()
self.metrics.limit_history[pc].append((current_time, new_limit))
self._current_limits[pc] = new_limit
logging.info(
f"Adaptive limit for {pc.name}: {old_limit} -> {new_limit} "
f"(util: {utilizations[pc]:.2%}, wait: {self.metrics.wait_times[pc][-1] if self.metrics.wait_times[pc] else 'N/A'})"
)
self._last_adjustment = current_time
def _cleanup_old_metrics(self):
"""Clean up old metric samples"""
cutoff = time.time() - 3600 # Keep 1 hour
for pc in self.class_configs:
self.metrics.wait_times[pc] = [
t for t in self.metrics.wait_times[pc]
if t > 0 # Simple cleanup (would need timestamps in real impl)
][-100:] # Keep last 100 samples
self.metrics.limit_history[pc] = [
(ts, lim) for ts, lim in self.metrics.limit_history[pc]
if ts > cutoff
]
# ============== OBSERVABILITY ==============
def get_status(self) -> Dict:
"""Get current pool status"""
status = {
'total_max': self.total_max_connections,
'total_used': sum(len(s) for s in self._in_use.values()),
'total_available': sum(len(q) for q in self._available.values()),
'total_queued': sum(len(q) for q in self._queues.values()),
'classes': {}
}
for pc in self.class_configs:
cfg = self.class_configs[pc]
current_limit = self._current_limits[pc]
in_use = len(self._in_use[pc])
available = len(self._available[pc])
queued = len(self._queues[pc])
# Calculate effective limit (including borrowed)
borrowed_in = sum(
1 for (orig, curr, _) in self._borrowed.values()
if curr == pc
)
borrowed_out = sum(
1 for (orig, curr, _) in self._borrowed.values()
if orig == pc
)
status['classes'][pc.name] = {
'config': {
'min': cfg.min_connections,
'max': cfg.max_connections,
'target_util': cfg.target_utilization,
'priority': pc.value
},
'current': {
'limit': current_limit,
'in_use': in_use,
'available': available,
'queued': queued,
'borrowed_in': borrowed_in,
'borrowed_out': borrowed_out,
'utilization': in_use / max(current_limit, 1)
},
'queue_depth': queued,
'avg_wait_time': statistics.mean(self.metrics.wait_times[pc][-10:])
if self.metrics.wait_times[pc] else 0
}
# Add system load
if self._load_window:
latest_load = self._load_window[-1]
status['system_load'] = latest_load
return status
def get_metrics(self) -> Dict:
"""Get Prometheus-style metrics"""
return {
'connections_active': {
pc.name: len(self._in_use[pc])
for pc in self.class_configs
},
'connections_available': {
pc.name: len(self._available[pc])
for pc in self.class_configs
},
'queues': {
pc.name: len(self._queues[pc])
for pc in self.class_configs
},
'limits': {
pc.name: self._current_limits[pc]
for pc in self.class_configs
}
}
# ============== LIFECYCLE ==============
async def start(self):
"""Start the pool and background tasks"""
self._monitor_task = asyncio.create_task(self._adaptive_control_loop())
logging.info("Connection pool started")
async def stop(self):
"""Gracefully shutdown the pool"""
self._shutdown = True
if self._monitor_task:
self._monitor_task.cancel()
try:
await self._monitor_task
except asyncio.CancelledError:
pass
# Close all connections
for pc_connections in self._in_use.values():
for conn_id in list(pc_connections):
self.release_connection(conn_id)
logging.info("Connection pool stopped")
# ============== SYSTEM MONITOR ==============
class SystemMonitor:
"""Monitors system and database load"""
async def get_load(self) -> Dict[str, float]:
"""Get current system load metrics"""
# In reality, this would query:
# - Database: active connections, query duration, lock waits
# - System: CPU, memory, I/O
# - Application: QPS, error rates
return {
'cpu_percent': 45.2,
'memory_percent': 62.1,
'connection_count': 150,
'avg_query_time': 0.25,
'active_transactions': 75
}
# ============== USAGE EXAMPLE ==============
async def example_usage():
"""Example of how to use the connection pool"""
# Configure priority classes
class_configs = {
PriorityClass.CRITICAL: ClassConfig(
priority=PriorityClass.CRITICAL,
min_connections=2,
max_connections=5,
target_utilization=0.6,
queue_timeout=1.0,
borrow_from=[] # Critical cannot borrow from anyone
),
PriorityClass.INTERACTIVE: ClassConfig(
priority=PriorityClass.INTERACTIVE,
min_connections=5,
max_connections=20,
target_utilization=0.7,
queue_timeout=2.0,
borrow_from=[PriorityClass.BEST_EFFORT]
),
PriorityClass.ANALYTICS: ClassConfig(
priority=PriorityClass.ANALYTICS,
min_connections=2,
max_connections=15,
target_utilization=0.8,
queue_timeout=30.0,
borrow_from=[PriorityClass.BACKGROUND, PriorityClass.BEST_EFFORT]
),
PriorityClass.BEST_EFFORT: ClassConfig(
priority=PriorityClass.BEST_EFFORT,
min_connections=1,
max_connections=10,
target_utilization=0.5,
queue_timeout=60.0
)
}
# Create pool (max 50 total connections)
pool = ConnectionPool(
total_max_connections=50,
class_configs=class_configs,
system_monitor=SystemMonitor()
)
try:
await pool.start()
# Simulate workload
async def simulate_workload():
tasks = []
# Interactive workload (high priority)
for i in range(30):
tasks.append(
asyncio.create_task(
simulate_request(pool, PriorityClass.INTERACTIVE, 0.1)
)
)
# Analytics workload (medium priority)
for i in range(20):
tasks.append(
asyncio.create_task(
simulate_request(pool, PriorityClass.ANALYTICS, 2.0)
)
)
# Best effort (low priority)
for i in range(10):
tasks.append(
asyncio.create_task(
simulate_request(pool, PriorityClass.BEST_EFFORT, 5.0)
)
)
await asyncio.gather(*tasks)
await simulate_workload()
# Print status
print("\nPool Status:")
import json
print(json.dumps(pool.get_status(), indent=2))
finally:
await pool.stop()
async def simulate_request(pool: ConnectionPool, priority: PriorityClass, hold_time: float):
"""Simulate a database request"""
try:
conn = await pool.get_connection(priority)
try:
# Simulate query execution
await asyncio.sleep(hold_time)
finally:
pool.release_connection(conn)
except ConnectionError as e:
print(f"Request failed: {e}")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(example_usage())