Initial commit: Test GLM project
This commit is contained in:
@@ -0,0 +1,493 @@
|
||||
# Subtask: Rate Limiting and Task Throttling
|
||||
|
||||
**Parent Task**: Decomp/003
|
||||
**Subtask ID**: Decomp/003-09
|
||||
**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-02 (Task Producer API)
|
||||
|
||||
## Description
|
||||
|
||||
Implement rate limiting and task throttling to prevent abuse and manage resource consumption. Support per-queue limits, per-task-type limits, and dynamic rate adjustment.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Rate limit task enqueueing per queue
|
||||
- Rate limit per task type/function
|
||||
- Throttling based on system load
|
||||
- Token bucket algorithm for smooth limits
|
||||
- Configurable limits via database
|
||||
- Burst allowance handling
|
||||
- Priority queue bypass for high-priority tasks
|
||||
- Rate limit statistics and monitoring
|
||||
|
||||
## Technical Specifications
|
||||
|
||||
**Token bucket rate limiter**:
|
||||
```python
|
||||
import asyncio
|
||||
import time
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from typing import Dict, Optional
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@dataclass
|
||||
class RateLimit:
|
||||
"""Rate limit configuration."""
|
||||
rate: float # Tokens per second
|
||||
burst: int # Maximum bucket size (token capacity)
|
||||
|
||||
def __post_init__(self):
|
||||
if self.burst <= 0:
|
||||
self.burst = int(self.rate) # Default burst to 1 second worth
|
||||
|
||||
@dataclass
|
||||
class RateLimitState:
|
||||
"""Runtime state for rate limiter."""
|
||||
tokens: float
|
||||
last_update: float # Unix timestamp
|
||||
|
||||
class TokenBucketLimiter:
|
||||
"""Token bucket rate limiter."""
|
||||
|
||||
def __init__(self):
|
||||
# State: key -> (tokens, last_update)
|
||||
self._state: Dict[str, RateLimitState] = {}
|
||||
self._limits: Dict[str, RateLimit] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
def configure(self, key: str, rate: float, burst: int = None):
|
||||
"""Configure rate limit for a key."""
|
||||
self._limits[key] = RateLimit(
|
||||
rate=rate,
|
||||
burst=burst or int(rate)
|
||||
)
|
||||
|
||||
async def acquire(
|
||||
self,
|
||||
key: str,
|
||||
tokens: float = 1.0,
|
||||
block: bool = True,
|
||||
timeout: float = None
|
||||
) -> bool:
|
||||
"""
|
||||
Acquire tokens from the bucket.
|
||||
|
||||
Args:
|
||||
key: Bucket identifier
|
||||
tokens: Number of tokens to acquire
|
||||
block: Wait if tokens not available
|
||||
timeout: Max wait time in seconds
|
||||
|
||||
Returns:
|
||||
True if acquired, False if would exceed timeout
|
||||
"""
|
||||
limit = self._limits.get(key)
|
||||
if limit is None:
|
||||
# No limit configured
|
||||
return True
|
||||
|
||||
async with self._lock:
|
||||
now = time.time()
|
||||
state = self._state.get(key)
|
||||
|
||||
if state is None:
|
||||
state = RateLimitState(tokens=limit.burst, last_update=now)
|
||||
self._state[key] = state
|
||||
|
||||
# Refill tokens based on elapsed time
|
||||
elapsed = now - state.last_update
|
||||
state.tokens = min(limit.burst, state.tokens + elapsed * limit.rate)
|
||||
state.last_update = now
|
||||
|
||||
# Check if enough tokens
|
||||
if state.tokens >= tokens:
|
||||
state.tokens -= tokens
|
||||
return True
|
||||
|
||||
if not block:
|
||||
return False
|
||||
|
||||
# Calculate wait time
|
||||
deficit = tokens - state.tokens
|
||||
wait_time = deficit / limit.rate
|
||||
|
||||
if timeout is not None and wait_time > timeout:
|
||||
return False
|
||||
|
||||
# Wait outside lock, then retry
|
||||
await asyncio.sleep(min(wait_time, timeout or wait_time))
|
||||
return await self.acquire(key, tokens, block=False)
|
||||
|
||||
async def consume(
|
||||
self,
|
||||
key: str,
|
||||
tokens: float = 1.0
|
||||
) -> bool:
|
||||
"""Consume tokens without blocking (returns immediately)."""
|
||||
return await self.acquire(key, tokens, block=False)
|
||||
|
||||
def get_available_tokens(self, key: str) -> float:
|
||||
"""Get current token count for a key."""
|
||||
limit = self._limits.get(key)
|
||||
if limit is None:
|
||||
return float('inf')
|
||||
|
||||
state = self._state.get(key)
|
||||
if state is None:
|
||||
return limit.burst
|
||||
|
||||
now = time.time()
|
||||
elapsed = now - state.last_update
|
||||
return min(limit.burst, state.tokens + elapsed * limit.rate)
|
||||
|
||||
def reset(self, key: str = None):
|
||||
"""Reset token bucket(s)."""
|
||||
if key:
|
||||
self._state.pop(key, None)
|
||||
else:
|
||||
self._state.clear()
|
||||
```
|
||||
|
||||
**Rate limiting service**:
|
||||
```python
|
||||
class RateLimitingService:
|
||||
"""Service for rate limiting task operations."""
|
||||
|
||||
def __init__(self, db, redis=None):
|
||||
self.db = db
|
||||
self.redis = redis # Optional Redis for distributed rate limiting
|
||||
self.local_limiter = TokenBucketLimiter()
|
||||
self._initialized = False
|
||||
|
||||
async def initialize(self):
|
||||
"""Load rate limit configurations from database."""
|
||||
if self._initialized:
|
||||
return
|
||||
|
||||
async with self.db.acquire() as conn:
|
||||
# Load queue limits
|
||||
queue_limits = await conn.fetch(
|
||||
"""SELECT name, rate_limit, burst_limit
|
||||
FROM task_queues
|
||||
WHERE rate_limit IS NOT NULL"""
|
||||
)
|
||||
|
||||
for row in queue_limits:
|
||||
self.local_limiter.configure(
|
||||
key=f"queue:{row['name']}",
|
||||
rate=row['rate_limit'],
|
||||
burst=row.get('burst_limit')
|
||||
)
|
||||
|
||||
# Load task type limits
|
||||
task_limits = await conn.fetch(
|
||||
"""SELECT task_name, rate_limit, burst_limit
|
||||
FROM task_rate_limits
|
||||
WHERE is_active = TRUE"""
|
||||
)
|
||||
|
||||
for row in task_limits:
|
||||
self.local_limiter.configure(
|
||||
key=f"task:{row['task_name']}",
|
||||
rate=row['rate_limit'],
|
||||
burst=row.get('burst_limit')
|
||||
)
|
||||
|
||||
self._initialized = True
|
||||
|
||||
async def check_enqueue_limit(
|
||||
self,
|
||||
queue_name: str,
|
||||
task_name: str = None,
|
||||
priority: int = 5
|
||||
) -> tuple[bool, str]:
|
||||
"""
|
||||
Check if task can be enqueued under rate limits.
|
||||
|
||||
Returns:
|
||||
(allowed, reason)
|
||||
"""
|
||||
await self.initialize()
|
||||
|
||||
# High priority tasks bypass rate limits
|
||||
if priority <= 2:
|
||||
return True, "high_priority_bypass"
|
||||
|
||||
# Check queue limit
|
||||
queue_key = f"queue:{queue_name}"
|
||||
if not await self.local_limiter.consume(queue_key):
|
||||
return False, f"queue_rate_limit_exceeded:{queue_name}"
|
||||
|
||||
# Check task type limit
|
||||
if task_name:
|
||||
task_key = f"task:{task_name}"
|
||||
if not await self.local_limiter.consume(task_key):
|
||||
return False, f"task_rate_limit_exceeded:{task_name}"
|
||||
|
||||
return True, "ok"
|
||||
|
||||
async def wait_for_enqueue_slot(
|
||||
self,
|
||||
queue_name: str,
|
||||
task_name: str = None,
|
||||
timeout: float = 30.0
|
||||
) -> bool:
|
||||
"""Wait until a slot is available under rate limits."""
|
||||
await self.initialize()
|
||||
|
||||
tasks = []
|
||||
tasks.append(self.local_limiter.acquire(f"queue:{queue_name}", block=True, timeout=timeout))
|
||||
|
||||
if task_name:
|
||||
tasks.append(self.local_limiter.acquire(f"task:{task_name}", block=True, timeout=timeout))
|
||||
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
return all(r is True for r in results)
|
||||
|
||||
async def set_queue_limit(
|
||||
self,
|
||||
queue_name: str,
|
||||
rate: float,
|
||||
burst: int = None
|
||||
):
|
||||
"""Set rate limit for a queue."""
|
||||
async with self.db.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""UPDATE task_queues
|
||||
SET rate_limit = $1, burst_limit = $2
|
||||
WHERE name = $3""",
|
||||
rate,
|
||||
burst,
|
||||
queue_name
|
||||
)
|
||||
|
||||
self.local_limiter.configure(f"queue:{queue_name}", rate, burst)
|
||||
|
||||
async def set_task_limit(
|
||||
self,
|
||||
task_name: str,
|
||||
rate: float,
|
||||
burst: int = None
|
||||
):
|
||||
"""Set rate limit for a task type."""
|
||||
async with self.db.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""INSERT INTO task_rate_limits (task_name, rate_limit, burst_limit, is_active)
|
||||
VALUES ($1, $2, $3, TRUE)
|
||||
ON CONFLICT (task_name) DO UPDATE
|
||||
SET rate_limit = EXCLUDED.rate_limit,
|
||||
burst_limit = EXCLUDED.burst_limit,
|
||||
is_active = TRUE""",
|
||||
task_name,
|
||||
rate,
|
||||
burst
|
||||
)
|
||||
|
||||
self.local_limiter.configure(f"task:{task_name}", rate, burst)
|
||||
|
||||
async def get_limit_stats(self) -> dict:
|
||||
"""Get current rate limit statistics."""
|
||||
await self.initialize()
|
||||
|
||||
stats = {
|
||||
"queues": {},
|
||||
"tasks": {},
|
||||
"global_available": {}
|
||||
}
|
||||
|
||||
for key, limit in self.local_limiter._limits.items():
|
||||
available = self.local_limiter.get_available_tokens(key)
|
||||
prefix, name = key.split(":", 1)
|
||||
|
||||
if prefix == "queue":
|
||||
stats["queues"][name] = {
|
||||
"rate": limit.rate,
|
||||
"burst": limit.burst,
|
||||
"available": available
|
||||
}
|
||||
elif prefix == "task":
|
||||
stats["tasks"][name] = {
|
||||
"rate": limit.rate,
|
||||
"burst": limit.burst,
|
||||
"available": available
|
||||
}
|
||||
|
||||
return stats
|
||||
|
||||
class SystemThrottler:
|
||||
"""Throttle task processing based on system load."""
|
||||
|
||||
def __init__(self, db):
|
||||
self.db = db
|
||||
self._cpu_threshold = 80.0 # Percent
|
||||
self._memory_threshold = 85.0 # Percent
|
||||
self._queue_depth_threshold = 10000 # Tasks
|
||||
|
||||
async def should_throttle(self, queue_name: str = None) -> tuple[bool, str]:
|
||||
"""
|
||||
Check if system is under load and should throttle.
|
||||
|
||||
Returns:
|
||||
(should_throttle, reason)
|
||||
"""
|
||||
checks = []
|
||||
|
||||
# Check queue depth
|
||||
if queue_name:
|
||||
depth = await self._get_queue_depth(queue_name)
|
||||
if depth > self._queue_depth_threshold:
|
||||
checks.append(f"queue_depth:{depth}")
|
||||
|
||||
# Check running task count
|
||||
running = await self._get_running_count()
|
||||
if running > self._queue_depth_threshold:
|
||||
checks.append(f"running_tasks:{running}")
|
||||
|
||||
# Check DLQ size
|
||||
dlq_size = await self._get_dlq_size()
|
||||
if dlq_size > 100:
|
||||
checks.append(f"dlq_size:{dlq_size}")
|
||||
|
||||
if checks:
|
||||
return True, ",".join(checks)
|
||||
|
||||
return False, "ok"
|
||||
|
||||
async def _get_queue_depth(self, queue_name: str) -> int:
|
||||
"""Get pending task count for queue."""
|
||||
async with self.db.acquire() as conn:
|
||||
return await conn.fetchval(
|
||||
"""SELECT COUNT(*)
|
||||
FROM tasks t
|
||||
JOIN task_queues tq ON t.queue_id = tq.id
|
||||
WHERE tq.name = $1 AND t.status = 'pending'""",
|
||||
queue_name
|
||||
)
|
||||
|
||||
async def _get_running_count(self) -> int:
|
||||
"""Get total running task count."""
|
||||
async with self.db.acquire() as conn:
|
||||
return await conn.fetchval(
|
||||
"SELECT COUNT(*) FROM tasks WHERE status = 'running'"
|
||||
)
|
||||
|
||||
async def _get_dlq_size(self) -> int:
|
||||
"""Get dead letter queue size."""
|
||||
async with self.db.acquire() as conn:
|
||||
return await conn.fetchval("SELECT COUNT(*) FROM dead_letter_queue")
|
||||
|
||||
def set_thresholds(self, cpu: float = None, memory: float = None, queue_depth: int = None):
|
||||
"""Update throttling thresholds."""
|
||||
if cpu is not None:
|
||||
self._cpu_threshold = cpu
|
||||
if memory is not None:
|
||||
self._memory_threshold = memory
|
||||
if queue_depth is not None:
|
||||
self._queue_depth_threshold = queue_depth
|
||||
```
|
||||
|
||||
**Integration with task producer**:
|
||||
```python
|
||||
# Modify TaskProducer to check rate limits
|
||||
class TaskProducer:
|
||||
def __init__(self, broker, rate_limiter: RateLimitingService = None):
|
||||
self.broker = broker
|
||||
self.rate_limiter = rate_limiter
|
||||
# ... rest of init
|
||||
|
||||
async def apply_async(
|
||||
self,
|
||||
task_func,
|
||||
args=None,
|
||||
kwargs=None,
|
||||
queue=None,
|
||||
priority=TaskPriority.NORMAL,
|
||||
**options
|
||||
) -> str:
|
||||
"""Apply a task with rate limiting."""
|
||||
|
||||
# Get task name
|
||||
if callable(task_func):
|
||||
task_name = f"{task_func.__module__}.{task_func.__name__}"
|
||||
else:
|
||||
task_name = task_func
|
||||
|
||||
queue_name = queue or self.default_queue
|
||||
|
||||
# Check rate limits
|
||||
if self.rate_limiter:
|
||||
allowed, reason = await self.rate_limiter.check_enqueue_limit(
|
||||
queue_name=queue_name,
|
||||
task_name=task_name,
|
||||
priority=priority.value
|
||||
)
|
||||
|
||||
if not allowed:
|
||||
raise RateLimitError(f"Rate limit exceeded: {reason}")
|
||||
|
||||
# Continue with normal enqueue logic
|
||||
# ... (rest of apply_async implementation)
|
||||
```
|
||||
|
||||
**Database schema extensions**:
|
||||
```sql
|
||||
-- Add rate limit columns to task_queues
|
||||
ALTER TABLE task_queues
|
||||
ADD COLUMN rate_limit FLOAT, -- Tokens per second
|
||||
ADD COLUMN burst_limit INTEGER; -- Maximum bucket size
|
||||
|
||||
-- Task-specific rate limits
|
||||
CREATE TABLE task_rate_limits (
|
||||
id SERIAL PRIMARY KEY,
|
||||
task_name VARCHAR(200) NOT NULL UNIQUE,
|
||||
rate_limit FLOAT NOT NULL,
|
||||
burst_limit INTEGER,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_task_rate_limits_active ON task_rate_limits(task_name) WHERE is_active = TRUE;
|
||||
|
||||
-- Trigger to update updated_at
|
||||
CREATE TRIGGER task_rate_limits_updated_at
|
||||
BEFORE UPDATE ON task_rate_limits
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION update_updated_at();
|
||||
```
|
||||
|
||||
**Custom exception**:
|
||||
```python
|
||||
class RateLimitError(Exception):
|
||||
"""Raised when rate limit is exceeded."""
|
||||
def __init__(self, message: str, retry_after: float = None):
|
||||
super().__init__(message)
|
||||
self.retry_after = retry_after
|
||||
```
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] Queue rate limits are enforced
|
||||
- [ ] Task type rate limits are enforced
|
||||
- [ ] High-priority tasks bypass limits
|
||||
- [ ] Rate limits can be configured dynamically
|
||||
- [ ] System throttling activates under load
|
||||
- [ ] Rate limit stats are available
|
||||
- [ ] Token bucket refills correctly
|
||||
|
||||
## Notes
|
||||
|
||||
**Trade-offs**:
|
||||
- In-memory vs distributed limiter: In-memory for simplicity, Redis for distributed
|
||||
- Reject vs delay: Prefer reject with retry-after for APIs
|
||||
|
||||
**Performance**:
|
||||
- Use Redis for distributed deployments
|
||||
- Batch limit checks for multiple tasks
|
||||
|
||||
**Alternatives considered**:
|
||||
- Fixed window: Token bucket smoother
|
||||
- Leaky bucket: Token bucket more flexible
|
||||
- Sliding window log: More complex, less performant
|
||||
Reference in New Issue
Block a user