DEV Community

Cover image for Supercharge Your Node.js App with Blazing Fast In-Memory Caching!
shubham paul
shubham paul

Posted on

3

Supercharge Your Node.js App with Blazing Fast In-Memory Caching!

Introduction

If you’re experiencing latency issues in your Node.js application, implementing in-memory caching can be a game-changer. This guide will walk you through how to set up in-memory caching using node-cache in an Express.js server to significantly improve your API performance.

The Challenge

We recently saw a rapid increase in our backend project, reaching over 1000 active users in just 5 days. However, this spike led to latency issues, with API calls averaging around 200ms. Initially, we used Redis for caching, but latency remained between 180-200ms because our Redis instance and main server were both in the US-West region, while our users were primarily in India.

To address this, we implemented in-memory caching on the server, reducing latency by approximately 60%.

Here's how to implement in-memory caching using Node.js and Express.js:

- Install the node cache package

npm install node-cache

- Setup your Cache

const NodeCache = require('node-cache');
const myCache = new NodeCache({ stdTTL: 100, checkperiod: 120 });

// stdTTL is the default time-to-live for cache entries (in seconds)
// checkperiod is the interval for automatic cache cleaning (in seconds)

Enter fullscreen mode Exit fullscreen mode

- Implement in the express js server

const express = require('express');
const app = express();

// Example data fetching function
async function fetchDataFromDatabase() {
    // Simulate a database call
    return { data: 'This is some data from the database.' };
}

app.get('/data', async (req, res) => {
    const cacheKey = 'myDataKey';
    const cachedData = myCache.get(cacheKey);

    if (cachedData) {
        return res.json({ source: 'cache', data: cachedData });
    }

    const data = await fetchDataFromDatabase();
    myCache.set(cacheKey, data);
    res.json({ source: 'database', data });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Enter fullscreen mode Exit fullscreen mode

- Manage your cache

// Get cache statistics
console.log(myCache.getStats());

// Manually delete a cache entry
myCache.del('myDataKey');

// Flush the entire cache
myCache.flushAll();

Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Try REST API Generation for Snowflake

DevOps for Private APIs. Automate the building, securing, and documenting of internal/private REST APIs with built-in enterprise security on bare-metal, VMs, or containers.

  • Auto-generated live APIs mapped from Snowflake database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay