Adaptive Concurrency Controller Design
Overview
The Adaptive Concurrency Controller (ACC) is a distributed system component designed for high-throughput services (e.g., LLM inference APIs, microservices) that dynamically manages concurrency to balance throughput, latency, fairness, and resource efficiency. It integrates:
- Token Budgets: Per-tenant (user/account) and global rate limiting using a token bucket algorithm, where "tokens" represent compute units (e.g., input/output tokens in LLMs, CPU-seconds).
- Queue Fairness: Weighted Fair Queueing (WFQ) to prevent request starvation, prioritizing based on tenant tiers while ensuring proportional bandwidth.
- Autoscaling Signals: Real-time metrics (e.g., queue depth, latency p99, token depletion rate) emitted to an orchestrator (e.g., Kubernetes HPA, KEDA) for horizontal/vertical scaling.
The controller is adaptive: It uses feedback loops (PID-inspired) to tune max concurrency (max_concurrency) based on observed load, ensuring SLOs (e.g., p99 latency < 5s) while respecting budgets.
Key Goals:
- Maximize throughput without overwhelming resources.
- Fair allocation: High-volume tenants don't starve low-volume ones.
- Proactive scaling: Signal before overload.
Assumptions:
- Requests have metadata:
tenant_id, estimated_tokens (pre-computed via tokenizer).
- Deployed as a sidecar/proxy (e.g., Envoy filter) or middleware (e.g., in Go/Python).
- Backed by Redis (for shared state) or etcd for distributed consistency.
Architecture
[Ingress] --> [Fair Queue (WFQ)] --> [Token Budget Gate] --> [Concurrency Semaphore] --> [Workers/Pods]
| | | |
v v v v
[Fairness ] [Budget Refill] [Adaptive Limit] [Inference Engine]
Controller (Leaky Bucket) (PID Loop)
^ ^ ^
| | |
+--------------------+------------------------+
Metrics Aggregator
|
v
[Autoscaling Signals]
(Prometheus/Kafka)
1. Token Budget Manager
Purpose: Enforce hard limits on token consumption to prevent abuse/overspend.
- Per-Tenant Buckets: Each tenant has a bucket with
capacity (daily/hourly budget, e.g., 1M tokens/day) and refill_rate (e.g., 10k tokens/min).
- Global Bucket: Shared pool for burst handling (e.g., 100M tokens/hour).
- Algorithm: Token Bucket (RFC 3447 variant).
- On request: Check
estimated_tokens <= available_tokens. If yes, consume and proceed; else, enqueue/reject.
- Refill: Background goroutine/cron refills at
refill_rate, capped at capacity. Burst allowance via initial fill.
- Adaptivity: Dynamically adjust
refill_rate based on tenant history (e.g., +20% for underutilizers via ML prediction).
Pseudocode (Go-like):
type TokenBucket struct {
capacity, available, refillRate int64
lastRefill time.Time
}
func (b *TokenBucket) Consume(tokens int64) bool {
b.refill() // Atomic update
if b.available >= tokens {
b.available -= tokens
return true
}
return false
}
func (b *TokenBucket) refill() {
now := time.Now()
delta := int64(now.Sub(b.lastRefill).Minutes()) * b.refillRate
b.available = min(b.capacity, b.available + delta)
b.lastRefill = now
}
- Storage: Redis
INCR/DECR with Lua scripts for atomicity: shards[tenant_id].
2. Queue Fairness System
Purpose: Ensure equitable service across tenants, avoiding "noisy neighbor" issues.
- WFQ Scheduler: Virtual queues per tenant, with weights based on tier (e.g., Premium: weight=10, Free: weight=1).
- Requests enqueued with
tenant_id, priority (derived from SLA).
- Dequeue: Select queue with highest "virtual finish time" (WFQ formula:
finish_time = start_time + size/weight).
- Fairness Metrics:
- Served share ≈ weight share.
- Starvation prevention: Minimum quantum (e.g., 1 request/10s per queue).
- Adaptivity: Adjust weights dynamically (e.g., boost under-served queues by 1.5x).
Pseudocode:
type WFQQueue struct {
queues map[string]*VirtualQueue // tenant_id -> queue
weights map[string]float64
}
func (w *WFQQueue) Dequeue() *Request {
minFinish := math.MaxFloat64
var selected *VirtualQueue
for _, q := range w.queues {
if !q.empty() {
ftime := q.head().virtualFinishTime()
if ftime < minFinish {
minFinish = ftime
selected = q
}
}
}
return selected.pop()
}
- Fallback: Strict round-robin if WFQ overhead is high.
3. Concurrency Controller
Purpose: Limit parallel execution to max_concurrency (e.g., 100 workers).
- Mechanism: Distributed semaphore (Redis
SETNX or leader-elected locks).
- Adaptive Tuning (PID Loop, every 10s):
- Error Signal:
e = target_latency - observed_p99_latency (target=2s).
max_concurrency_new = max_concurrency + Kp*e + Ki*integral(e) + Kd*delta(e)
- Kp=0.1, Ki=0.01, Kd=0.05 (tunable).
- Bounds: 10 ≤ max_concurrency ≤ 1000.
- Gates Integration:
- Enqueue in WFQ.
- Dequeue → Check token budget → Acquire semaphore → Execute → Release.
4. Autoscaling Signals
Purpose: Proactive scaling for cluster autoscalers.
-
Emitted Metrics (Prometheus format, every 5s):
| Metric | Description | Scaling Trigger |
|---|
queue_depth | Total/WFQ depths | >80% → scale up |
token_depletion_rate | Tokens/sec consumed | >90% capacity → scale up |
p99_latency | End-to-end latency | >5s → scale up |
fairness_imbalance | Max-min served share | >2x deviation → alert |
headroom | (max_concurrency - active)/max_concurrency | <20% → scale up |
error_rate | Rejects due to budget/queue | >5% → scale up |
-
Output: Kafka/Prometheus push. KEDA can consume queue_depth > 100 for HPA.
Example HPA YAML Snippet:
apiVersion: autoscaling.keda.sh/v1alpha1
kind: ScaledObject
spec:
scaleTargetRef:
name: worker-deployment
triggers:
- type: prometheus
metadata:
query: avg(acc_queue_depth) > 100
threshold: '1'
Request Flow
- Request arrives → Enqueue in tenant's WFQ virtual queue.
- Scheduler dequeues → Check per-tenant/global token budget (reject 429 if fail).
- Acquire adaptive semaphore (wait or 503 if full).
- Execute in worker → Observe latency/tokens.
- Release semaphore → Update metrics.
- Controller loop: Tune
max_concurrency + emit signals.
Implementation Considerations
- Distributed: Redis Cluster for state (buckets, semaphore, queues).
- Edge Cases:
- Long-running requests: Heartbeat leases on semaphore.
- Budget bursts: Allow 2x refill for short spikes.
- Failover: Leader election (etcd) for controller.
- Monitoring: Grafana dashboards for PID tuning, fairness heatmaps.
- Tech Stack: Go (low-latency), Rust (safety), or Envoy WASM.
- Performance: <1ms overhead per request at 10k QPS.
- Testing: Chaos (queue floods), load tests (Locust).
This design scales to 1M+ req/min while maintaining fairness and SLOs. For prototypes, I can provide full Go code or Terraform for deployment!