Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to cache in Node.js

I am trying to find the best caching solution for a node app. There a few modules which can manage this. Most popular being: https://www.npmjs.com/package/node-cache

But I found that responses are faster if I just save some results into a variable like:

var cache = ["Kosonsoy","Pandean","Ḩadīdah","Chirilagua","Chattanooga","Hebi","Péruwelz","Pul-e Khumrī"];

I can then update that variable on a fixed interval, is this also classed as caching? Are there any known issues/problems to this method. As it defiantly provides the fastest response times.

like image 398
wazzaday Avatar asked Dec 21 '14 14:12

wazzaday


People also ask

How do I store cache in NodeJS?

const express = require('express'); const fetch = require('node-fetch'); const NodeCache = require('node-cache'); // stdTTL is the default time-to-live for each cache entry const myCache = new NodeCache({ stdTTL: 600 }); // retrieve some data from an API async function getPosts() { const response = await fetch(`https ...


2 Answers

Of course it is faster as you use local memory to store the data. For limited cache size this is good, but can quickly eat up all your process memory.

I would advise to use modules as there is a considerable amount of collaborative brainpower invested in them. Alternatively you can use a dedicated instance to run something like Redis to use as cache.

Alternatives aside, if you would stick with your solution I recommend small improvement.

Instead of

var cache = ["Kosonsoy","Pandean","Ḩadīdah","Chirilagua","Chattanooga","Hebi","Péruwelz","Pul-e Khumrī"];

try using objects as key value storage.

This will make searching and updating entries faster.

var cache = {"Kosonsoy":data,"Pandean":moreData,...};

Searching in array requires iterations while accessing the object is as simple as

var storedValue = cache["Kosonosoy"];

saving

cache[key] = value;
like image 107
swogger Avatar answered Oct 17 '22 11:10

swogger


If you use many workers you will have a duplicated cache for each one because they have no shared memory.

Of course, you can use it for small data. And keeping a data in a variable for an amount of time can be called caching for me.

like image 2
Gnucki Avatar answered Oct 17 '22 10:10

Gnucki