I've written a simple service using redis to store data in memory or fetch from disc and then store in memory and want to set a timeout for slow requests. I'm hoping to find a way make a get request with a timeout to prevent this a request from hanging. Any help is appreciated.
2 Answers
So, there are a few things you can do here. But, first I wonder if you are attempting premature optimization. Redis in most normal situations is blazingly fast, and if you are finding performance issues on the client, then that indicates that you have some issues with your data or how you are processing it in redis. This should be fixed this in redis, there is nothing you should do in your client to handle slow requests.
So, if you are seeing occasional slowdowns, what are they coming from? This is not a normal redis issue, and should be addressed instead of looking for a javascript fix.
If you are still looking for a javascript fix, you could do something like this:
const client = require('redis').createClient(...);
export async function asyncSetEx(key) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error('Timed out'));
});
client.setEx(key, (res, err) => {
if (err) {
reject(err);
} else {
resolve(res);
}
clearTimeout(timer);
});
});
}
Though, I'd recommend generalizing this so that it works for any redis function with any number of parameters.

- 28,387
- 9
- 92
- 148
prevent this a request from hanging
If you set enable_offline_queue
to false
, all Redis commands will throw an exception immediately instead of waiting to reconnect. You can then catch that exception and do your fetching from disc or some DB.
Couldnt find anything in the documentation regarding this and found many such questions here on SO, hence posting in this old question.
Do keep in mind that, with enable_offline_queue
set to false, the commands that you issue while there's some connection issue with the server will never be executed.

- 885
- 2
- 14
- 31