Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use Redis to improve response time with my Nodejs API? I #12027

Open
johnvsmit31 opened this issue Apr 12, 2023 · 1 comment
Open

How to use Redis to improve response time with my Nodejs API? I #12027

johnvsmit31 opened this issue Apr 12, 2023 · 1 comment

Comments

@johnvsmit31
Copy link

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' });
    }
});
@johnvsmit31 johnvsmit31 changed the title [QUESTION] How to use Redis to improve response time with my Nodejs API? I Apr 12, 2023
@zuiderkwast
Copy link
Contributor

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants