feat(client): add handle429Backoff method for intelligent rate limit handling
Some checks failed
Default (tags) / security (push) Failing after 23s
Default (tags) / test (push) Failing after 14s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped

This commit is contained in:
2025-07-29 13:49:50 +00:00
parent 4cbca08f43
commit b4769e7feb
5 changed files with 115 additions and 28 deletions

View File

@@ -361,6 +361,69 @@ async function performMultipleRequests() {
}
```
### Rate Limiting (429 Too Many Requests) Handling
The library includes built-in support for handling HTTP 429 (Too Many Requests) responses with intelligent backoff:
```typescript
import { SmartRequest } from '@push.rocks/smartrequest';
// Simple usage - handle 429 with defaults
async function fetchWithRateLimitHandling() {
const response = await SmartRequest.create()
.url('https://api.example.com/data')
.handle429Backoff() // Automatically retry on 429
.get();
return await response.json();
}
// Advanced usage with custom configuration
async function fetchWithCustomRateLimiting() {
const response = await SmartRequest.create()
.url('https://api.example.com/data')
.handle429Backoff({
maxRetries: 5, // Try up to 5 times (default: 3)
respectRetryAfter: true, // Honor Retry-After header (default: true)
maxWaitTime: 30000, // Max 30 seconds wait (default: 60000)
fallbackDelay: 2000, // 2s initial delay if no Retry-After (default: 1000)
backoffFactor: 2, // Exponential backoff multiplier (default: 2)
onRateLimit: (attempt, waitTime) => {
console.log(`Rate limited. Attempt ${attempt}, waiting ${waitTime}ms`);
}
})
.get();
return await response.json();
}
// Example: API client with rate limit handling
class RateLimitedApiClient {
private async request(path: string) {
return SmartRequest.create()
.url(`https://api.example.com${path}`)
.handle429Backoff({
maxRetries: 3,
onRateLimit: (attempt, waitTime) => {
console.log(`API rate limit hit. Waiting ${waitTime}ms before retry ${attempt}`);
}
});
}
async fetchData(id: string) {
const response = await this.request(`/data/${id}`).get();
return response.json();
}
}
```
The rate limiting feature:
- Automatically detects 429 responses and retries with backoff
- Respects the `Retry-After` header when present (supports both seconds and HTTP date formats)
- Uses exponential backoff when no `Retry-After` header is provided
- Allows custom callbacks for monitoring rate limit events
- Caps maximum wait time to prevent excessive delays
## Platform-Specific Features
### Browser-Specific Options