Статья ещё не опубликована на языке Russian. Показана версия на English.
Rate Limiting, Token Buckets, and Provider Circuit Breakers for Outbound Messaging
Опубликовано
2 мин на чтение
Sending outbound messages faster than a messaging provider or recipient tier allows triggers 429 throttling, degraded account quality scores, and temporary sender restrictions. Production dispatchers combine proactive pacing (token buckets) with reactive protection (provider circuit breakers).
Rate Limiting Algorithms Compared
| Algorithm | Behavior | Burst Handling | Best For |
|---|---|---|---|
| Fixed Window | Counts requests per clock minute | Vulnerable to 2x boundary spikes | Simple coarse API quotas |
| Sliding Window Log | Tracks timestamps in rolling window | Accurate, higher memory | Strict per-user abuse protection |
| Token Bucket | Refills tokens at steady rate up to burst cap | Smooth steady throughput + controlled bursts | Outbound messaging per phone number / tenant |
Separating Throughput Errors From Account Restrictions
A critical operational distinction in messaging platforms:
- Transient throughput errors (too many requests per second): slow down the token bucket smoothly; do not latch a permanent circuit breaker or mark the sender account broken.
- Hard sender/account policy errors (payment method failed, account suspended, template paused): trip the circuit breaker immediately for that sender scope so you do not hammer 10,000 remaining recipients into a guaranteed failure storm.
ts
export type CircuitState = "closed" | "open" | "half_open";
export class ScopedCircuitBreaker {
private state: CircuitState = "closed";
private consecutiveHardFailures = 0;
private openedUntilMs = 0;
constructor(
private readonly failureThreshold = 5,
private readonly cooldownMs = 60_000
) {}
canProceed(nowMs = Date.now()): boolean {
if (this.state === "closed") return true;
if (nowMs >= this.openedUntilMs) {
this.state = "half_open";
return true;
}
return false;
}
recordSuccess(): void {
this.state = "closed";
this.consecutiveHardFailures = 0;
}
recordHardFailure(nowMs = Date.now()): void {
this.consecutiveHardFailures += 1;
if (this.consecutiveHardFailures >= this.failureThreshold) {
this.state = "open";
this.openedUntilMs = nowMs + this.cooldownMs;
}
}
}
Next: coordinate thousands of concurrent sends safely without exhausting memory or DB pools in Fan-Out / Fan-In Batch Processing and Backpressure.
Было ли это полезно?