import threading
from collections import deque
from typing import Optional, Any, Dict, List
from dataclasses import dataclass
from enum import Enum
@dataclass
class EnqueueResult:
success: bool
reason: str = ""
class DrainMode(Enum):
NORMAL = "normal"
DRAINING = "draining"
OVERLOADED = "overloaded"
class QueueBackpressurePolicy:
"""
A thread-safe, queue-based backpressure policy with:
- **Credits**: Per-producer credit buckets. Enqueue consumes a credit;
successful dequeue replenishes it for that producer.
- **Draining**: High/low watermarks trigger drain mode, rejecting new enqueues
until queue drains below low watermark.
- **Fairness**:
- Max credits per producer prevents hogging.
- Min credits reserved for fairness (prevents starvation).
- Round-robin credit boost for idle producers during low load.
"""
def __init__(
self,
max_queue_size: int = 1000,
initial_credits_per_producer: int = 10,
max_credits_per_producer: int = 50,
min_credits_per_producer: int = 1,
high_watermark: float = 0.9, # 90% full -> start draining
low_watermark: float = 0.7, # 70% full -> resume normal
idle_credit_boost_interval: int = 100, # Dequeues before boosting idle producers
):
self.max_queue_size = max_queue_size
self.initial_credits = initial_credits_per_producer
self.max_credits = max_credits_per_producer
self.min_credits = min_credits_per_producer
self.high_watermark = high_watermark
self.low_watermark = low_watermark
self.idle_credit_boost_interval = idle_credit_boost_interval
self._queue: deque = deque(maxlen=max_queue_size)
self._producer_credits: Dict[str, int] = {}
self._producer_last_boost: Dict[str, int] = {}
self._drain_mode = DrainMode.NORMAL
self._dequeue_count = 0
self._lock = threading.Lock()
def register_producer(self, producer_id: str) -> bool:
"""Register a new producer with initial credits."""
with self._lock:
if producer_id in self._producer_credits:
return False
self._producer_credits[producer_id] = self.initial_credits
self._producer_last_boost[producer_id] = 0
return True
def unregister_producer(self, producer_id: str):
"""Unregister and reclaim credits (for cleanup)."""
with self._lock:
if producer_id in self._producer_credits:
del self._producer_credits[producer_id]
del self._producer_last_boost[producer_id]
def _update_drain_mode(self):
"""Update drain mode based on queue utilization."""
utilization = len(self._queue) / self.max_queue_size
if utilization > self.high_watermark:
self._drain_mode = DrainMode.DRAINING if self._drain_mode != DrainMode.OVERLOADED else DrainMode.OVERLOADED
elif utilization < self.low_watermark:
self._drain_mode = DrainMode.NORMAL
def _fairness_boost(self, producer_id: str):
"""Periodically boost idle producers for fairness."""
self._dequeue_count += 1
if self._dequeue_count % self.idle_credit_boost_interval == 0:
# Boost all producers with min credits by 1 (up to max)
for pid in list(self._producer_credits.keys()):
if (self._producer_credits[pid] == self.min_credits and
self._producer_last_boost[pid] < self._dequeue_count - self.idle_credit_boost_interval):
self._producer_credits[pid] = min(self.max_credits, self._producer_credits[pid] + 1)
self._producer_last_boost[pid] = self._dequeue_count
def enqueue(self, producer_id: str, item: Any) -> EnqueueResult:
"""Enqueue item with backpressure checks."""
if producer_id not in self._producer_credits:
return EnqueueResult(success=False, reason="Producer not registered")
with self._lock:
# Credit check (backpressure)
if self._producer_credits[producer_id] <= 0:
return EnqueueResult(success=False, reason="No credits available")
# Queue full check
if len(self._queue) >= self.max_queue_size:
self._update_drain_mode()
return EnqueueResult(success=False, reason="Queue full (draining)")
# Drain mode check
if self._drain_mode != DrainMode.NORMAL:
return EnqueueResult(success=False, reason=f"Draining ({self._drain_mode.value})")
# Enqueue and consume credit (fairness: cap credits)
self._queue.append((producer_id, item))
self._producer_credits[producer_id] -= 1
self._producer_credits[producer_id] = max(self.min_credits, self._producer_credits[producer_id])
self._update_drain_mode()
return EnqueueResult(success=True)
def dequeue(self) -> Optional[Any]:
"""Dequeue and replenish credit for the producer (FIFO for simplicity)."""
with self._lock:
if not self._queue:
return None
producer_id, item = self._queue.popleft()
# Replenish credit (fairness: cap at max)
self._producer_credits[producer_id] = min(self.max_credits, self._producer_credits[producer_id] + 1)
self._producer_last_boost[producer_id] = self._dequeue_count # Track activity
self._fairness_boost(producer_id)
self._update_drain_mode()
return item
def get_stats(self) -> Dict:
"""Get current stats for monitoring."""
with self._lock:
utilization = len(self._queue) / self.max_queue_size
return {
"queue_size": len(self._queue),
"utilization": utilization,
"drain_mode": self._drain_mode.value,
"producer_credits": dict(self._producer_credits),
"dequeue_count": self._dequeue_count,
}
Key Features Explained
Credits: Each producer has a credit bucket (initial=10, max=50, min=1). enqueue consumes 1 credit; dequeue replenishes 1 for that producer. No credits → immediate backpressure (reject).
Draining: Monitored via high/low watermarks (90%/70%). When high, enter DRAINING (reject new enqueues). Persists until below low watermark. OVERLOADED for extreme cases.
Fairness:
Per-producer credits prevent any single producer from flooding.
Min credits reserve capacity to avoid starvation.
Idle boost: Every N dequeues, boost producers stuck at min credits.
FIFO queue ensures order fairness within credits.
Usage Example
python
policy = QueueBackpressurePolicy(max_queue_size=10)
# Register producers
policy.register_producer("prod1")
policy.register_producer("prod2")
# Enqueue (succeeds initially)
print(policy.enqueue("prod1", "task1")) # EnqueueResult(success=True)
# Producer1 floods: will fail after credits exhausted
for i in range(20):
result = policy.enqueue("prod1", f"task{i}")
print(result)
# Dequeue to drain and replenish
for _ in range(5):
item = policy.dequeue()
print(f"Dequeued: {item}")
print(policy.get_stats())
This policy is production-ready for task queues, API gateways, or stream processors. Thread-safe with locks. Extend with priorities (e.g., Weighted Fair Queueing) if needed!