| name | mistral-rate-limits |
| description | Implement Mistral AI rate limiting, backoff, and request management.
Use when handling rate limit errors, implementing retry logic,
or optimizing API request throughput for Mistral AI.
Trigger with phrases like "mistral rate limit", "mistral throttling",
"mistral 429", "mistral retry", "mistral backoff".
|
| allowed-tools | Read, Write, Edit |
| version | 1.0.0 |
| license | MIT |
| author | Jeremy Longshore <jeremy@intentsolutions.io> |
Mistral AI Rate Limits
Overview
Handle Mistral AI rate limits gracefully with exponential backoff and request management.
Prerequisites
- Mistral AI SDK installed
- Understanding of async/await patterns
- Access to rate limit headers
Instructions
Step 1: Understand Rate Limit Tiers
| Tier | Requests/min | Tokens/min | Tokens/month |
|---|
| Free | 2 | 500K | 1B |
| Production | 120 | 1M | 10B |
| Enterprise | Custom | Custom | Custom |
Note: Limits vary by model and are subject to change. Check console.mistral.ai for current limits.
Step 2: Implement Exponential Backoff with Jitter
interface RetryConfig {
maxRetries: number;
baseDelayMs: number;
maxDelayMs: number;
jitterMs: number;
}
async function withExponentialBackoff<T>(
operation: () => Promise<T>,
config: RetryConfig = {
maxRetries: 5,
baseDelayMs: 1000,
maxDelayMs: 60000,
jitterMs: 500
}
): Promise<T> {
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
try {
return await operation();
} catch (error: any) {
if (attempt === config.maxRetries) throw error;
const status = error.status;
if (status !== 429 && (status < 500 || status >= 600)) throw error;
const retryAfter = error.?.[];
: ;
(retryAfter) {
delay = (retryAfter) * ;
} {
exponentialDelay = config. * .(, attempt);
jitter = .() * config.;
delay = .(exponentialDelay + jitter, config.);
}
.();
( (r, delay));
}
}
();
}
response = (
client..({
: ,
: [{ : , : }],
})
);
Step 3: Token-Based Rate Limiting
class TokenRateLimiter {
private tokensUsed = 0;
private windowStart = Date.now();
private readonly tokensPerMinute: number;
private readonly windowMs = 60000;
constructor(tokensPerMinute = 500000) {
this.tokensPerMinute = tokensPerMinute;
}
async waitForCapacity(estimatedTokens: number): Promise<void> {
const now = Date.now();
const elapsed = now - this.windowStart;
if (elapsed >= this.windowMs) {
this.tokensUsed = 0;
this.windowStart = now;
}
if (this.tokensUsed + estimatedTokens > this.tokensPerMinute) {
const waitTime = this. - elapsed;
.();
( (r, waitTime));
. = ;
. = .();
}
}
(: ): {
. += tokensUsed;
}
}
rateLimiter = ();
(): <> {
estimatedTokens = .(messages). / ;
rateLimiter.(estimatedTokens + );
response = client..({
: ,
messages,
});
(response.) {
rateLimiter.(response.. || );
}
response.?.[]?.?. ?? ;
}
Step 4: Request Queue with Concurrency Control
import PQueue from 'p-queue';
const requestQueue = new PQueue({
concurrency: 5,
interval: 1000,
intervalCap: 10,
});
async function queuedRequest<T>(operation: () => Promise<T>): Promise<T> {
return requestQueue.add(async () => {
return withExponentialBackoff(operation);
});
}
const results = await Promise.all(
prompts.map(prompt =>
queuedRequest(() =>
client.chat.complete({
model: 'mistral-small-latest',
messages: [{ role: 'user', content: prompt }],
})
)
)
);
Step 5: Rate Limit Monitor
class RateLimitMonitor {
private requestCount = 0;
private lastReset = Date.now();
private readonly alertThreshold: number;
constructor(alertThreshold = 0.8) {
this.alertThreshold = alertThreshold;
}
recordRequest(): void {
const now = Date.now();
if (now - this.lastReset >= 60000) {
this.requestCount = 0;
this.lastReset = now;
}
this.requestCount++;
}
checkThreshold(maxRequests: number): void {
if (this.requestCount / maxRequests > this.alertThreshold) {
console.warn(`Rate limit warning: ${this.requestCount}/${maxRequests} requests used`);
}
}
getStats(): { requestCount: ; : } {
{
: .,
: - (.() - .),
};
}
}
Output
- Reliable API calls with automatic retry
- Token-based rate limiting
- Request queue with concurrency control
- Rate limit monitoring
Error Handling
| Header | Description | Action |
|---|
| Retry-After | Seconds to wait | Honor this value |
| X-RateLimit-Limit | Max requests | Monitor usage |
| X-RateLimit-Remaining | Remaining requests | Throttle if low |
| X-RateLimit-Reset | Reset timestamp | Wait until reset |
Examples
Python Rate Limiting
import time
import asyncio
from mistralai import Mistral
async def with_retry(client, max_retries=3):
for attempt in range(max_retries):
try:
return await client.chat.complete(
model="mistral-small-latest",
messages=[{"role": "user", "content": "Hello"}]
)
except Exception as e:
if hasattr(e, 'status') and e.status == 429:
delay = (2 ** attempt) + (random.random() * 0.5)
print(f"Rate limited. Waiting {delay:.1f}s...")
await asyncio.sleep(delay)
else:
raise
raise Exception("Max retries exceeded")
Batch Processing with Rate Limiting
async function processBatch<T, R>(
items: T[],
processor: (item: T) => Promise<R>,
batchSize = 5,
delayMs = 1000
): Promise<R[]> {
const results: R[] = [];
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
const batchResults = await Promise.all(
batch.map(item => withExponentialBackoff(() => processor(item)))
);
results.push(...batchResults);
if (i + batchSize < items.length) {
await new Promise(r => setTimeout(r, delayMs));
}
}
return results;
}
Resources
Next Steps
For security configuration, see mistral-security-basics.