HTTP Client
The NotPixel SDK includes a robust HTTP client with configurable timeout, retries, and exponential backoff.
Configuration
import Ads from 'notpixel';
const ads = new Ads({
publisherId: 'pub-xxx',
timeout: 2000, // 2 seconds (default: 1500ms)
retries: 3, // Retry up to 3 times (default: 0)
});Timeout
Set a maximum time for API requests:
const ads = new Ads({
publisherId: 'pub-xxx',
timeout: 1500, // milliseconds
});Default timeout is 1500ms. Increase this for slower networks or decrease for faster failure detection.
Environment Variable
NOTPIXEL_TIMEOUT_MS=2000Retries with Exponential Backoff
Enable automatic retries for transient failures:
const ads = new Ads({
publisherId: 'pub-xxx',
retries: 3, // Retry up to 3 times
});How Backoff Works
When a request fails, the SDK waits before retrying:
| Retry | Wait Time | Description |
|---|---|---|
| 1st | ~100ms | Base delay + jitter |
| 2nd | ~200ms | 2x previous + jitter |
| 3rd | ~400ms | 2x previous + jitter |
Request → Fail → Wait 100ms → Retry → Fail → Wait 200ms → Retry → SuccessRandom jitter is added to each delay to prevent “thundering herd” problems when many clients retry simultaneously.
Environment Variable
NOTPIXEL_RETRIES=3Error Handling
The SDK handles different HTTP errors appropriately:
| Status | Behavior |
|---|---|
2xx | Success |
400 | No retry (client error) |
401 | No retry (auth error) |
404 | No retry (not found) |
429 | Retry with backoff |
5xx | Retry with backoff |
| Network error | Retry with backoff |
Handling Errors
const ads = new Ads({
publisherId: 'pub-xxx',
retries: 3,
hooks: {
onError: (e) => {
console.error('Final error after retries:', e.error);
// Log to monitoring service
analytics.track('ad_error', { error: e.error, input: e.input });
},
},
});
// Use try-catch for explicit handling
try {
const ad = await ads.getAd({ input: 'query' });
} catch (error) {
// Handle error
console.error('Failed to fetch ad:', error);
}Best Practices
1. Set Appropriate Timeout
// Fast failure for real-time apps
const ads = new Ads({ publisherId: 'pub-xxx', timeout: 1000 });
// Longer timeout for batch processing
const batchAds = new Ads({ publisherId: 'pub-xxx', timeout: 5000 });2. Enable Retries for Production
const ads = new Ads({
publisherId: 'pub-xxx',
retries: 2, // Usually 2-3 is enough
});3. Combine with Caching
const ads = new Ads({
publisherId: 'pub-xxx',
cache: true, // Reduce API calls
retries: 2, // Retry on failure
timeout: 1500,
});4. Monitor with Hooks
const ads = new Ads({
publisherId: 'pub-xxx',
hooks: {
onAdFetched: (e) => {
metrics.histogram('ad_latency', e.latencyMs);
},
onError: (e) => {
metrics.increment('ad_errors');
},
},
});Request Deduplication
The HTTP client automatically deduplicates parallel requests for the same input. See Request Deduplication for details.