Take the 2-minute tour ×

In Redis pub/sub if something is published when there is no subscriber, data is kind of lost.

What i wanted is kind of notification to publisher when subscriber is subscribed.

One way could be keep publishing in a loop and break the loop when publisher find at least one subscriber. But i don't think thats a good way. (Also i can't keep exponential back off).

while(1) {
    $numOfSubscriber = $redis->publish($channel1, $encodePublish);
    if($numOfSubscriber > 0)

Is there any better way to solve the same issue?

I am using Predis.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

It's hard to be specific unless you explain more about your usecase, but if it's enough that one subscriber gets any message, you could implement a queue using a redis list and store all messages there, while also publishing. Pseudo-code:


# Persist message in a queue
lpush channel1.queue message
# Publish message to any connected subscriber
publish channel1 message


# Subscribe to channel1
subscribe channel1
# Process any persisted messages
brpop channel1.queue

Edit: Another solution, where publisher only stores messages if there was no subscriber:


subscribers = publish channel1 message
if subscribers == 0
  lpush channel1.queue message


# handle stored messages
while(message = rpop channel1.queue)
  # process message

# subscribe for new messages
subscribe channel1
share|improve this answer
I do not want to really store any values, in my application what i care is when publisher is publishing there should be some subscriber to catch that message without putting publisher in a loop. If the subscriber starts after publisher than it might miss messages from publisher. –  amitchhajer Aug 14 '12 at 10:41
Yeah, that's why you could also store them, and let the subscriber pop them. Or you could push them only if there was no subscriber. But as I said, without more info on your case it's hard to give straightforward advice. –  Linus G Thiel Aug 14 '12 at 10:46
My use case is: i want to send acknowledgement to one of the worker to start working and push some data to queue's , if other worker (one sending the ack) is ready. So it sends the ack and worker receiving it starts pushing the data. Does that explain better? I am trying to explain my use case. One solution could be keeping one more set of pub/sub to control. –  amitchhajer Aug 14 '12 at 10:52
add comment

Your Answer


