Best practices for handling rate limiting
Model Studio APIs limit request volume, token usage, and growth rate. Apply these strategies to maximize throughput and maintain availability.
Model Studio API imposes limits on the number of requests, Token usage, and the growth rate, known as rate limiting. Large model requests involve high latency and are constrained by both request count and Token volume, so simply "retrying on error" has limited effect — targeted flow-control measures are required.
Three solution types, ordered from lowest to highest implementation cost:
- Platform configuration solutions (minimal code changes): Server-side queuing, PTU, and Batch API.
- Client-side traffic control strategies (client code changes): Four strategies with increasing engineering complexity, from basic retry to adaptive congestion control.
- Architectural fallback solutions (system architecture changes): Model fallback and peak-load shifting using message queues (MQ).
If you are troubleshooting a 429 error now, go to Error diagnosis and strategy recommendations to identify the cause. For traffic burst errors, try server-side queuing first — it only requires one request header.
Platform rate limiting mechanism
Rate limiting is calculated independently per Alibaba Cloud account and per model, and typically recovers within 1 minute after being triggered. For each model's rate-limit conditions and current usage, see Model rate-limit conditions and Monitoring. Model Studio API has the following three rate-limit rules:
- Minute-level quota limits (RPM / TPM): The maximum number of requests per minute (RPM) and the maximum token usage per minute (TPM).
- Instantaneous frequency limits (RPS / TPS): Maximum requests per second (RPS) and maximum token usage per second (TPS). Dense API calls or token consumption within a single second can trigger rate limiting.
- Growth rate limits (Traffic Burst): A sudden surge in request volume or token usage triggers rate limiting. The threshold adjusts dynamically. Ramp up requests gradually to avoid triggering this limit.
The following sections cover solutions at three levels: platform configuration, client-side traffic control, and architectural fallback.
Error diagnosis and strategy recommendations
The same error code can be triggered by different rate limiting dimensions. High concurrency can also saturate the server, causing timeouts. The adaptive congestion control strategy can help mitigate this.
Error code (DashScope / OpenAI) | Triggering dimension | Feature diagnosis | Recommended strategy |
|---|---|---|---|
Throttling.RateQuota / limit_requests | Request rate exceeded | Intermittent errors. Success rate decreases over time. | Token bucket: Control the request quota per unit of time. |
Request rate exceeded | Concentrated errors at startup or during concurrency spikes. | Concurrency semaphore or smoothing rate limiter: Increase the interval between requests. | |
Throttling.AllocationQuota / insufficient_quota | Token usage exceeded | Intermittent errors when processing long texts. | Dual token bucket: Limit both RPM and TPM quotas simultaneously. |
Token usage exceeded | Instantaneous token consumption is too high during concurrent processing of long texts. | ||
Throttling.BurstRate / limit_burst_rate | Traffic growth rate exceeded | Sudden large volume of requests after startup or recovery from an idle state. | We recommend trying server-side queuing first. Alternatively, use a token bucket with a low initial value, such as |
Platform configuration solutions
These solutions rely on platform capabilities and require minimal or no client-side code changes.
Server-side queuing (recommended)
For traffic burst rate limiting, Model Studio accepts an upper bound for the wait time in the request header. After receiving the request, the server retries it as opportunities arise within that window until it starts processing or the retries within the window end. The value is only an upper bound; the server does not wait until the value is reached before retrying. This significantly improves success rates during traffic bursts compared to an immediate 429 response.
NoteThis feature only applies to growth rate / traffic burst rate limiting (Throttling.BurstRate). It does not apply to absolute quota rate limiting (RPM/TPM).
Add the X-DashScope-Wait-Timeout field to the request header:
Header field | Examples | Description |
|---|---|---|
X-DashScope-Wait-Timeout | 90 | The upper limit of the queuing wait time window, in seconds. The server retries the request at an opportune time within this window, rather than waiting until the configured value before starting retries.
|
After configuring queuing wait, adjust the client timeout accordingly to prevent the connection from closing early due to the added queuing time:
- Non-streaming requests (stream: false): timeout = original base timeout + Wait-Timeout value.
- Streaming requests (stream: true): timeout > Wait-Timeout value. Streaming requests start timing after the first chunk is received, so you only need to ensure the first-response timeout is greater than the queuing time.
For example, if the original base timeout is 120 s and Wait-Timeout is set to 90 s, the timeout for non-streaming requests should be set to 210 s.
Code example
import os
from openai import OpenAI
client = OpenAI(
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
api_key=os.getenv("DASHSCOPE_API_KEY"),
timeout=210.0, # 原超时 120s + 排队等待上限 90s
)
response = client.chat.completions.create(
model="qwen-plus",
messages=[{"role": "user", "content": "Hello"}],
extra_headers={
"X-DashScope-Wait-Timeout": "90" # 排队等待上限 90 秒
}
)
print(response.choices[0].message.content)
curl -X POST "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-Wait-Timeout: 90" \
-d '{
"model": "qwen-plus",
"messages": [{"role": "user", "content": "Hello"}]
}'
Provisioned Throughput Unit (PTU)
The PTU service provides independently reserved dedicated computing power, avoiding contention in the public resource pool. It is the first choice for guaranteeing real-time high throughput.
Applicable Scenario: Your business has deterministic throughput requirements (such as SLA commitments), or you want to skip client-side flow-control development and directly obtain stable high throughput.
PTUs are reserved resources and are billed continuously even when not fully utilized. Evaluate the specification based on actual peak usage to avoid idle waste.
Asynchronous batch processing (Batch API)
For tasks without real-time requirements, such as data cleaning and offline analysis, you can use the Batch API to submit requests in batches. Tasks execute asynchronously during off-peak periods and are not subject to online rate limits.
Applicable Scenario: Tasks such as data annotation, log analysis, and batch summarization that tolerate results returned within hours to days. Costs are typically lower than real-time APIs.
The result return time is uncertain, making it unsuitable for online businesses that require immediate responses. After submission, results must be retrieved through polling or callbacks.
Client-side flow-control strategies
When platform solutions (such as server-side queuing wait) cannot meet your needs, introduce flow control on the client side. Core principle: distribute requests evenly across the time window to avoid bursts that trigger rate limiting. After system startup or long idle periods, ramp up concurrency gradually instead of maxing out instantly.
The following four strategies are listed in ascending order of engineering complexity; each includes the capabilities of the previous level and adds more:
- Basic retry provides passive defense only;
- Request rate limiting adds active queuing;
- Traffic shaping further introduces Token-level control and smoothed sending;
- Adaptive congestion control dynamically adjusts the sending rate based on real-time feedback.
Provided business requirements are met, prefer the strategy with the lowest implementation cost.
Throughput comparison of the strategies
Throughput performance of the four strategies under different loads:
- Basic retry strategy: Effective under low load, but prone to congestion collapse under high concurrency, with a cliff-like drop in throughput.
- Request rate limiting strategy: Strong crash resistance, but under mixed workloads dominated by long texts, throughput fluctuates in a sawtooth pattern due to the lack of Token control.
- Traffic shaping strategy: High stability, trading some peak throughput for steady output.
- Adaptive congestion control strategy: Under high load, it can dynamically converge to a stable high-throughput point, but incurs cold-start probing overhead.
Basic retry strategy
Suitable for low-concurrency scenarios such as personal testing and local scripts. It does not limit the sending rate; it only triggers exponential backoff retries with random jitter upon receiving 429 or 5xx.
Without upstream traffic control, multi-threaded concurrency easily triggers rate limiting and causes request backlog.
Code example
import openai
from openai import OpenAI
from tenacity import (
retry,
stop_after_attempt,
wait_random_exponential,
retry_if_exception_type
)
RETRYABLE_ERRORS = (
openai.RateLimitError,
openai.InternalServerError,
openai.APIConnectionError,
)
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(6),
retry=retry_if_exception_type(RETRYABLE_ERRORS)
)
def chat_with_retry(client, model, messages, max_tokens):
return client.chat.completions.create(
model=model,
max_tokens=max_tokens,
messages=messages
)
client = OpenAI(
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
api_key="YOUR_DASHSCOPE_API_KEY"
)
try:
response = chat_with_retry(
client=client,
model="qwen-plus",
messages=[{"role": "user", "content": "什么是指数退避重试?"}],
max_tokens=1024
)
print(response.choices[0].message.content)
except Exception as e:
print(f"请求失败: {e}")
import time
import random
import openai
from openai import OpenAI
RETRYABLE_ERRORS = (
openai.RateLimitError,
openai.InternalServerError,
openai.APIConnectionError,
)
def chat_with_retry(client, model, messages, max_tokens):
attempt = 0
max_retries = 5
base_delay = 1
max_delay = 60
while attempt <= max_retries:
try:
return client.chat.completions.create(
model=model,
max_tokens=max_tokens,
messages=messages
)
except RETRYABLE_ERRORS as e:
attempt += 1
if attempt > max_retries:
raise e
backoff = min(max_delay, base_delay * (2 ** (attempt - 1)))
sleep_time = backoff + random.uniform(0, 1)
print(f"触发 {type(e).__name__},等待 {sleep_time:.2f}s 后重试...")
time.sleep(sleep_time)
client = OpenAI(
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
api_key="YOUR_DASHSCOPE_API_KEY"
)
try:
response = chat_with_retry(
client=client,
model="qwen-plus",
messages=[{"role": "user", "content": "什么是指数退避重试?"}],
max_tokens=1024
)
print(response.choices[0].message.content)
except Exception as e:
print(f"请求失败: {e}")
The above code uses exponential backoff instead of fixed-interval retries. Fixed-interval retries cause all failed requests to resend at the same time, triggering rate limiting again. Exponential backoff + random jitter spreads retries out:
- Wait time doubles progressively: for example
1s:2s:4s..., avoiding repeated requests within a short period. - Add random jitter: introduce random values (such as
2s +/- 0.5s) to spread out retry traffic, preventing "clustered" retries from forming a secondary peak (thundering herd effect).
The system recovers in a distributed manner, avoiding the vicious cycle of "failure—collective retry—failure again".
Request rate limiting strategy
Passive retries struggle to handle real business traffic, and frequent retries increase latency. This strategy introduces proactive flow control: requests self-check before being sent, turning unordered incoming requests into a queue that conforms to RPM limits. Proactive smoothing introduces a small, controllable queuing delay, but far below the cost of the "error—wait—retry" loop—trading a certain small cost to avoid uncertain large delays.
Suitable for lightweight interactions such as chatbots and online services sensitive to time-to-first-token latency.
Client-side proactive queuing uses two levels of control:
- RPM token bucket: limits the total number of requests per minute. The bucket capacity is the RPM quota, and tokens refill at a constant rate. Advance spending is supported: when tokens are insufficient, future quota can be drawn in advance, with strict FIFO.
- Concurrency semaphore: limits the number of concurrent requests to prevent instantaneous high concurrency from triggering RPS limits.
The two levels of control must acquire the RPM token first, then the concurrency semaphore. Concurrency slots are a scarce resource and should only be allocated to requests that already meet execution conditions. If the order is reversed, high load causes head-of-line blocking—requests hold slots with no tokens available, all slots get occupied but no requests are sent. Principle: never perform long waits while holding a scarce resource.
The code below initializes the token bucket as full (initial_tokens=rpm_limit), suitable for online services that need to process requests immediately at startup. If a full-bucket start triggers rate limiting, you can lower the initial value (for example initial_tokens=0, empty-bucket start) so the system enters its working state at a gentler rate.
This strategy does not track token usage, so long-text tasks may still exhaust the TPM quota.
Code example
import time
class TokenBucket:
"""
令牌桶实现,用于控制每分钟请求数 (RPM)。
支持预支 (Debt) 机制,以保证高并发下的先进先出 (FIFO) 顺序。
"""
def __init__(self, quota_per_minute: float, initial_tokens: float = 0.0):
self.capacity = quota_per_minute
self.tokens = initial_tokens
self.refill_rate = quota_per_minute / 60.0
self.last_refill = time.monotonic()
def reserve(self, cost: float = 1.0) -> float:
"""
申请令牌。
如果令牌不足,返回需要等待的秒数(支持预支)。
"""
self._refill()
# 1. 令牌充足:直接扣除
if self.tokens >= cost:
self.tokens -= cost
return 0.0
# 2. 令牌不足:计算等待时间并预支
# 为当前请求"预定"了未来的令牌,确保 FIFO 顺序
deficit = cost - self.tokens
wait_seconds = deficit / self.refill_rate
self.tokens -= cost
return wait_seconds
def _refill(self):
"""根据流逝时间补充令牌"""
now = time.monotonic()
elapsed = now - self.last_refill
if elapsed > 0:
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
self.last_refill = now
import asyncio
import openai
from openai import AsyncOpenAI
from tenacity import retry, wait_random_exponential, stop_after_attempt, retry_if_exception_type
class RateLimitedClient:
def __init__(
self,
api_key: str,
base_url: str = "https://dashscope.aliyuncs.com/compatible-mode/v1",
rpm_limit: float = 600.0,
max_concurrency: int = 20
):
self.client = AsyncOpenAI(api_key=api_key, base_url=base_url)
# 组件 1: RPM 令牌桶 (控制总量)
self.rpm_bucket = TokenBucket(
quota_per_minute=rpm_limit,
initial_tokens=rpm_limit # 满桶启动,适合轻量在线服务
)
# 组件 2: 并发信号量 (控制瞬间并发)
self.semaphore = asyncio.Semaphore(max_concurrency)
async def _execute_request(self, model, messages, max_tokens):
"""执行单个请求:依次通过 RPM 检查和并发限制。"""
# 1. RPM 检查 (先拿令牌)
wait_seconds = self.rpm_bucket.reserve(1.0)
if wait_seconds > 0:
await asyncio.sleep(wait_seconds)
# 2. 并发检查 (再拿信号量)
async with self.semaphore:
# 3. 发起 API 调用
return await self.client.chat.completions.create(
model=model,
messages=messages,
max_tokens=max_tokens
)
@retry(
wait=wait_random_exponential(min=1, max=60),
stop=stop_after_attempt(5),
retry=retry_if_exception_type((
openai.RateLimitError,
openai.InternalServerError,
openai.APIConnectionError
))
)
async def chat_with_limit(self, model, messages, max_tokens=1024):
# 设计考量:为什么重试也要重新拿 Token?
# 答:为了安全。如果不重新拿,重试带来的流量脉冲
# 可能会瞬间突破 RPM 限制
return await self._execute_request(model, messages, max_tokens)
Traffic shaping strategy
In scenarios requiring high, stable throughput such as real-time RAG ingestion and batch analysis of long documents, request rate limiting has a TPM blind spot. The traffic shaping strategy upgrades to dual-resource awareness (RPM & TPM) and introduces a shaping mechanism on the sending side, leveling bursty pulses into smooth flow.
Building on request rate limiting, it enhances the following capabilities:
- Dual-resource control (RPM & TPM): maintains both RPM and TPM token buckets; every request must pass quota checks on both dimensions before being sent.
- Input pre-deducted, output settled afterward: the model's output length is unknown before a request. The TPM token bucket pre-deducts only input tokens at send time and settles the actual output after completion. Even if tokens go negative after settlement, subsequent requests wait for recovery, naturally smoothing the flow.
- Steady warm-up: during cold start, the token issuance rate grows linearly over time, eliminating initial burst risk.
- Smooth rate limiting: enforces a minimum interval between requests (pacing) to smooth the send rate and reduce the risk of triggering rate limits.
Alternative: if your business is insensitive to the small queuing delay at startup, you can reuse a standard token bucket (set initial_tokens=0) for a safe start and reduce client complexity. The Python token bucket only demonstrates the idea; for production environments, use mature rate-limiting components (such as Java Guava's SmoothRateLimiter).
In the sample code, the smoothing wait is placed inside the concurrency lock. Multiple requests may compete for the semaphore simultaneously after their waits end, causing traffic to congest again at the exit. Smoothing inside the lock slightly reduces concurrency efficiency, but keeps the send interval controllable.
The complete traffic shaping pipeline is: Estimate input tokens → Dual admission (RPM & TPM) → Concurrency lock → Smoothing → Send → Output token settlement.
This strategy uses a conservative smoothing mechanism that sacrifices some peak concurrency and is not suitable for online services requiring extremely low latency.
Code example
import time
class TokenBucket:
"""进阶令牌桶,支持匀速预热 (Continuous Warm-up) 机制。"""
def __init__(self, quota_per_minute: float, warmup_seconds: float = 0.0):
self.capacity = quota_per_minute
self.tokens = 0.0
self.target_refill_rate = quota_per_minute / 60.0
self.warmup_seconds = warmup_seconds
self.start_time = time.monotonic()
self.last_update_time = self.start_time
self.cumulative_generated = 0.0
def _get_cumulative_tokens(self, t: float) -> float:
if t <= 0:
return 0.0
R = self.target_refill_rate
T = self.warmup_seconds
if T <= 0:
return R * t
if t <= T:
return (R / (2 * T)) * (t ** 2)
else:
warmup_total = (R * T) / 2.0
return warmup_total + R * (t - T)
def _get_time_for_cumulative_tokens(self, target_cumulative: float) -> float:
if target_cumulative <= 0:
return 0.0
R = self.target_refill_rate
T = self.warmup_seconds
if T <= 0:
return target_cumulative / R
warmup_total = (R * T) / 2.0
if target_cumulative <= warmup_total:
return ((2 * T * target_cumulative) / R) ** 0.5
else:
return (target_cumulative - warmup_total) / R + T
def reserve(self, cost: float = 1.0) -> float:
now = time.monotonic()
relative_now = now - self.start_time
current_cumulative = self._get_cumulative_tokens(relative_now)
new_tokens = current_cumulative - self.cumulative_generated
self.tokens = min(self.capacity, self.tokens + new_tokens)
self.cumulative_generated = current_cumulative
self.last_update_time = now
if self.tokens >= cost:
self.tokens -= cost
return 0.0
deficit = cost - self.tokens
self.tokens -= cost
target_cumulative = self.cumulative_generated + deficit
target_time = self._get_time_for_cumulative_tokens(target_cumulative)
wait_seconds = target_time - relative_now
return max(0.0, wait_seconds)
def adjust(self, amount: float):
self.tokens = min(self.capacity, self.tokens + amount)
import time
class SmoothRateLimiter:
def __init__(self, rate_per_minute: float):
self._min_interval = 60.0 / rate_per_minute
self._last_operation = time.monotonic()
def reserve(self) -> float:
now = time.monotonic()
elapsed = now - self._last_operation
wait_time = max(0.0, self._min_interval - elapsed)
self._last_operation = now + wait_time
return wait_time
import asyncio
class TrafficShapingClient:
def __init__(self):
self._rpm_bucket = TokenBucket(quota_per_minute=600)
self._tpm_bucket = TokenBucket(quota_per_minute=1_000_000)
self._smooth_limiter = SmoothRateLimiter(rate_per_minute=600)
self._concurrency_semaphore = asyncio.Semaphore(20)
async def _execute_throttled_request(self, model, prompt, max_tokens, input_tokens):
# [步骤 1] 双重准入控制 (Parallel Admission)
# 同时检查 RPM 和 TPM,取两者中较长的等待时间
wait_rpm = self._rpm_bucket.reserve(1.0)
# TPM 检查仅针对输入 Token 申请额度
wait_tpm = self._tpm_bucket.reserve(input_tokens)
admission_wait = max(wait_rpm, wait_tpm)
if admission_wait > 0:
await asyncio.sleep(admission_wait)
# [步骤 2] 获取并发锁 (Concurrency Lock)
async with self._concurrency_semaphore:
# [步骤 3] 流量整形 (Traffic Shaping)
# 关键:在锁内进行平滑等待
# 牺牲部分并发效率,换取发送间隔的精准可控
smooth_wait = self._smooth_limiter.reserve()
if smooth_wait > 0:
await asyncio.sleep(smooth_wait)
# [步骤 4] 发送请求
content, actual_usage = await self._send_chat_request(model, prompt, max_tokens)
# [步骤 5] 输出 Token 结算
output_tokens = actual_usage.completion_tokens
if output_tokens > 0:
self._tpm_bucket.adjust(-output_tokens)
return content
Adaptive congestion control strategy
Suitable for large-scale dynamic load scenarios such as API gateways, complex proxies, and multi-tenancy.
Note
Selection tip: this strategy is not a universal solutionThe value of this strategy lies in handling highly uncertain and volatile environments; it is not a universal choice:
- Performance paradox: if the load is predictable (such as fixed-volume batch processing), directly setting optimal static parameters usually outperforms dynamic probing that requires "probing and convergence".
- Probing overhead: dynamic algorithms inevitably involve cold-start ramping and probing fluctuation, which is unnecessary performance overhead in predictable scenarios.
- Maintenance cost: the closed-loop feedback mechanism increases system complexity and troubleshooting difficulty.
Unless your business is of extremely large scale, with complex and significantly fluctuating load, prefer the simpler first three strategies.
Request rate limiting and traffic shaping are based on static quotas and fully applicable under stable load. But in gateway-level scenarios, downstream load is complex and volatile (short requests interleaved with deep reasoning), and platform thresholds also fluctuate dynamically; static strategies struggle to balance efficiency and stability.
This strategy draws on BBR to build a closed-loop control system based on EBP (Elastic Bandwidth Probing). It takes RPM/TPM quotas as guiding upper bounds and dynamically computes the optimal send rate from real-time feedback (latency, rate-limiting signals).
- Elastic probing (EBP): remembers the historical highest success watermark and computes the probing gain by simulating spring tension based on the distance between current concurrency and the highest watermark (accelerating when far, decelerating when near). A tiny linear thrust is added on top to ensure the boundary can still be explored in high-saturation zones.
- TPT congestion awareness: large model generation time is proportional to output length, so high latency on long texts does not indicate congestion. TPT (Time Per Token) is used as the metric to filter out content-length noise, and computational saturation is declared only when TPT degrades significantly.
- Anti-burst governor: no matter how high the target computed by EBP is, the governor forcibly caps the acceleration of concurrency growth, ensuring traffic rises smoothly and avoiding step jumps that trigger rate-increase limits.
Compared with native BBR, the following adaptations were made for large model characteristics:
- Guided probing: Introduces the known RPM/TPM quotas as a "guideline ceiling" to avoid frequent quota collisions caused by blind trial and error.
- Signal source redesign (RTT → TPT): Native BBR relies on RTT, but in large models the latency variance caused by content length far exceeds network jitter, so TPT is used instead to eliminate the interference.
- Response mechanism enhancement (ProbeRTT → Hold): In the face of latency fluctuations, it maintains the current concurrency level instead of actively backing off and reducing throughput.
- Hard rate-limit response (Packet Loss → 429 Drain): Once a
429error is triggered, it enters an aggressive Drain state and performs fast recovery after the cooldown period ends.
Limitations:
- TPT noise: The current TPT is roughly estimated as "total latency / total token count", which mixes in network round trips, queuing, and time to first token. It is prone to being inflated by jitter or long inputs, which may falsely trigger the Hold state.
- Large-request starvation: To pursue scheduling performance, a non-strict FIFO wake-up mechanism is adopted. When quotas are scarce, short-token requests may preempt resources, causing long-token requests to wait excessively.
- Cold start: It requires warm-up time to build the statistical model, so throughput may be lower than that of the first three strategies under low load or in short-lived tasks.
Code example
class ElasticCongestionController:
async def acquire(self):
"""[准入阶段] 请求发起前的检查"""
# 1. SSR 慢启动重启:若空闲太久,主动衰减上限
# 防止过时水位导致的突发流量
if self.is_idle_too_long():
self.perform_slow_start_restart()
# 2. 熔断检查:若处于 DRAIN (冷却) 状态,强制等待
if self.state == CongestionState.DRAIN:
await self.wait_for_cooldown()
# 3. 双重预算检查:同时检查并发槽位和 Token 预算
await self.wait_for_budget(request_tokens)
async def release(self, latency, actual_tokens, error):
"""[反馈阶段] 请求结束后的决策"""
if error:
# [故障响应] 遇限流错误 (429/503):立即排水 + 乘性回退
self.state = CongestionState.DRAIN
self.concurrency_limit *= self.backoff_factor # e.g. 0.7
return
# [正常响应] 计算 TPT (Time-Per-Token)
current_tpt = latency / actual_tokens
# [拥塞感知] TPT 突增 (生成变慢):进入 HOLD 观察
# 维持并发水平,不退避也不增长
if current_tpt > self.metrics.ema_tpt * 2.0:
self.state = CongestionState.HOLD
else:
# [稳态探测] 网络健康:执行 EBP 弹性探测
self.state = CongestionState.PROBING
self.update_limit_via_ebp()
def probe_next_limit(self, current_limit, max_known_capacity):
"""
计算下一个并发上限
核心公式:Next = Max(弹簧张力, 线性推力) + 调速器平滑
"""
# 1. 计算物理上限 (Little's Law)
# 理论上限 = 吞吐量 * 延迟 * 缓冲因子
dynamic_ceiling = self.metrics.tps * self.metrics.avg_latency * 1.2
# 2. 弹簧逻辑 (Spring Tension)
# 距离历史最高水位越远,张力越大(加速);越近则越小(减速)
tension = 1.0 - (current_limit / max_known_capacity)
spring_target = current_limit * (1.0 + tension * gain)
# 3. 线性推力 (Additive Thrust)
# 解决"芝诺悖论":张力趋近于 0 时,强制叠加微小线性增量
# 确保系统能突破局部极值,持续探索边界
linear_target = current_limit + self.min_additive_step
raw_target = max(spring_target, linear_target)
# 4. 防突发调速器 (Rate Governor)
# 限制并发增长的加速度,防止阶梯跳变
final_limit = self.governor.smooth(raw_target)
return min(final_limit, dynamic_ceiling)
class CongestionMetrics:
def update_stats(self, latency, token_count):
"""
[传感器] 实时更新统计指标
使用 EMA (指数移动平均) 滤除长尾请求的噪声
"""
alpha = 0.2 # 平滑因子
# 1. 估算单请求大小 (Token Size)
self.ema_tokens = (1 - alpha) * self.ema_tokens + alpha * token_count
# 2. 估算 TPT (Time Per Token)
# 用 TPT 代替 Latency,消除 LLM 生成长度不同带来的误差
instant_tpt = latency / token_count
self.ema_tpt = (1 - alpha) * self.ema_tpt + alpha * instant_tpt
def track_inflight(self, estimated_tokens):
"""
[盲区填充] 修正"响应后才计数"的滞后性
请求发起瞬间,立即预扣额度
"""
self.inflight_tokens += estimated_tokens
Architectural fallback solutions
When platform configuration and client-side traffic control still cannot meet availability or peak throughput requirements, add fallback mechanisms at the architecture level.
Model fallback
When the primary model cannot respond due to rate limiting or service issues, automatically fall back to an alternative model with a more generous quota.
Fallback path design principles- Choose models from different series: Rate limiting is per-model. Use a different model as fallback — for example, fall back from
qwen3.6-plustoqwen3.6-flash. - Trigger fallback only on rate limit errors: Fall back on
429errors, not all exceptions. Switching models will not fix network timeouts or parameter errors. - Validate the fallback model in advance: Ensure it supports required features (Function Calling, structured output, etc.) to avoid functional issues after fallback.
Code example
The following example demonstrates model fallback logic based on the 429 error code. When a request to the primary model triggers rate limiting, it automatically switches to the fallback model for a retry.
import os
import asyncio
from openai import AsyncOpenAI, APIStatusError
# 主模型与备选模型(不同系列,独立配额)
PRIMARY_MODEL = "qwen3.6-plus"
FALLBACK_MODEL = "qwen3.6-flash"
client = AsyncOpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
async def chat_with_fallback(messages: list) -> str:
"""带降级的请求:主模型限流时自动切换备选模型。"""
for model in [PRIMARY_MODEL, FALLBACK_MODEL]:
try:
response = await client.chat.completions.create(
model=model,
messages=messages
)
return response.choices[0].message.content
except APIStatusError as e:
if e.status_code == 429 and model == PRIMARY_MODEL:
print(f"[限流触发] {model},降级至 {FALLBACK_MODEL}")
continue
raise
raise RuntimeError("所有模型均不可用")
async def main():
result = await chat_with_fallback(
messages=[{"role": "user", "content": "你好"}]
)
print(result)
if __name__ == "__main__":
asyncio.run(main())
Model fallback can be combined with client-side traffic control strategies. For example, you can integrate fallback logic into the retry mechanism of the request rate limiting strategy. When retries are exhausted and rate limiting is still triggered, switch to the fallback model.
Peak-load shifting using message queues (MQ)
For backend services that do not require immediate responses, introduce a message middleware (RabbitMQ, Kafka) for peak-load shifting. Burst traffic goes into the MQ first; consumers pull and process at a steady rate matching the rate limit quota. This decouples frontend peaks from backend calls.
Suitable for businesses where users accept asynchronous results: ticket processing, content moderation, batch data annotation.
Key design points:
- Consumer rate control: The consumer side should use the request rate limiting or traffic shaping strategy to consume messages at a steady rate based on the RPM/TPM quota, rather than pulling messages without limits.
- Dead-letter handling: Move messages that fail after multiple retries to a dead-letter queue and trigger an alert. Prevent infinite retries from blocking consumption.
- Back-pressure propagation: When the MQ backlog exceeds a threshold, propagate pressure upstream (for example, return a queuing status) to prevent unbounded queue growth.
Production environment considerations
The code examples use a Python asyncio single-threaded loop to demonstrate core algorithms. Before large-scale production use, consider the following.
-
Adapting to non-text models
The strategies above use text models as examples, but the core principles apply to multimodal services (image generation, speech synthesis). The units differ, but the essence is the same: limiting submission rate and processing capacity.
- Models such as speech recognition are typically constrained by both the number of requests per unit of time (such as RPM) and usage (such as audio duration). The strategies are basically the same as for text models.
- Models for images and videos are typically constrained by the task submission rate and the number of concurrent tasks. You can use the same approach as the request rate limiting strategy: limit the task submission rate and use a semaphore to control concurrency.
Regardless of how metrics change, the principle of client-side throttling stays the same. Replace the counter or probing metric with the one for your modality. For specific rules, see Rate limiting.
-
Atomicity in concurrent models
Example:
asynciouses single-threaded cooperative scheduling, so state modifications are inherently atomic within a single process.Production: In multi-threaded or multi-process environments, ensure concurrency safety of the token bucket and statistics window. Race conditions will break traffic control.
-
Distributed rate limiting
Example: All traffic control components are in-memory.
Production: In multi-instance deployments, each instance throttles independently. Total usage may exceed the limit. Use a centralized counter (such as Redis) to manage usage across all nodes.
-
Priority queues and starvation prevention
Example: No priority differentiation. The adaptive congestion control strategy uses non-strict FIFO wakeup for scheduling performance.
Production: For high/low priority requests, implement a weighted priority queue to guarantee bandwidth for high-priority traffic. Reserve a minimum quota for low-priority queues to prevent starvation.