How to use Redis to improve response time with my Nodejs API? I am trying to use Redis to improve my response time but when it is taking longer than my normal api when i was not using Redis it was fetching data in 52-58ms on average but when i use Redis it is taking longer its taking 60-66ms in response time how to fix this problem i checked my location its all correct

How to improve response time?

const Redis = require('ioredis');
const redisClient = new Redis({
    port: 16545,
    host: 'redis-16545.c305.ap-south-1-1.ec2.cloud.redislabs.com',
    password: 'mypass',
});

router.get('/posts', async (req, res) => {
    try {
        const cacheKey = `posts:${req.query.page || 1}`;
        const cacheTTL = 60;
        const cachedData = await redisClient.get(cacheKey);
        if (cachedData) {
            console.log('Data fetched from Redis cache');
            return res.json(JSON.parse(cachedData));
        }
        const page = Number(req.query.page) || 1;
        const limit = Number(req.query.limit) || 50;
        const skip = (page - 1) * limit;
        const result = await User.aggregate([
            { $project: { posts: 1 } },
            { $unwind: '$posts' },
            { $project: { postImage: '$posts.post', date: '$posts.date' } },
            { $sort: { date: -1 } },
            { $skip: skip },
            { $limit: limit },
        ]);
        await redisClient.set(cacheKey, JSON.stringify(result), 'EX', cacheTTL);
        console.log('Data fetched from MongoDB and cached in Redis');
        res.json(result);
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Internal server error' });
    }
});

Comment From: zuiderkwast

I don't know but if your mongodb is installed locally (same machine as your web server and NodeJS) but redis is remote (redislabs.com), then maybe it is slower with redis due to network latency between your web server and redislabs server?