Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Architecture and operations › Messaging and asynchronous processing

Message queue basics

Leave a note instead of calling directly

Why it exists — If one server calls another server directly and waits until it finishes, the response is delayed as much as the other side is slow, and if the other side is stopped, the request fails too. A message queue puts a place between the two servers where messages are stored, so the sending side responds without waiting for the result, and the receiving side, after stopping and coming back, processes the backed-up messages starting with the oldest.

Where it's used today — It is used to hand off follow-up work that the response does not immediately need, such as sending a confirmation email after an order or creating a thumbnail of an uploaded image, and tools such as RabbitMQ, Kafka, and Amazon SQS do this job. It is also used when several services must each receive and process one event. For work where you must receive the result before going to the next step, such as payment approval, a direct call is kept.

When an order comes in, you must send a confirmation email. The order server can call the email server directly and wait until it finishes, or it can put a message that says "send the email" in a queue and respond right away.

Checked against real execution · All 36 combinations were run and checked: the order server and the email server on Spring Boot 4.1.1 (the methods on the screen compiled as they are), and for the queue approach RabbitMQ 4.4.1 (Docker rabbitmq:4) with Spring AMQP 4.1.1. The response times are values measured on this computer

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.
Synchronous and asynchronous
Why it exists — If every call is synchronous, you must wait for even a task that takes long but whose result is not needed right away, such as sending an email, so the response becomes slow. The asynchronous approach hands off the work, moves on to the next thing first, and receives the result later.
Where it's used today — A call whose result decides the next step, such as payment approval, is made synchronously, and work that may finish later, such as sending a notification or aggregating statistics, is handled asynchronously with a message queue or @Async.
Synchronous means that the side that requests a task waits until it receives the result and only then moves on. Asynchronous means that the requester starts the task and moves on to the next work without waiting for the result, and the result is delivered later through a callback, a Future, or a similar means.
Pub/Sub
Why it exists — If the sender knows each receiver and calls them directly, the sending code has to change every time a receiver is added. With Pub/Sub, publishing once to a topic delivers the message to everyone subscribed, so the sender stays the same even when receivers increase.
Where it's used today — It is used to send a message to chat users who are connected across several servers, or to send a notice of a configuration change or a cache deletion to all servers. For messages that must not be missed, use Kafka or Redis Streams, which keep a record.
A messaging approach in which a publisher sends a message to a specific topic (channel) and every subscriber that is subscribed to that topic receives the message. Publishers and subscribers do not need to know each other. The Redis version does not store messages, so a subscriber that is not connected at that moment does not receive the message.
Message delivery guarantees
The level of guarantee about how many times a message is delivered. With at-most-once, a message is delivered at most one time, so there are no duplicates but messages can be lost. With at-least-once, a message is delivered at least one time, so nothing is lost but duplicates can occur. With exactly-once, a message is delivered exactly one time. In practice, systems often use at-least-once and make the consumer handle duplicates (idempotent).
Eventual consistency
The guarantee that, although some nodes may show the old value right after data changes, all nodes end up with the same value over time if no further changes are made. It gives up immediate consistency and gains availability and scalability in return. It is commonly adopted in distributed databases and for synchronizing data between microservices.

Try these

Running with the default settings

  1. 3 orders arrive one after another (the next order arrives after the response to the previous one). After saving the order, the order server calls the email server directly with mailClient, an example object we made (mailClient sends a request to the email server with RestClient, which Spring provides). The email server takes 1s to send one confirmation email. The response times below are values measured by really running this on this computer.
  2. Order 1: After saving, the order server calls the email server and waits until it finishes (1s). The user gets a response only after 1.02s.
  3. Order 2: After saving, the order server calls the email server and waits until it finishes (1s). The user gets a response only after 1.02s.
  4. Order 3: After saving, the order server calls the email server and waits until it finishes (1s). The user gets a response only after 1.02s.

Result of this run

Code

// Only the methods are shown (class declarations, imports, and the example Order, OrderDto, orderService, etc. omitted)
@PostMapping("/orders")
OrderDto order(@RequestBody OrderRequest req) {
    Order order = orderService.save(req);          // saves the order
    mailClient.sendConfirm(order);                 // calls the email server directly and waits
    return OrderDto.of(order);                     // responds only after the email is done
}

Assumptions of this model

All 36 combinations (with 1, 3, and 5 orders) were really run and checked. The methods on the screen were left as they are, only the declarations omitted on the screen were added, the code was compiled on JDK 21.0.12.1, and the order server and the email server were started on 127.0.0.1 of this computer with Spring Boot 4.1.1 (embedded Tomcat) and Spring Framework 7.0.9. The queue approach was run with RabbitMQ 4.4.1 (the official Docker image rabbitmq:4), Spring AMQP 4.1.1 (the RabbitTemplate created by the Spring Boot auto-configuration, and @RabbitListener), and the RabbitMQ Java client 5.30.0. The added declarations are all examples we made. orderService.save saves the order in memory and gives it a number (no database is used, so saving takes almost no time), mailClient.sendConfirm calls POST /mail of the email server with RestClient, mailSender.sendConfirm waits for the time it takes to send one email (0.2s, 1s, or 3s), and in the queue approach a Queue bean creates the queue order-created. The orders were sent as POST /orders requests, one after another. The response time of one order is a value measured on this computer. It is the median of 9 orders that have the same approach, time for one email, and email server state (the runs with 1, 3, and 5 orders put together), written to 0.001s, and it changes a little on every run. The first request after the run started took longer than the median (0.624s for the first request of the direct call with a 0.2s email, and 0.349s for the first request of the queue approach). The most messages in the queue is a value read inside RabbitMQ every 1ms, the maximum of the messages not yet handed over plus the messages handed over and waiting for the confirmation. In the combinations where the email server is normal, RabbitMQ handed each message to the email server as soon as it arrived (the prefetch of the receiving side that RabbitMQ reported is 250), and the messages were removed from the queue one at a time, after each email was sent and the confirmation arrived. The first email finished only after all the orders had been answered, so the most messages in the queue was the same as the number of orders. If many more orders keep coming or emails finish much faster, this number becomes smaller than the number of orders. "Down" was run as the state where the program of the email server is not running. In that state the direct call had its connection refused at once, ResourceAccessException (cause java.net.ConnectException) occurred, the order request ended with 500, the saved orders remained, and no email went out even when the email server was started again and watched for 1s. If the email server is running but does not respond, or if the machine itself is off, the caller waits until a timeout occurs, and that case was not run. In the queue approach with the email server down, after all the orders were sent RabbitMQ reported as many messages not handed over as there were orders and 0 receiving sides, and when the email server was started they were handled in the order they were put in. With a direct call you can also catch the exception to keep the order from failing, and the case where the queue itself goes down, message loss, duplicate delivery, ordering problems, and several receiving sides are not covered here. The check is done by verify/spring/cmp_mq.js.

Previous lab: Rate limiting · Next lab: Kafka partitions and consumers

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these