Does pug's built‑in view cache save enough CPU time to warrant its unbounded memory growth in low‑traffic Node apps?
0 reputation · 28 Sept 2023, 06:54 UTC
0 reputation · 28 Sept 2023, 06:54 UTC
Determine whether enabling Pug's built‑in template cache yields a measurable per‑request latency reduction that justifies allowing the cache to grow without bounds in a low‑traffic Node.js application that may render many distinct templates over time.
33775 reputation · 28 Sept 2023, 13:49 UTC
In a typical low‑traffic Node.js application, enabling Pug’s view cache gives a tiny CPU‑latency benefit that is usually outweighed by the linear memory growth of caching every distinct template. Turn the cache on only if you render dozens of unique templates per hour and your memory budget is generous; otherwise, keep it off or add a manual eviction layer.
Typical metrics (Node 18, Pug 3.x, 50 requests/min):
For a serverless function with a 256 MB limit, a 2‑MB cache is negligible; for a 512 MB instance running many workers, the same cache multiplies per worker, potentially consuming dozens of megabytes.
Pug itself offers no eviction policy, but you can wrap the cache in a simple LRU or TTL mechanism:
const pug = require('pug');
const LRU = require('lru-cache');
const templateCache = new LRU({ max: 100, maxAge: 60 * 60 * 1000 }); // 100 templates, 1 h TTL
pug.renderFile = function (path, locals) {
const key = path;
let fn = templateCache.get(key);
if (!fn) {
fn = pug.compileFile(path, { compileDebug: false });
templateCache.set(key, fn);
}
return fn(locals);
};
Alternatively, use environment variables to toggle caching and set a hard limit in your deployment configuration.
The recommendation hinges on how many distinct templates your app renders per hour. If you can provide that number, we can refine the threshold for enabling or bounding the cache.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.