The labs on this site need JavaScript to run. The same content is written out below.
Fundamentals › Architecture and operations
Message queues
What is a message queue, and how is it different from calling a server directly?
Why it exists — If one server gives work directly to another server, it has to wait until the other finishes, and if the other is down, the work fails and is not processed unless someone sends it again. A message queue holds the work to be done as messages between the two servers, so that the sending side can hand off work regardless of whether the receiving side is running now or how busy it is.
Where it's used today — It is used to hand off work that takes time but need not be answered right away, such as a notification email or text message sent after an order is finished, or the conversion of an uploaded video. In real services, a message broker such as RabbitMQ or Kafka runs the queue. In Spring, with RabbitMQ you send with RabbitTemplate and receive with @RabbitListener, and with Kafka you use KafkaTemplate and @KafkaListener. Sometimes several servers that do the work are run and take messages from the same queue, dividing them among themselves. For work that can go on to the next step only after its result is received right away, such as payment approval, the request is sent directly instead of through a queue.
A message queue is a line, placed between the server that asks for work and the server that does the work, in which the work to be done is written down. In real services, a message broker such as RabbitMQ or Kafka (a server that receives messages, holds them, and passes them on) runs the queue, and in Spring you use a RabbitMQ queue with RabbitTemplate and @RabbitListener, which Spring AMQP provides. The code on the screen is the code of the two servers. QueueConfig in the order server creates a queue named order-created in RabbitMQ (Queue is a class that Spring AMQP provides). The order method of OrderService, an example class we made, puts the order number in the queue order-created with rabbitTemplate.convertAndSend each time an order comes in, and returns right away. The short piece of data put in the queue like this is called a message, and order is the side that sends messages. In Notifier, an example class we made for the notification server, the handle method that has @RabbitListener(queues = "order-created") is called by Spring when a message arrives in the queue (the side that receives messages). In this lab you remove the queue so that the order server sends the request straight to the notification server with RestClient, which Spring provides (the notification server then receives it in a @PostMapping("/notify") method), or you keep the notification server stopped while the 3 orders are sent and start it later, and you see the result the order server gets and how the notifications are handled. All four cases were checked by really running the code on the screen on RabbitMQ and Spring Boot.
Checked against real execution · All four combinations were run by compiling the same source as the screen. The two combinations that use the queue were run with RabbitMQ 4.4.1 (Docker rabbitmq:4), Spring AMQP 4.1.1 (RabbitTemplate, @RabbitListener), and Spring Boot 4.1.1, and the number of messages in the queue was read from RabbitMQ and checked. The two combinations that call directly were run with Spring Boot 4.1.1 and RestClient (ResourceAccessException was confirmed). Match 4 / 4 (verify/net/cmp_queue_basic.js)
Concepts in this lab
- Message queue
- An intermediate store that sits between the sending side (the producer) and the receiving side (the consumer), holds messages, and then delivers them. The producer puts a message in and moves straight on to its next work, and the consumer takes messages out and processes them at its own pace. The two systems do not call each other directly, so coupling is lower, and a sudden burst of requests can be piled up and processed later.
- Message broker
- Why it exists — If a producer and a consumer connect directly to each other, each must know the other's address, and every time you add or change consumers, the producer must be changed too. A message broker is a separate server standing between the two, so both sides need to know only the broker's address.
- Where it's used today — Several Spring servers connect to a broker server such as RabbitMQ or Kafka to send and receive messages. Instead of running a broker yourself, you may also use a queue service that is operated for you in the cloud, such as Amazon SQS.
- A message broker is an intermediate program that receives the messages a producer sends and passes them on to a consumer. The RabbitMQ tutorial introduces RabbitMQ as a message broker that accepts and forwards messages. The broker keeps the messages it receives in queues, and the same tutorial describes a queue as a large message buffer that holds messages as far as the memory and disk of the host allow. Producers and consumers do not connect to each other directly. They exchange messages through the broker.
- RabbitTemplate
- Why it exists — If you use the Java client of RabbitMQ as it is, you have to open and close connections and channels and convert objects to bytes by yourself every time. RabbitTemplate takes care of this work, so you only give it the queue name and the object to send.
- Where it's used today — After saving an order, it is used to put an "an order was created" message in the queue with rabbitTemplate.convertAndSend and respond right away, handing work that can be done later, such as email, notifications, and statistics, to another server.
- RabbitTemplate is a class that Spring AMQP (spring-rabbit) provides, and a Spring application uses it to send messages to RabbitMQ. When you call it like rabbitTemplate.convertAndSend("order-created", no), it converts a Java object (here, an order number) into a message and sends it through the default exchange to the place whose routing key is "order-created", that is, to the queue named order-created. This works because, according to the RabbitMQ documentation, the default exchange binds every queue with a routing key equal to the queue name. It returns right after sending the message and does not wait for the receiving side to handle it. If the RabbitMQ library is present, Spring Boot creates a RabbitTemplate as a bean, so you receive it by injection in the class that needs it.
- @RabbitListener
- Why it exists — To receive messages from a queue, you have to repeat the work of connecting to RabbitMQ and getting ready to receive, converting bytes to objects and handling them each time a message arrives, and telling that handling is done. @RabbitListener leaves this work to Spring, so the developer writes only a method that handles one message.
- Where it's used today — It is used by putting @RabbitListener(queues = "order-created") on a method of a notification server, so that each time it receives an order number that the order server put in, it sends a notification email. If you use Kafka, you write @KafkaListener(topics = …) in the same place.
- @RabbitListener is an annotation that Spring AMQP provides. When you write it above a method like @RabbitListener(queues = "order-created"), that method becomes the side that receives the messages of the queue order-created. When a message arrives, Spring converts the message to the parameter type of the method and calls that method. With the default setting (AUTO), when the method ends without an exception, Spring tells RabbitMQ that handling is done, and RabbitMQ removes the message from the queue at that moment. The queue to receive from must already exist or must be created as a Queue bean.
- Producers and consumers
- Why it exists — If the side that creates tasks also does the processing itself, the creating side also stops and waits for as long as the processing is slow. If you split the roles into producer and consumer and put a queue between them, each works at its own speed, and when busy you can handle more by adding only consumers.
- Where it's used today — For example, an order server becomes the producer and sends an "order completed" message, and a notification server becomes the consumer, receives that message, and sends an email. Even inside one Java program, threads divide work in the same way with a BlockingQueue between them.
- A producer is a program that creates and sends messages, and a consumer is a program that receives those messages and handles them. The RabbitMQ tutorial calls a program that sends messages a producer and a program that mostly waits to receive messages a consumer, and the Kafka documentation calls a client application that writes events a producer and the side that reads and processes events a consumer. When a queue sits between them, the producer only puts messages in the queue, and the consumer takes them out of the queue when it is ready. The Kafka documentation explains that the two are fully decoupled and agnostic of each other.
- ResourceAccessException
- Why it exists — A call to another server can fail because of the network, and the kind of that failure differs depending on which HTTP client library you use. Spring throws it as one exception, so that the calling code can catch "no response was obtained" in one place regardless of the library.
- Where it's used today — In the code that calls another server, you catch it with catch (ResourceAccessException e), and then send the request again, use a default value, or tell the user to try again in a moment. When failures continue, a circuit breaker sometimes counts this exception and stops the calls for a while.
- ResourceAccessException is the exception that Spring (spring-web) throws when an I/O error occurs while calling another server with RestClient and no response could be obtained. This is the case when the other server is off and the connection is refused, or when the timeout you set has passed and the wait is cut off. It is a RuntimeException that inherits from RestClientException, so catching it is not forced, and you look at getCause() to see what actually happened. In the run for this lab, the cause was java.net.ConnectException when the connection was refused and java.net.SocketTimeoutException when the read timeout was hit. When the other side did answer but with an error status code such as 404 or 500, it arrives not as this exception but as HttpClientErrorException or HttpServerErrorException.
Try these
- Default settings — convertAndSend in the order server puts the message in the queue and returns right away. After that, the @RabbitListener method of the notification server receives the messages and handles them in the order they were put in.
- Calling directly without a queue — The order server waits until the notification server has finished handling the request, and only then gets the result.
- Calling directly while the notification server is stopped — All 3 requests fail with ResourceAccessException, and even after the notification server starts there is no notification to handle.
- Using the queue while the notification server is stopped — The 3 orders succeed, and the messages stay in the queue and are handled after the notification server starts.
Running with the default settings
- The order server receives the 3 orders one after another. Each time an order comes in, the order method of OrderService is called, and order sends the work for the notification server with rabbitTemplate.convertAndSend("order-created", no). What it sends is one order number, and this short piece of data is called a message. The message goes not to the notification server but to the RabbitMQ queue order-created. The queue keeps messages in the order they were put in, and in the notification server the handle method that has @RabbitListener(queues = "order-created") receives the messages of the queue one at a time. It is not our code but Spring that calls handle. The notification server is running now, and the queue was empty when it started. In this run, handling one notification was made to take 0.3s.
- order(1) sends order number 1 to the queue order-created with convertAndSend, and the queue keeps this message at the tail. convertAndSend returns right after sending the message, so order finishes without waiting for the notification to be handled, and the result of this order is success. This result means that the message was sent to the queue. It does not mean that the notification was handled. The queue hands this message at once to the notification server, which was waiting, and Spring calls handle, which starts handling "Notify order 1". A message that was handed over is still not removed from the queue until the confirmation that handling is done arrives, so the number of messages in the queue is 1.
- order(2) sends order number 2 to the queue and finishes right away, and it gets the result of this order (success). The number of messages in the queue is 2.
- order(3) sends order number 3 to the queue and finishes right away, and it gets the result of this order (success). The number of messages in the queue is 3.
- The order server has got the results of all 3 orders. At that moment, not one notification has been handled yet. "Notify order 1" is being handled by handle (0.3s), and order numbers 2 and 3 have already been handed to the notification server by the queue, but they wait for their turn because handle is called for one message at a time. All three messages are still in the queue, because none has been confirmed yet. The order server cannot know when these notifications will finish.
- handle finishes handling "Notify order 1" (0.3s). When handle ends without an exception, Spring tells RabbitMQ that handling is done (the confirmation), and only then is the message for order number 1 removed from the queue. Spring calls handle again with the next message it took in advance, order number 2, and 2 are left in the queue. handle is called in the order the messages were put in.
- handle finishes handling "Notify order 2", and the message for order number 2 is removed from the queue. 1 are left in the queue. Spring calls handle with the next message, the one for order number 3.
- handle finishes handling "Notify order 3", and the message for order number 3 is removed from the queue. The queue is empty. All 3 notifications have been handled. The order in which they were handled is order 1, order 2, and order 3, the same as the order they were put in.
Result of this run
- A message queue is a line, placed between the order server and the notification server, in which the work to be done is written down. In the code, rabbitTemplate.convertAndSend("order-created", no) on the sending side and @RabbitListener(queues = "order-created") on the receiving side are connected by the same queue name, and the code of the order server has no address of the notification server. The order server only sent messages to the queue and got the result at once, and the notification server took them in the order they were put in, at its own speed, and handled them.
- In exchange, when the order server got the result, not one notification had been handled yet. Success only means that the message was sent to the queue, so the order server cannot know right away when the notification will finish.
Code
// Code of the order server (import lines and the main class omitted)
// Creates the queue: Queue is a class that Spring AMQP provides
@Configuration
class QueueConfig {
@Bean
Queue orderCreatedQueue() {
// Creates a queue named order-created in RabbitMQ
return new Queue("order-created");
}
}
// An order service we made as an example
@Service
class OrderService {
// The tool that sends messages: RabbitTemplate, which Spring AMQP provides
@Autowired
RabbitTemplate rabbitTemplate;
// Called each time an order comes in (this lab sends orders 1, 2, and 3 in turn)
void order(int no) {
// Puts the order number in the queue order-created as a message and returns right away
rabbitTemplate.convertAndSend("order-created", no);
}
}
// Code of the notification server (import lines and the main class omitted)
// A class we made as an example for sending notifications
@Component
class Notifier {
// Receiving: when a message arrives in the queue order-created, Spring calls this method
@RabbitListener(queues = "order-created")
void handle(int no) {
// Sends the notification (instead of sending an email or text message, prints to the screen)
System.out.println("Notification sent for order " + no);
}
}
Assumptions of this model
All four combinations were checked by really running the code on the screen. The same source as the code on the screen (with only the package and import lines added) was compiled with javac of JDK 21.0.12.1 and run on Spring Boot 4.1.1 and Spring Framework 7.0.9. The two combinations that use the queue were run with RabbitMQ 4.4.1 (the official Docker image rabbitmq:4, only inside 127.0.0.1 of this computer), Spring AMQP 4.1.1 (spring-rabbit, and the auto-configuration of spring-boot-amqp 4.1.1 that creates RabbitTemplate as a bean), and the RabbitMQ Java client 5.30.0. The order server (QueueConfig and OrderService) and the notification server (Notifier) were started as separate Spring Boot applications, and order(1), order(2), and order(3) of the OrderService bean in the order server were called in turn. The settings for connecting to RabbitMQ gave only the address and the port, and the rest are the defaults. The number of messages in the queue is the value that RabbitMQ reported, that is, the messages not yet handed to the receiving side plus the messages handed over and waiting for the confirmation (it was read inside the broker every 1ms). This is what was seen in this run. convertAndSend returned without an exception all three times (tens of ms for the first one, which opens the connection, and about 1ms for the others), and the first notification finished only after the results of all 3 orders had been received. When there was a receiving side, RabbitMQ handed over every message as soon as it arrived (the prefetch of the receiving side that RabbitMQ reported is 250), and the messages that were handed over were removed from the queue one at a time, each time handle finished one (3, 2, 1, and 0 messages, 0.3s apart). handle was called on one thread, one message at a time, in the order of orders 1, 2, and 3. The listener container was SimpleMessageListenerContainer, the acknowledge mode was AUTO, the message converter was SimpleMessageConverter, and the order number was received by handle(int no) as it is. The queue that was created was durable, and neither auto-delete nor exclusive. In the combination where the notification server starts later, the queue did not exist before the orders were sent, it appeared after the first convertAndSend, and after the 3 orders RabbitMQ reported 3 messages not handed over and 0 receiving sides. In the combination where the notification server is running, the order server was started first and made to connect to RabbitMQ once (AmqpAdmin.initialize() created the queue of QueueConfig), and the notification server was started while the queue existed. It was also checked by running that if only the notification server is started first while the queue does not exist, @RabbitListener cannot find the queue and the notification server fails to start (RabbitMQ answers 404 NOT_FOUND, and about 17s later the startup fails with ApplicationContextException). For the two combinations that remove the queue and call directly, Notifier of the notification server was started with Spring Boot (embedded Tomcat) on 127.0.0.1, and only the 8081 in localhost:8081 on the screen was replaced with an unused port number of this computer. In the combination where the notification server is running, every time order ended only after handle finished printing "Notification sent for order N", and in the combination where it is stopped, order ended all three times with ResourceAccessException (cause java.net.ConnectException), and even when the notification server was started on the same port number and watched for 1s, handle was never called. The 0.3s for one notification is a value chosen for this lab. handle on the screen only prints one line, so for the run the standard output was replaced with an output that takes 0.3s to print the line "Notification sent for order N". What was compared is the three columns of the result table and the facts written above (verify/net/cmp_queue_basic.js). That the message of convertAndSend("order-created", no) went into the queue with the same name although no exchange was created was seen in the run, and the reason (convertAndSend(String routingKey, Object message) sends to the default exchange, and the default exchange binds every queue with a routing key equal to the queue name) was checked against the RabbitMQ AMQP 0-9-1 Model Explained (https://www.rabbitmq.com/tutorials/amqp-concepts) and the Spring AMQP API documentation. KafkaTemplate and @KafkaListener are not covered in this lab. What was shortened on the screen: the import lines of the two servers and the main class (the class that has @SpringBootApplication), and the settings that connect to RabbitMQ (spring.rabbitmq.host and so on) are not shown. What this lab did not look at: keeping the queue on disk and the case where RabbitMQ itself stops, handing a message over again when the receiving side stopped before the confirmation, the case where a message is delivered twice, the order and distribution when there are several receiving sides, redoing a failed handling, and the timeout of RestClient. Such details are covered in the in-depth labs "Message queue basics", "Kafka partitions and consumers", and "Saga and outbox". This lab also did not judge the standard that separates the jobs a queue suits from the jobs that suit a direct call (whether the result is needed right away).
Previous lab: Caches · Next lab: Deployment