Showing posts with label RabbitMQ. Show all posts
Showing posts with label RabbitMQ. Show all posts

Saturday, 14 February 2015

Delay or Scheduled Message Delivery with RabbitMQ

In this tutorial,i will show you the logic of Delay or Scheduled message delivery with RabbitMQ. And  how to implement it through java. For Real world example/usecase of RabbitMQ,please go through this article.

Sometimes you don’t want messages in the queue to be read or delivered immediately. For example, while processing fax message if it fail due to network error,then no meaning of immediate retry,hence delay in this type of scenario will be useful.Fortunately, RabbitMQ 2.8+ introduced Dead Letter Exchanges (DLX), which allows us to simulate message scheduling.

In practice, if we wanted to enable retry on failure every 3 minutes, the flow would look like this:
  1. Create Work Queue and bind it to Work Exchange.
  2. Create Delay Queue and bind it to Delay Exchange.
  3. Set x-dead-letter-exchange to Work Exchange.
  4. Set x-message-ttl to 180000 ms (3 minutes) to Delay Queue .
  5. Publish message to Work Queue.
  6. Client reads message from Work Queue and attempts to process it.
  7. If the message processing fails and client publishes to Delay Queue.
  8. Messages stays in Delay Queue for 3 minutes.
  9. When message ttl expires, it is re-queued to Work Queue via Work Exchange for another attempt at processing.
  10. Repeat steps 4-7


Create the Work Queue:

private String WORK_QUEUE = "WorkQueue";
private String WORK_EXCHANGE = "WorkExchange"; 

//Create your connection factory for getting connection and channel
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

//declare Work Exchange and Work Queue,finally bind Work Queue to Work Exchange 
channel.exchangeDeclare(WORK_EXCHANGE, "direct", true);
channel.queueDeclare(WORK_QUEUE, true, false, false, null);
channel.queueBind(WORK_QUEUE, WORK_EXCHANGE,"RK", null);


Create the Delay Queue:

private String DELAY_QUEUE ="DelayQueue";
private String DELAY_EXCHANGE = "DelayExchange";

//Make Delay Queue's Dead Letter Exchange to Work Exchange,so that after message ttl expires the message are sent to Work Queue via Work Exchange.

Map<String, Object> args = new HashMap<String, Object>();
args.put("x-dead-letter-exchange", WORK_EXCHANGE);
args.put("x-message-ttl", 180000);
//declare Delay  Exchange and Delay Queue,finally bind Delay Queue to Delay Exchange 
channel.exchangeDeclare(DELAY_EXCHANGE, direct, true);
channel.queueDeclare(DELAY_QUEUE, true, false, false,args);
channel.queueBind(DELAY_QUEUE, DELAY_EXCHANGE, "RK", null);


Read from Work Queue:

QueueingConsumer consumer = new QueueingConsumer(channel);
 channel.basicConsume(WORK_QUEUE, true, consumer);

    while (true) {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery();
      String message = new String(delivery.getBody());
         if (!processSomething(message)) {
        processLater(message);
    }
   }


Publish to Delay Queue on message processing failure:

String message = new String(delivery.getBody());
channel.basicPublish(DELAY_EXCHANGE, "", null, message.getBytes());


Notes:
It's worth mentioning that Delay Queue mechanishm gurantee that the message will be delivered atleast after the delay time,but not exactly after delay time is over.

Real World Example of RabbitMQ - Universal Message Queue

Last year i was developing a message queue based application  for our company to be used by different other products/application.Since it's purpose was to be very scalable and also to be used by various other application, so we named it Universal Message Queue (UMQ).

Why UMQ came to the picture?

Earlier database was used as queue for certain scenario. But Database is not a good choice for huge queuing functionality. A heavy loaded database with additional queuing functionality will affect the performance of an application. Database should not be used for queuing purpose because of following:


  •  Database inherently does not support queue functionality
  •  Using Database as queue increases load on the database, hence affect the overall application performance. 
  • Implementing some new functionality of queue (such as priority, Delay, Tracking etc) through database are complex and not well proven.

To overcome the above issues, UMQ is good choice. UMQ is a generalized message queue system.
It is based on rest services. Beside eliminating the issues of database as a queuing system, UMQ
has the important additional features that are useful in different scenario for various application as
stated below.


Some of the major components  that were used for the UMQ are RabbitMQ and Redis.

Truly speaking we have done lots of poc & rnd with various opensource message Queue's before developing this internal product,but RabbitMQ was able to full-fill our above needs very well.

Some of the fetaures of RabbitMQ are very well, like Routing logic based on Exchange and Queue mechanism, Prioity(through its Plugin) ,Negative Acknowledgement(NACK) with/without  Requeing and Delay or Schedule Message delivery.

So in the next tutorial,i will give you the idea of Delay/Schedule message delivery along with how to implement the logic through java. 

Sunday, 3 August 2014

ActiveMQ vs RabbitMQ vs ZeroMQ vs Apache Qpid vs Kafka vs IronMQ -Message Queue Comparision

What are Message Queues[MQ]?

Message Oriented Middleware or MOM concept involves the exchange of data between different applications using messages asynchronously. Using this mechanism, applications are decoupled and senders and receivers exist without the knowledge of each other. It becomes the responsibility of the messaging system (Message Oriented Middleware) to transfer the messages between applications. Queues allow you to store metadata for processing jobs at a later
date. They can aid in the development of SOA (service-oriented architecture) by providing the flexibility to defer tasks to separate processes. When applied correctly, queues can dramatically increase the user experience of a web site by reducing load times.



Advantages of message queues:
•Asynchronous: Queue it now, run it later.
•Decoupling: Separates application logic.
•Resilience: Won't take down your whole application if part of it fails.
•Redundancy: Can retry jobs if they fail.
•Guarantees: Makes sure that jobs will be processed.
•Scalable: Many workers can process individual jobs in a queue.



Use cases of message queues:
•Sending/receiving data from a third-party APIs
•Communication between various application asynchronously
•Sending an e-mail, Uploading documents
•Running labour intensive processes

JMS vs AMQP
AMQP is an application-level standard for Message Oriented Middleware (MOM). JMS is a standard API for Java for communicating with MOM.
Two different Java applications using JMS could be using different MOM and hence still be unable to communicate. ActiveMQ is a MOM system with a JMS library that allows Java programs to access it using JMS, but it can't necessarily communicate with another JMS Java program using, say, WebLogic MOM.
Different AMQP MOM systems can interoperate with each other (assuming that they are using the same version of AMQP) since AMQP is a standard along the same lines as, say SMTP. There is no reason that an AMQP MOM system could not also provide a JMS library for its Java clients.


OpenSource Message Queue

1. RabbitMQ is one of the leading implementation of the AMQP protocol (along with ApacheQpid). Therefore, it implements a broker architecture, meaning that messages are queued on a central node before being sent to clients. This approach makes RabbitMQ very easy to use and deploy, because advanced scenarios like routing, load balancing or persistent message queuing,Negetive Ackowledgement(NACK), Requeing and Delay or Schedule messaging are supported in just a few lines of code. However, it also makes it less scalable and “slower” because the central node adds latency and message envelopes are quite big.

2. Apache ActiveMQ is the most popular and powerful open source messaging and Integration Patterns server.Supports many advanced featuressuch as Message Groups, Virtual Destinations, Wildcards and Composite Destinations.It makes for a reliable hub in any message-oriented enterprise application and integrates beautifully with Java EE containers,ESBs, and other JMS providers
ActiveMQ Apollo is a faster, more reliable, easier to maintain messaging broker built from the foundations of the original ActiveMQ- a new Gen ActiveMQ. It accomplishes this using a radically different threading and message dispatching architecture. Like ActiveMQ, Apollo is a multi-protocol broker and supports STOMP, AMQP, MQTT, Openwire, SSL, and WebSockets.

3. ZeroMQ is a very lightweight messaging system specially designed for high throughput/low latency scenarios like the one you can find in the financial world. Zmq supports many advanced messaging scenarios but contrary to ActiveMQ/RabbitMQ, you’ll have to implement most of them yourself by combining various pieces of the framework (e.g : sockets and devices).ZeroMQ is a lightweight message orientated socket implementation. It is also suitable
for in-process asynchronous programming. It is possible to run a "Enterprise Messaging System" over ZeroMQ, but you would have to implement a lot on your own.

4. Kafka is a high throughput distributed messaging system.Written and used by LinkedIn to offload processing of all page and other views .Defaults to using persistence, uses OS disk cache for hot data (has higher throughput then any of the above having persistence enabled).Supports both on-line as off-line processing.Kafka does work on the push - pull basic and capable of handling large scale real time streams.

5. Apache Qpid, an open-source messaging system, implements the Advanced Message Queuing Protocol. It provides transaction management, queuing, distribution, security,management, clustering, federation and heterogeneous multi-platform support.

6. IronMQ is an easy-to-use highly available message queuing service. It is available as a cloud service on Amazon and Rackspace as well as on-premise with Iron.io's enterprise offering.Features include a nice dashboard to manage queues, easy to create webhooks, unicast and multicast Push Queues, autoscaling alerts for worker processes, and error queues.An easy-to-
use highly available message queuing service. Built for distributed cloud applications with critical messaging needs. Provides on-demand message queuing with HTTPS transport, one-time FIFO delivery, message persistence,and cloud-optimized performance.


Message Queue Comparison



BenchMark / Performance

• ActiveMQ (https://activemq.apache.org/benchmark-tests.html)

• Apollo (http://activemq.apache.org/apollo/documentation/performance-scaling.html)


• RabbitMQ (http://www.rabbitmq.com/blog/)


• ZeroMQ (http://zeromq.org/results:ib-tests-v206)


• Apache Qpid (http://qpid.apache.org/releases/qpid-0.20/)


• Kafka (https://kafka.apache.org/07/performance.html)


Conclusion
• ActiveMQ or Apollo is simply the leader when it comes to ease of configariton and different persistentstore, at the cost of performance in persistence mode.ApacheMQ and Apache Qpid seems to bevery good among broker based MQ at performing without persistence.Apollo is better in terms of performance and reliability than ActiveMQ /Apache Qpid.

•Just like other brokers based MQ, RabbitMQ is is best sutable for advance messaging pattren having routing,load balancing.However, it also makes it less scalable and “slower” because the central node adds latency and message envelopes are quite big. However even in persistent mode RabbitMQ performs better than ActiveMQ or Apache Qpid.

• ZeroMQ broker outperforms all others for simple messaging pattern between application. This means that unless you have a need for complex broker features,ZeroMQ is a perfect message dispatcher among processes.If you want one application to send messages to another as quickly as possible, you need ZeroMQ.Its crazy fast for transient message.

•Kafka does work on the push - pull basic and capable of handling large scale real time streams.It also provide ordered message delivery.Kafka's performance is effectively constant with respect to data size so retaining lots of data will not be a problem.Kafka is ideal if you are looking for reliable distributed messaging system with good throughput.Kafka is used at LinkedIn and it handles over 10
billion message writes per day with a sustained load that averages 172,000 messages per second.

•IronMQ is good in case of distributed cloud based queueing.It integrates with application running in Amazon or Rackspace,but its commercial.

Related Article:

  1. Real World  Example of RabbitMQ
  2. Delay or Scheduled Message with RabbitMQ