Search code examples
node.jsexpressredis

Redis take much time to retrieve data


I am working on node.js project. I start using Redis for cache data by upstash. and it needs more time to retrieve data then without redis. when I am using redis.get() or redis.set() it needs too much time.

const Redis = require('ioredis')
const redis = new Redis(REDIS_URL);

router.get('/', async (req, res) => {
    try {

        const redisProduct = await redis.get('products');
        if(redisProduct) {
            console.log("returned from redis")
            const products = JSON.parse(redisProduct)
            return res.render('products', { products })
        }
        const products = await productSchema.aggregate([
            {
                $sort: { createdAt: -1 }
            }
        ])
        await redis.set('products', JSON.stringify(products), 'EX', 300)
        console.log('quaried from database and set to the redis')
        return res.render('products', { products })
    } catch(error) {
        console.log('Error: ' + error)
        res.status(404).send('Something went wrong')
    }
})

Solution

  • 500 ms is half a second, that's extremely fast. Your db query without caching is only so fast because you are still setting up and have not acquired a large amount of data to query. If you know you will never have a large amount of data you do not need a caching service. I am pretty sure this is how it is all intended to work. Hope that is helpful to you.