Caching
NotPixel includes an in-memory cache with TTL (Time-To-Live) to reduce API calls and improve performance.
Enable Caching
import Ads from 'notpixel';
const ads = new Ads({
publisherId: 'pub-xxx',
cache: true,
});Custom Configuration
You can customize the cache behavior:
const ads = new Ads({
publisherId: 'pub-xxx',
cache: {
ttlMs: 300000, // 5 minutes (default: 5 min)
maxSize: 100, // max entries (default: 100)
},
});Cache API
Access cache statistics and management:
// Get cache stats
const stats = ads.cache.stats();
console.log(stats);
// { size: 10, hits: 50, misses: 5, hitRate: 0.91 }
// Clear all cached entries
ads.cache.clear();
// Remove expired entries only
ads.cache.cleanup();Cache is keyed by input text, so identical queries will return cached results within the TTL window.
How It Works
- When you call
ads.getAd(), the SDK checks if a cached response exists for that input - If found and not expired, returns the cached ad immediately
- If not found or expired, fetches from API and caches the result
- Cache automatically evicts oldest entries when
maxSizeis reached
Best Practices
- Enable caching for high-traffic applications to reduce latency
- Adjust
ttlMsbased on how often your ad inventory changes - Monitor
hitRateto ensure caching is effective - Call
cleanup()periodically in long-running processes