Develop a request prioritization engine blending SLA tiers, fairness queueing, and…
- User
Develop a request prioritization engine blending SLA tiers, fairness queueing, and admission control.
Assistant
Develop a request prioritization engine blending SLA tiers, fairness queueing, and admission control.
The user wants a request prioritization engine that combines three key concepts:
This is a classic systems engineering problem. I need to design a system architecture, data structures, and algorithms to implement this.
1. Conceptual Design & Strategy:
Input: Requests with metadata (UserID, Priority/SLA Tier, Payload, Complexity/Weight).
Queuing Mechanism: I need multiple queues.
Admission Control:
The "Blending" Algorithm:
Let's build a PriorityScheduler.
current_load > max_capacity * threshold:
N chances, Silver M chances, Bronze P chances.2. Implementation Details (Python):
Request: id, user_id, tier, payload.UserBucket: A queue for a specific user.TierQueue: Manages UserBuckets. Handles fairness among users within this tier.Scheduler: Manages TierQueues. Handles inter-tier priority (WFQ) and Admission Control.AdmissionController: Logic to accept/reject.3. Refining the Logic:
TierQueue maintains a list of active user queues. It iterates through them (Round Robin).4. Code Structure Plan:
import asyncio
import random
import time
from collections import deque, defaultdict
from enum import Enum
import heapq
class Tier(Enum): ...
class Request: ...
class AdmissionController:
# Checks global limits and tier limits
# Implements RED (Random Early Detection) or simple thresholds
def should_admit(request): ...
class FairnessQueue:
# Handles a specific tier.
# Map<user_id, deque>
# Active_users list (for round robin)
def enqueue(request): ...
def dequeue(): ... # Returns next request, ensuring user fairness
class Engine:
# Holds FairnessQueues for each tier
# The Dispatcher Loop
# Implements Inter-Tier Weighted Round Robin
async def run(): ...
5. Drafting the Admission Control Logic:
max_capacity: Total items in system.len(system) >= max_capacity:
6. Drafting the Fairness/Dispatching Logic:
7. Writing the Code (Mental Draft -> Actual Code):
asyncio to simulate concurrency.Self-Correction during drafting:
A simple Round Robin inside a tier is if implemented with a standard queue of queues.
Wait, strict Round Robin inside a tier requires knowing which users are currently active. We maintain a queue of user_ids who have pending items.
When enqueue(user_id, req) happens:
user_id not in active_users_queue, push user_id.req to user_req_map[user_id].When dequeue() happens:
user_id from active_users_queue.req from user_req_map[user_id].user_req_map[user_id] is not empty, push user_id back to active_users_queue.req.This is classic Fair Queueing.
Inter-Tier Prioritization (WFQ): We have 3 FairnessQueues (Gold, Silver, Bronze). We need to service them. Quantum based approach: Gold quantum = 10ms (or count). Silver quantum = 5ms. Bronze quantum = 1ms. Actually, let's use request counts relative to weights. Gold Weight = 3, Silver = 2, Bronze = 1. Loop: Serve 3 from Gold (if avail). Serve 2 from Silver (if avail). Serve 1 from Bronze (if avail). This creates a traffic ratio of 3:2:1 assuming infinite demand.
Admission Control Strategy:
Let's implement "Tiered Thresholds".
System Capacity = 100.
If current_load > 80: Drop Bronze.
If current_load > 95: Drop Silver.
If current_load >= 100: Drop Gold (System meltdown, usually better to reject everything or shed load, but Gold pays the bills, so maybe queue them?).
Actually, let's use a Queue limit.
Max Queue Size = 50.
Gold can use up to 50.
Silver up to 30.
Bronze up to 10.
If Bronze queue is full, drop new Bronze requests.
8. Refinement & Polish:
Add docstrings. Use dataclasses. Make it runnable. Add a simulation scenario:
9. Final Code Layout:
Request class.FairnessQueue class (logic for per-user fairness).AdmissionController class (logic for load shedding/rejection).PrioritizationEngine class (logic for WFQ across tiers + consuming from FairnessQueues).main simulation loop.This looks solid. I will write the Python implementation.
One detail on Admission Control:
To make it sophisticated, I'll implement a "Cost" function. Requests have a complexity.
Admission control checks current_cost + new_cost <= threshold.
For simplicity in this demo, I'll stick to request counts, as calculating execution time beforehand is hard without profiling. I will treat every request as "1 unit" but mention how it scales.
Self-Correction on WFQ: Simple Round Robin (Serve 3, then 2, then 1) can be bursty. Better: Calculate a "Virtual Time" or use a probabilistic selector (Pick a tier based on weight probability on every tick). Probabilistic is smoother for simulation. P(Gold) = 3/6 P(Silver) = 2/6 P(Bronze) = 1/6 If chosen tier is empty, try next highest? No, that distorts weights. Let's stick to Deficit Round Robin (DRR) or just strict counting (Quantum) for deterministic behavior in the demo. I'll use the counting method (service N requests per tier) as it's easier to visualize in logs.
Let's write it.
Step-by-Step Construction:
Data Structures:
Request: payload, sla_tier, user_id.Tier: Enum (PLATINUM, GOLD, SILVER, FREE).Components:
AdmissionController: Maintains current_load. Checks is_admissible(request).FairnessQueue: The intra-tier queue. Map of user_id -> deque. Main deque of active user_ids to ensure Round Robin.Scheduler: The main loop. Holds one FairnessQueue per tier. Implements the weighted priority logic.Admission Logic:
max_capacity.load > 80% and tier == FREE, reject. If load > 95% and tier == SILVER, reject.Scheduling Logic:
min(weight, len(queue)) items.Let's refine the "Fairness" part. What if a Gold user sends 100 requests and another Gold user sends 1? We must ensure the 1 request is processed roughly at the same rate per user, not per tier.
My FairnessQueue design (deque of user-queues) handles this perfectly.
Let's Go.
Code Check:
Does collections.deque support thread-safety? In CPython, append/pop are atomic, but with asyncio we don't have thread issues, we have coroutine issues. We need asyncio.Lock if we have multiple producers/consumers, but here we have one engine processing. Standard structures are fine.
Final check on "Admission Control blending". The prompt asks for an engine blending these. So the Admission Control shouldn't just be a gate; it should perhaps prioritize queueing slots for higher tiers. Logic: System has 100 slots. Platinum gets 30 reserved. Gold gets 20 reserved. Shared is 50. Or simple probabilistic admission.
Let's stick to Hierarchical Fair Service Curve (HFSC) simplified logic -> Weighted Fair Queuing.
I will produce a robust Python implementation. This design implements a Hierarchical Weighted Fair Queuing (HWFQ) system combined with Admission Control.
import time
import threading
import random
from collections import deque, defaultdict
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Deque, Optional
# --- Configuration ---
class Tier(Enum):
PLATINUM = 3 # Highest Priority
GOLD = 2
FREE = 1 # Lowest Priority
# Weights define how many 'credits' or 'turns' a tier gets relative to others
TIER_WEIGHTS = {
Tier.PLATINUM: 10,
Tier.GOLD: 5,
Tier.FREE: 1
}
# Admission Control Thresholds (Max concurrent active requests)
MAX_SYSTEM_CAPACITY = 50
# If load > 90%, reject FREE users. If > 95%, reject GOLD.
ADMISSION_THRESHOLDS = {
Tier.FREE: 0.90,
Tier.GOLD: 0.95,
Tier.PLATINUM: 1.00 # Only reject when truly full
}
# --- Data Structures ---
@dataclass(order=True)
class Request:
"""
Represents a unit of work.
'sort_index' is used by the heap/queue logic if strict ordering is needed,
but here we rely on the Queue structures.
"""
req_id: int
user_id: str
tier: Tier
payload: str
arrival_time: float = field(default_factory=time.time)
start_time: Optional[float] = None
def execute(self):
"""Simulate processing time."""
# Simulate variable processing time
proc_time = random.uniform(0.05, 0.2)
time.sleep(proc_time)
return f"Processed {self.req_id} (User: {self.user_id}, Tier: {self.tier.name})"
class UserQueue:
"""
Fairness Queue for a specific Tier.
Maintains a queue for each user to ensure fairness within the tier.
"""
def __init__(self):
# Mapping: user_id -> Deque of Requests
self.user_queues: Dict[str, Deque[Request]] = defaultdict(deque)
# Ordered list of user_ids waiting, to implement Round Robin
self.active_users: Deque[str] = deque()
self.lock = threading.Lock()
def push(self, req: Request):
with self.lock:
if not self.user_queues[req.user_id]:
# If user had no pending requests, add them to the end of active list
self.active_users.append(req.user_id)
self.user_queues[req.user_id].append(req)
def pop(self) -> Optional[Request]:
with self.lock:
if not self.active_users:
return None
# Round Robin: Check the first user in line
user_id = self.active_users[0]
req_queue = self.user_queues[user_id]
if not req_queue:
# Clean up: User queue empty (shouldn't happen if logic is perfect, but safety check)
self.active_users.popleft()
return self.pop() # Recursive call to find next user
# Pop the request
req = req_queue.popleft()
# Rotation Logic:
# If this user still has requests, move them to the end of the active_users list
# to give others a chance (Fairness).
if req_queue:
self.active_users.rotate(-1)
else:
# If empty, remove from active list entirely
self.active_users.popleft()
return req
def size(self):
return sum(len(q) for q in self.user_queues.values())
# --- The Engine ---
class PrioritizationEngine:
def __init__(self):
# Queues for each tier
self.queues = {tier: UserQueue() for tier in Tier}
# State
self.active_requests = 0
self.total_processed = 0
self.running = True
# Lock for admission control state
self.state_lock = threading.Lock()
def admission_control(self, req: Request) -> bool:
"""
Determines if a request should be accepted.
Implements 'Load Shedding' based on tier.
"""
with self.state_lock:
current_load_pct = self.active_requests / MAX_SYSTEM_CAPACITY
threshold = ADMISSION_THRESHOLDS[req.tier]
if current_load_pct >= threshold:
print(f"[REJECT] System Load {current_load_pct:.2f} >= Tier {req.tier.name} Threshold {threshold}. Dropping Req {req.req_id}")
return False
# Admit
self.active_requests += 1
return True
def submit_request(self, req: Request):
"""Entry point for incoming traffic."""
if not self.admission_control(req):
return # Request dropped
# Enqueue into the specific Tier's Fairness Queue
self.queues[req.tier].push(req)
def dispatcher_loop(self):
"""
The core scheduling loop.
Combines Weighted Fair Queuing (Inter-Tier) and Round Robin (Intra-Tier).
"""
while self.running:
request_found = False
# 1. Strict Priority / Weighted approach
# We iterate from Platinum -> Gold -> Free.
# In a strict Strict Priority system, we only check lower tiers if higher is empty.
# In a Weighted system, we would use a deficit counter.
# Here we implement a Hybrid: Strict Priority with 'burst' allowances.
for tier in [Tier.PLATINUM, Tier.GOLD, Tier.FREE]:
q = self.queues[tier]
# Optimization: Only pop if queue has items
if q.size() > 0:
req = q.pop()
if req:
request_found = True
self.process_request(req)
break # Restart loop from highest priority to ensure latency SLAs
if not request_found:
# If system is idle, sleep briefly to avoid spin-lock
time.sleep(0.01)
def process_request(self, req: Request):
"""Simulate processing and release resources."""
req.start_time = time.time()
wait_time = req.start_time - req.arrival_time
# Print status
print(f"Processing: {req.req_id:03} | Tier: {req.tier.name:8} | User: {req.user_id:5} | Wait: {wait_time:.3f}s")
# Execute (simulated blocking IO/CPU)
res = req.execute()
# Release resources
with self.state_lock:
self.active_requests -= 1
self.total_processed += 1
def stop(self):
self.running = False
# --- Simulation / Workload Generator ---
def simulate_traffic(engine: PrioritizationEngine, duration=5):
"""Floods the engine with mixed traffic."""
req_id = 0
start_time = time.time()
while time.time() - start_time < duration:
req_id += 1
# 1. Determine Tier (Most users are Free, few are Platinum)
p = random.random()
if p < 0.1: tier = Tier.PLATINUM
elif p < 0.4: tier = Tier.GOLD
else: tier = Tier.FREE
# 2. Determine User (Simulate 'Noisy Neighbor' on Free tier)
if tier == Tier.FREE and random.random() < 0.3:
user = "Spammer" # This user tries to send 30% of the free traffic
else:
user = f"User-{random.randint(1, 5)}"
req = Request(req_id, user, tier, "data")
engine.submit_request(req)
# Randomize arrival rate
time.sleep(random.uniform(0.01, 0.05))
if __name__ == "__main__":
engine = PrioritizationEngine()
# Start the Engine Dispatcher in a separate thread
dispatcher_thread = threading.Thread(target=engine.dispatcher_loop, daemon=True)
dispatcher_thread.start()
print(f"--- Starting Simulation (Capacity: {MAX_SYSTEM_CAPACITY}) ---")
# Start Traffic Generator
traffic_thread = threading.Thread(target=simulate_traffic, args=(engine, 5))
traffic_thread.start()
# Wait for traffic to finish
traffic_thread.join()
# Allow drain
time.sleep(2)
engine.stop()
print(f"--- Simulation Complete. Total Processed: {engine.total_processed} ---")
Admission Control (Gatekeeper)
submit_request checks admission_control.current_load (Active Requests / Max Capacity).Free requests are instantly rejected (HTTP 503 / 429), preserving the remaining 9% capacity specifically for paying Platinum users who might arrive late.Inter-Tier Prioritization (SLA Scheduling)
dispatcher_loop uses a Strict Priority approach. It always checks the Platinum UserQueue first.Intra-Tier Fairness (User Scheduling)
UserQueue class.user_id.active_users) of who has pending work.FREE tier, they will process one at a time, interleaved with other Free users. "User-Spammer" cannot block "User-Nice" who only sent 1 request.for tier in [...] loop with a Weighted Round Robin algorithm that picks a tier based on probability relative to TIER_WEIGHTS.