Ateş Göral
Ateş Göral

Reputation: 140050

Responding to Node client as soon as Redis key is available

On Node, I'm trying to send a response to the client as soon as a bit of data is available and to timeout and return a 404 if the data doesn't become available within the allotted period. The data comes in through another client request that can happen before or after the request that's waiting for the data.

My current attempt is to use Redis and do a RPUSH when the data comes in and do a BLPOP to wait for the data. It's not behaving as I would expect.

Using redis ~0.10.1, my code looks something like this:

Waiting side:

redisClient.blpop(key, 10, function (err, value) {
    if (!err && value) {
        res.send(value);
    } else {
        res.send(404);
    }
});

Setting side:

redisClient.rpush(key, 'something');
redisClient.expire(key, 30);

res.end();

My expectation is for the BLPOP callback to be called as soon as the RPUSH call is made. However, the BLPOP times out and I can only read the key on a subsequent request + call to BLPOP.

The first part of my question is about aligning my expectations with the actual expected behaviour of RPUSH/BLPOP on Node.

The second part of my question: I don't really have to use Redis. I'm just looking for any way to respond back to the client when an "event occurs" (in the most abstract sense). I'm open to suggestions for alternatives.

Upvotes: 0

Views: 1103

Answers (1)

mscdex
mscdex

Reputation: 106696

The redis protocol is generally synchronous, so the redis node client queues up requests and executes them in series. Try using different redis connections and you should get the expected results.

Upvotes: 1

Related Questions