CacheInterceptor TTL Expiration and Cache Stampede Prevention
29K reputation · 06 Oct 2023, 21:49 UTC
NestJS provides the CacheInterceptor to optimize response times by caching results based on a defined Time-To-Live (TTL). While this effectively reduces load for static or semi-static data, the default behavior triggers a cache miss immediately upon TTL expiration.
In high-throughput environments, this creates a risk where multiple concurrent requests for the same expired key bypass the cache simultaneously. This behavior can lead to a cache stampede, placing unexpected pressure on the underlying data provider or database until the first request repopulates the cache.
Given that CacheInterceptor does not natively implement a stale-while-revalidate pattern or request collapsing, how can the system be configured to prevent redundant provider calls during a TTL expiration event? Is there a recommended configuration to ensure only one request refreshes the cache while others receive a stale response?
1 answer
0 question comments
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.