I have a Node.js application and I am trying to use Redis cache to keep count of the amount of requests made. This is just a proof of concept to see if Redis is the right tool for me, but I am a bit disappointed by the outcome and I'm wondering if Redis is just performing really badly or if there is a flaw in my code.
I have the following code:
const express = require('express')
const Redis = require('ioredis')
const client = new Redis(6379, 'redis');
client.on('connect', function() {
console.log('Redis client connected');
});
client.on('error', function (err) {
console.log('Something went wrong ' + err);
});
const getRedisCount = async (question_id) => {
const count = await client.get('votes_' + question_id);
if(count) {
return count;
}
await setRedisCount(question_id, 0)
return 0;
}
const setRedisCount = async (question_id, count) => {
await client.set('votes_' + question_id, count)
}
const app = express();
app.use(express.json());
// post a vote
app.post('/vote', async (req, res) => {
let count = await getRedisCount(req.body.question_id)
count++
await setRedisCount(req.body.question_id, count)
res.status(200).send({ status: 200, data: count });
})
app.listen(5000, () => {
console.log('Vote service listening on port 5000')
})
Now this all works as expected when I just do a single post request in Postman. the counter updates as expected.
But when I run a test in JMeter where I do 150 requests at once, I get a count of around 20-30 after the last request, instead of the expected 150.
So my question is - is this expected behavior, or is this a fault in my code ? and in both cases - how to fix it ?