Transparent Caching Wrapper for Node

Eric Hacke
Webtips
Published in
2 min readJul 21, 2020

A simple transparent caching wrapper for Node. Wrap a function with it and call it normal. And the cache stays warm with background updates, so it’s always fast.

Available on GitHub

Previously I covered a more sophisticated caching solution for Firestore. However, you don’t always need something that complex.

Sometimes you just want an expensive function call to be cached for 5 or 10 minutes to reduce load. This is often the case for read-focused operations where it’s ok if the results are a little stale. Especially things like search results, image caching, certain computationally expensive operations, etc.

For that purpose, I built this transparent caching wrapper.

Features

  • The cache is periodically updated in the background without blocking the primary call. So it’s always fast.
  • Simplicity. Just wrap any function and it becomes cached on the next call.
  • Includes both local LRU cache and Redis cache levels. This improves speed and as a bonus minor network interrupts don’t effect serving from the local cache.

Use

In the most basic case, you can just supply the redis configuration, and then wrap the function.

Beyond that, you can specify global defaults for cache sizes and TTL.

And you can override any defaults at the moment the function is wrapped.

That’s it! A simple caching solution for read-heavy operations.

--

--