Design Patterns – Best Way to Send Messages to Multiple Subscribers

design-patterns

I'm writing an application in which –

Many users can subsribe to posts made by another users.

So for a single publisher there can be many subscribers.

When a message is posted by an user X, all users who have subscribed to messages of User X will be sent an email.

How to achieve this ? I'm thinking of using publish-subscribe pattern.

And then I came through JMS. Which is the best JMS implementation to use according to your experience ?

Or else what else solution do you propose to the given problem ?

Shall I go for a straight-forward solution ?:
User x posts a message, I find all users (from database) who subscribe to user x
and then for every user, I call the sendEmail() method.

[EDIT]
My intention here is not to send-emails. I'm really sorry if it wasn't clear.
I also have to send kind of system-notifications apart from Email to all subscribers.

Right now, I've implemented the email-sending as a threadPool

Best Answer

Hope you are not looking for a platform specific solution

If Yes, your requirement highlights a pub/sub pattern. I handled the same using RabbitMQ which has specific support for Pub/Sub scenario.

Without going in to granular details, to give you an idea on RabbitMQ's pub/sub model

It has something called "exchange" in addition to "producer","queue", & "consumer"

The core idea on this messaging model is that the producer never sends any messages directly to a queue. A quite often the producer doesn't even know if a message will be delivered to any queue at all. The producer can only send messages to an exchange. An exchange receives messages from producers and the other side it pushes them to queues.

It supports different exchange types to satisfy your various needs - direct, topic, headers and fanout.

This means greater flexibility to de-couple core MQ functionality from the business logic, which you may want to impose on message formats/delivery/retry logic

I used "topic" exchange type which supports message routing/filtering just by looking at message name/title.

To give you a best use of this logic - I had a weird requirement (on pub/sub model) to maintain the list of active subscribers , which I managed to get it done by introducing a heartbeat (topic based) message on the same queue

For the said reasons, and high accuracy on message delivery, and good performance results of supported AMQP protocol, I felt quite happy about my choice

Disclaimer : I am not advocating here that RabbitMQ is the only choice, but sharing this as my nice experience with a smart solution. There are quite few pub/sub solutions out there in the market.

I also found WAMP interesting while exploring various options,but didn't use it for any commercial implementation

Related Topic