Gathering detailed insights and metrics for auto-fetch-fifo-ttl-cache
Gathering detailed insights and metrics for auto-fetch-fifo-ttl-cache
Gathering detailed insights and metrics for auto-fetch-fifo-ttl-cache
Gathering detailed insights and metrics for auto-fetch-fifo-ttl-cache
An in-memory FIFO cache with fixed TTL for Node.js, designed to streamline the common get-or-fetch pattern by automating value retrieval. It uses an internal keyed lock to coalesce concurrent fetches for the same key, reducing redundant network calls and eliminating synchronization overhead for developers.
npm install auto-fetch-fifo-ttl-cache
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (99.44%)
JavaScript (0.56%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
Apache-2.0 License
1 Commits
1 Watchers
1 Branches
1 Contributors
Updated on Apr 26, 2025
Latest Version
1.0.0
Package Id
auto-fetch-fifo-ttl-cache@1.0.0
Unpacked Size
86.68 kB
Size
19.58 kB
File Count
19
NPM Version
10.9.2
Node Version
20.13.1
Published on
Apr 26, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
2
6
An in-memory FIFO cache with fixed TTL for Node.js, designed to streamline the common get-or-fetch pattern by automating value retrieval. It uses an internal keyed lock to coalesce concurrent fetches for the same key, reducing redundant network calls and eliminating synchronization overhead for developers.
Special emphasis is given to graceful teardown: The ability to await the completion of all active fetch attempts - particularly during application shutdown - makes it ideal for production environments requiring seamless resource cleanup.
getOrFetch
method streamlines the common get-or-fetch pattern, allowing developers to focus on core business logic. A value is fetched only if the key is missing or has expired; otherwise, the cached value is returned.getOrFetch
calls are made concurrently for the same missing key, only one fetch operation is executed. All callers await the same in-flight promise, reducing unnecessary network traffic and minimizing the risk of rate-limiting or throttling errors.waitForActiveFetchesToComplete
method. Example use cases include application shutdowns (e.g., onModuleDestroy
in NestJS applications) or maintaining a clear state between unit-tests.Map
maintains the insertion order of keys, offering a reliable and often overlooked guarantee for iteration. The underlying fifo-ttl-cache package leverages this guarantee to eliminate the need for manually managing insertion order during evictions.The AutoFetchFIFOCache
class provides the following methods:
fetchValue
function, stored in the cache, and then returned.onModuleDestroy
in NestJS applications) or maintaining a clear state between unit tests. This need is especially relevant in Kubernetes ReplicaSet deployments. When an HPA controller scales down, pods begin shutting down gracefully.If needed, refer to the code documentation for a more comprehensive description of each method.
The AutoFetchFIFOCache
class provides the following getter methods to reflect the current activity state:
getOrFetch
calls that are awaiting a fetch operation for keys that are not already in the cache.Intrusion detection systems often cache reputation data for IP addresses from a remote threat intelligence API. Threat intel lookups are expensive (latency, rate limits, cost), so caching improves performance and reduces load.
IP addresses tend to exhibit short-term behavioral consistency (e.g., a botnet or scanner using an IP will often keep using it for hours or days). In other words, IP ownership or usage can shift rapidly, especially with cloud providers or DHCP. Therefore, TTL must be short (e.g., minutes to a few hours).
The following IPRiskAssessor
component encapsulates both fetching and caching of IP risk assessments. This abstraction adheres to the single-responsibility principle, and facilitates unit testing by making the external dependency easy to mock:
1import { 2 IAutoFetchFIFOCacheOptions, 3 AutoFetchFIFOCache 4} from 'auto-fetch-fifo-ttl-cache'; 5 6const CACHE_CAPACITY = 2048; 7const CACHE_TTL_MS = 1000 * 60 * 5; 8 9interface IReputationInfo { 10 riskLevel: 'low' | 'medium' | 'high'; 11 categories: string[]; 12 lastUpdated: Date; 13} 14 15class IPRiskAssessor { 16 private readonly _ipToRiskCache: AutoFetchFIFOCache<IReputationInfo>; 17 18 constructor() { 19 const options: IAutoFetchFIFOCacheOptions = { 20 capacity: CACHE_CAPACITY, 21 ttlMs: CACHE_TTL_MS, 22 fetchValue: this._fetchFromThreatIntel.bind(this) 23 // Alternatively, define the value fetcher using an arrow function: 24 // (ip: string): Promise<ReputationInfo> => this._fetchFromThreatIntel(ip) 25 }; 26 this._ipToRiskCache = new AutoFetchFIFOCache<IReputationInfo>(options); 27 } 28 29 public async getReputation(ip: string): Promise<IReputationInfo> { 30 const reputationInfo = await this._ipToRiskCache.getOrFetch(ip); 31 return reputationInfo; 32 } 33 34 private async _fetchFromThreatIntel(ip: string): Promise<ReputationInfo> { 35 // Simulate a remote fetch; in real life, call an external API here. 36 } 37}
If the fetcher throws or returns a rejected promise, the corresponding getOrFetch
call will also reject, and no value will be cached for the key. This behavior mirrors the manual workflow of fetching a value before explicitly storing it via set
, allowing developers to retain full control over error-handling strategies.
The cache remains agnostic to how errors should be handled. If desired, the fetcher itself may implement fallback logic - such as returning a default value or a sentinel object representing failure - depending on the needs of the application.
Unlike the widely used LRU Cache, a FIFO Cache does not prioritize keeping popular keys cached for extended durations. This simplicity reduces implementation overhead and generally offers faster response times. FIFO caches are particularly well-suited for scenarios where:
No vulnerabilities found.
No security vulnerabilities found.