iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📝

Anatomy of Distributed Message Queues: Be Indifferent to the Immediate

に公開
2026/06/19

Introduction

A note to organize my thoughts on distributed message queue systems.

A distributed message queue is a mechanism where application components do not communicate directly. Instead, a "queue"—acting like a box—is placed in between, and messages (data) are temporarily stored there.

The sending side (Producer) just throws messages into the queue. The receiving side (Consumer) retrieves and processes messages from the queue at its own convenience. Both sides don't need to worry about whether the other is currently running (asynchronous communication). Since the queue holds onto the message until the Consumer takes it, the message won't be lost even if the Consumer stops midway.

It plays an active role in many places.

Architecture and Basic Concepts

Understanding the basic structure of a distributed message queue system reveals its power. Let's first take a look at the basic architecture.

Publish/Subscribe (Pub/Sub) Model

The foundation of distributed message queue systems is the Pub/Sub model. The diagram below illustrates this concept.

The roles of each element in this model are as follows.

Element Role
Producer Generates messages and publishes them to a specific Topic.
Broker Receives messages published from Producers, categorizes them by Topic, and maintains/manages them. Usually, multiple Broker servers form a cluster to ensure load balancing and fault tolerance.
Consumer Subscribes to a specific Topic, receives messages from the Broker, and processes (consumes) them.

The advantage of the Pub/Sub model is that the sender and receiver of messages do not need to know each other. The Producer simply broadcasts, "There is news related to this Topic," without needing to know who is listening. On the other hand, the Consumer simply declares, "I want information on this Topic," without needing to know who is sending it. This improves the flexibility and scalability of the system.

Role in the System

By eliminating direct dependencies between components, the impact of changes in one component on another is minimized, increasing the efficiency of development and maintenance. Decoupling is achieved through the following three aspects:

Aspect Description
Time Producers and consumers do not need to be active at the same time; messages are stored in the Broker and processed when the Consumer becomes available.
Space Producers and Consumers do not need to know each other's physical locations or connection endpoints.
Asynchronous After sending a message to the Broker, the Producer can proceed to the next task without waiting for the Consumer's processing to complete.

This "decoupling" characteristic is the reason why message queues play a crucial role in modern distributed systems and microservices architectures. For example, even if a service is temporarily down, messages destined for that service are safely stored in the queue and processed once the service is restored. This improves the overall robustness of the system.

Key Technologies

Let's look at the key technologies that support distributed message queue systems. By combining these technologies in complex ways, systems that possess both high throughput and reliability are realized.

Basic Elements of Messaging

We will go over the basic elements based on the Kafka architecture (from the Zookeeper-dependent era) shown below.


https://www.researchgate.net/publication/326564203_KerA_Scalable_Data_Ingestion_for_Stream_Processing

Topic

A logical category name or stream name for messages. Producers publish messages by specifying this Topic, and Consumers subscribe to this Topic.

A Topic is like a mailing list for emails or a category on a bulletin board. It is common to create a Topic for each type of message, such as "Financial Information," "User Registration," or "Order Information." Proper Topic design significantly impacts the system's efficiency and ease of management.

Partition

A physical unit that further divides a Topic. One Topic consists of one or more Partitions.

Function Description
Parallel Processing Parallelizes message processing by assigning a Consumer to each Partition. The number of Consumers in a Consumer Group is typically less than or equal to the number of Partitions.
Load Balancing Balances the load on Brokers by distributing messages across multiple Partitions.
Ordering Guarantees Guarantees that messages within the same Partition are delivered to Consumers in the order they were published. However, the order of messages across different Partitions is not guaranteed.

A Partition plays a role similar to a shard (distributed storage) in a file system. For example, in a system that processes a large volume of log messages, a single storage unit has limits in terms of both speed and scale. Therefore, processing capacity is improved by distributing data across multiple physical Partitions.

Broker

Function Description
Message Store Stores received messages on disk or in memory.
Forwarding Delivers messages in response to requests from Consumers.
Cluster Configuration Forms a cluster with multiple Brokers to enhance load balancing, scalability, and availability.

The Broker serves as the "heart" of the system, responsible for receiving, storing, and delivering messages. To ensure fault tolerance, large-scale systems typically configure a cluster with three or more Brokers.

Producer

Function Description
Message Publishing Sends messages to the Broker.
Batch Processing Often includes functionality to send multiple messages together to improve network efficiency (e.g., Kafka).

A Producer is the "sender" of information, and any system or application can be a Producer. Diverse information sources publish messages, such as IoT devices sending sensor data, web servers recording user actions, or e-commerce backends notifying of inventory updates.

Consumer

Function Description
Message Reception Retrieves messages from the Broker.
Processing Logic Executes various processes based on received messages, such as storing data, analysis, or notifying other services.

A Consumer is the "user" of information, receiving messages and performing actual work. They come in various forms, such as processes that store information in databases, stream processing engines that perform real-time analysis, or monitoring systems that send alerts.

Consumer Group

Multiple Consumer instances that collaborate to consume a single Topic (or multiple Partitions). It has the following characteristics:

Characteristic Description
Exclusivity of Message Delivery Messages within a Topic are delivered to only one Consumer within the group.
Load Balancing and Parallel Processing Improves processing capacity by distributing tasks among multiple Consumers.
Independence Between Groups Different Consumer Groups can each independently receive all messages of the same Topic (realizing the Pub/Sub model).

A Consumer Group is like a work team. Members share the same job (processing Topic messages) to work efficiently. It is possible for one team (Group A) to process messages for the purpose of "storing customer data," while another team (Group B) processes the same messages for a completely different purpose, such as "performing marketing analysis."

Message Data Structure

Messages exchanged in a distributed message queue system generally consist of the following elements. In systems like Kafka, these elements play crucial roles.

Component Description Role/Characteristics in Kafka
Key Optional data for identifying or grouping messages. Byte array. ・Partition assignment. If a key exists, the partition to which the message is sent is determined based on the hash value of the key. This ensures that messages with the same key are always sent to the same partition, guaranteeing their order within that partition.
・If no key exists (null), messages are often assigned to partitions in a Round Robin fashion by default.
・The key itself is also serialized and sent as a byte array (e.g., IntegerSerializer, StringSerializer).
Payload (Value) The actual data body. Byte array. ・The main information the application wants to send and receive (e.g., JSON string, sensor data, event information).
・Converted from an object to a byte array by an appropriate serializer (e.g., StringSerializer, AvroSerializer, ProtobufSerializer) on the producer side, and restored from a byte array to an object by a corresponding deserializer on the consumer side.
Headers A list of metadata (additional information) in Key-Value format. Optional. ・Used to attach additional information about the message itself (e.g., source system ID, trace ID, schema version, etc.).
Timestamp The time the message was created or received by the Broker. ・Used for recording event occurrence times or time-based data processing (e.g., windowing). It can be configured whether the producer attaches it or the broker attaches it upon reception.
Offset A unique, monotonically increasing number indicating the logical position of a message within a Partition. ・Automatically assigned by the Broker.
・By recording and managing this offset, a Consumer knows how far it has read messages, enabling recovery and resumption from failures.
・The combination of Partition number and offset uniquely identifies a message within a Topic.
Partition Number The number of the Partition to which the message belongs. The producer client determines this (usually based on the key or via Round Robin) and indicates the target partition to which the message is sent. The Broker stores the message in that partition.

Pull vs Push Model

Model Description Advantages Disadvantages Representative Examples
Pull The Consumer retrieves messages from the Broker at its own timing. ・Consumers can retrieve messages according to their own processing capacity (flow control is easy).
・Easy to re-read (rewind) messages.
・Potential for higher latency in message arrival compared to the Push model. Kafka
Push The Broker actively delivers messages to the Consumer. ・Low latency in message arrival. ・Messages may be sent exceeding the Consumer's processing capacity (separate flow control is required). Part of RabbitMQ

The difference between the Pull and Push models is similar to the difference between dining at a restaurant and getting delivery. The Pull model is like going to a restaurant yourself and ordering and eating at your own pace. The Push model is like a delivery service where food is brought to your home as soon as it's ready. Which one is better depends on the situation.

Reliability and Availability

Replication

A mechanism for maintaining copies of Partition data across multiple Brokers.

Characteristic Description
Leader-Follower Structure Each Partition has a Leader and Followers. The Leader handles writes, and Followers replicate them.
Handover During Failure If the Leader fails, one of the Followers is promoted to the new Leader.
Replication Factor A value indicating how many Brokers the data is replicated to. Usually, 3 is recommended (one Leader and two Followers).

Replication is like insurance. You keep multiple copies of the same data on different servers just in case something goes wrong. This allows the system as a whole to continue operating even if some servers fail. Such redundancy is no longer a luxury but an essential element.

ACK (Acknowledgement)

Responses used to confirm that a message has been processed correctly.

Type Description Trade-off
Producer ACK A response where the Producer sends a message to the Broker, and the Broker confirms it has been correctly received and persisted. Depending on the ACK level (Leader only, including a specific number of Followers, etc.), a trade-off between reliability and performance (latency) occurs.
Consumer ACK A response where the Consumer notifies the Broker that it has correctly received and completed processing a message (important in RabbitMQ, etc.). Guarantees that the message will be redelivered if the Consumer fails during processing.

In Kafka, the following options are available for the Producer ACK level:

ACK Level Meaning Reliability Latency
0 Producer does not wait for a response. Low (High potential for message loss) Minimum
1 Only the Leader responds. Medium (Potential loss during Leader failure) Medium
all (-1) The Leader and a specified number of Followers respond. High (No loss with proper configuration) Maximum

While "ack=all" is chosen for areas requiring strict consistency like financial transactions, "ack=1" or "ack=0" may be chosen for areas demanding ultra-low latency like real-time ad bidding.

Delivery Guarantees

The level of guarantee regarding how many times a message is delivered to a Consumer.

Guarantee Level Description Use Case Implementation Method
At-most-once Messages are delivered at most once but may be lost. High-throughput systems where partial data loss is acceptable. Proceed with processing without waiting for ACK.
At-least-once Messages are never lost but may be delivered redundantly. Systems where data loss is not acceptable. Kafka's default. The Producer attempts redelivery until an appropriate ACK is received. Deduplication (ensuring idempotency) is required on the application side.
Exactly-once Messages are delivered exactly once. Financial transactions where neither duplication nor loss is acceptable. Requires advanced and complex mechanisms such as transaction processing or idempotent producers/consumers. Significant impact on performance.

Delivery guarantees are similar to the quality assurance of a delivery service. At-most-once is like "we'll try to deliver, but won't redeliver if you're out"; At-least-once is like "we will definitely deliver, but the same package might arrive multiple times (theoretically speaking)"; and Exactly-once is like "guaranteed delivery exactly once, with no double delivery and no loss."

Message Persistence (Persistence)

By saving messages received by the Broker to persistent storage like a disk, it ensures that messages are not lost even if the Broker restarts.

Implementation Example Characteristics
Kafka Achieves both persistence and high throughput by actively utilizing the OS page cache and performing sequential writes to disk.
RabbitMQ Allows specifying a persistence option (Durable) when creating a queue.

Coordination and Management

Rebalancing

The process of automatically readjusting the assignment of Partitions handled by each Consumer when a Consumer is added to or removed from a Consumer Group, or when a Broker failure occurs.

Characteristic Description
Automatic Adjustment Automatically readjusts Partition assignments during Consumer fluctuations or Broker failures.
Coordination Service In Kafka, coordination services like ZooKeeper (or the internal Kafka controller in recent versions) are used for this adjustment.
Processing Pause Message processing may temporarily stop during rebalancing.
Rebalancing Strategy Various assignment strategies exist, such as Range, RoundRobin, and Sticky. In Kafka, available strategies vary by version.

Rebalancing is like the redistribution of work in an office. It is the process of fairly redistributing tasks when an employee goes on vacation or a new member joins. However, since work can temporarily stagnate during redistribution, it is desirable to avoid frequent rebalancing.

Offset Management

Records and manages how far a Consumer has read through a Topic's Partition (the offset of the last processed message).

Implementation Example Characteristics
Kafka Consumers manage offsets themselves and periodically commit them to the Broker or an external store (ZooKeeper or Kafka's own dedicated Topic). This allows Consumers to resume processing from where they left off when restarted. It is also possible to intentionally re-read from old offsets (rewind).
Other Systems The Broker may manage the offsets.

Offset management is like a bookmark in a book. When you stop reading, you can remember which page you read up to and start from there the next time. In Kafka, these bookmarks must be explicitly saved (committed), and the timing and frequency of commits are important design decisions.

Routing and Filtering

A mechanism for determining which Queue or Consumer a message should be delivered to.

Method Description Implementation Example
Topic-based The most common method, where delivery destinations are determined based on the Topic name. Kafka, many Pub/Sub systems
Content-based Filters based on message content (e.g., header attributes) and delivers only to Consumers that match the criteria. RabbitMQ, etc.
Exchange-Binding (AMQP) Establishes rules called Bindings between Exchanges and Queues to achieve flexible routing. RabbitMQ

In AMQP, the following Exchange types are defined:

Exchange Type Behavior
Direct Delivers only to Queues where the routing key matches exactly.
Topic Evaluates the routing key using pattern matching (including wildcards) and delivers to matching Queues.
Fanout Ignores the routing key and delivers to all connected Queues.
Headers Routes based on attributes in the message headers.

Routing and filtering are like sorting operations at a post office. Items are distributed to the appropriate destinations based on the address or content. Especially in systems with advanced routing capabilities like RabbitMQ, delivery based on very complex rules is possible.

Schema Management

A mechanism to guarantee compatibility of the message data structure (schema) between the Producer and Consumer.

Technology Description
Schema Definition Language Uses languages such as Avro, Protobuf, or JSON Schema to define data structures.
Schema Registry A service for centralized schema management (e.g., Confluent Schema Registry). It performs schema versioning and compatibility checks.
Versioning Manages changes to schemas via versions and checks compatibility. Ensures forward compatibility (new Consumers can read old data) and backward compatibility (old Consumers can read new data).

Schema management is like grammar and dictionaries for a language. If the structure of the message sent by the Producer does not match the structure expected by the Consumer, communication cannot be established. The Schema Registry manages a common dictionary and supports "translation" even between Producers and Consumers of different versions.

Flow Control / Backpressure

A mechanism to control the flow rate to prevent the entire system from collapsing when the Producer's message issuance rate exceeds the Consumer's processing rate or the Broker's capacity.

Model Mechanism
Pull Model Since Consumers retrieve at their own pace, it is relatively easy to control.
Push Model Mechanisms are needed to urge the Producer to suppress issuance, utilizing reception buffer size limits or ACK delays on the Broker or Consumer side (backpressure).

Specific control methods in each implementation are as follows:

Implementation Control Method
Kafka Naturally controlled because Consumers pull at their own pace. Backpressure from Producer to Broker is achieved through buffer size limits and ACK timeouts.
RabbitMQ Provides features such as flow control based on queue depth, consumer prefetch count settings, and blocking based on queue length.

Backpressure is like a water valve. If the flow of water (messages) is too fast, the pipes (system) might burst, so the flow rate is adjusted appropriately. Without an appropriate backpressure mechanism, the system becomes unstable under high load, potentially leading to message loss or system crashes in the worst case.

Security

Element Description
Authentication Confirms that the Producer, Consumer, and Broker are legitimate (e.g., SASL, TLS client certificates).
Authorization Controls read/write permissions for Topics (ACL: Access Control List).
Communication Encryption Encrypts communication between the Broker and clients, and between Brokers using TLS/SSL to prevent eavesdropping and tampering.

Representative Implementation Examples

There are various implementations of distributed message queues. Here, let's look at some representative ones.

Apache Kafka

Developed by LinkedIn and now a top-level project of the Apache Software Foundation. Originally designed for log processing, it focuses on high throughput and scalability.

Item Details
Overview A high-throughput, fault-tolerant distributed messaging system. Its characteristic feature is an architecture that manages messages as distributed commit logs.
Architecture ・Distributed commit log: Persists Topics/Partitions as log files on disk.
・Pull model: Consumers actively retrieve data from Brokers.
・Offset management by Consumer: Consumers manage their own read positions.
・ZooKeeper dependency (formerly): Uses ZooKeeper for cluster management and leader election. Recently, ZooKeeper-less configurations have become possible via the KRaft protocol.
Key Features ・High throughput and low latency (utilizing OS page cache, sendfile API, and batch processing).
・Persistence and fault tolerance (replication).
・Load balancing and Pub/Sub via Consumer Groups.
・Kafka Streams: A stream processing library.
・Kafka Connect: A framework for integration with external systems.
Use Cases Large-scale log aggregation, real-time analytics pipelines, event sourcing, asynchronous communication for microservices, and website activity tracking.

Kafka is widely adopted as the core of modern distributed systems. In particular, the idea that "logs are queues" has enabled many new architecture patterns.

RabbitMQ (AMQP Implementation)

A message broker implemented in Erlang. It is one of the representative implementations of AMQP (Advanced Message Queuing Protocol), focusing on flexible routing and reliable message delivery.

Item Details
Overview A highly reliable message broker implementing AMQP. It also supports other protocols like MQTT and STOMP.
Architecture ・Exchange and Queue: Producers send messages to an Exchange, which then routes them to Queues based on Binding rules.
・Diverse Exchange types: Four types (Direct, Topic, Fanout, and Headers) are available to implement various routing logics.
Key Features ・Flexible routing.
・Choice between Push and Pull models.
・Message persistence options (Durable Queue/Message).
・Guaranteed message processing through Consumer ACKs.
・Features like priority queues and TTL (Time To Live).
・Management UI and plugin mechanism.
Use Cases Enterprise application integration, reliable communication between microservices, task queues, notification systems, and financial systems—scenarios requiring flexible routing or guaranteed delivery.

RabbitMQ is favored by many companies for its flexibility and reliability. In particular, the variety of routing options is a powerful weapon for handling complex messaging needs. Despite being implemented in Erlang, a relatively minor language, it has a strong reputation for high stability and availability.

Other Systems

System Overview
Apache ActiveMQ A Java-based message broker. Well-known as a full implementation of the JMS (Java Message Service) specification. It also supports AMQP, MQTT, STOMP, and more.
Apache RocketMQ A distributed messaging and streaming platform developed by Alibaba. It is characterized by high throughput, low latency, and high availability.
Apache Pulsar A distributed Pub/Sub messaging system developed by Yahoo!. It combines features of both Kafka and RabbitMQ, offering advanced functions such as multi-tenancy, Geo-replication, and tiered storage.

Cloud-Based Services

Service Overview
Amazon SQS (Simple Queue Service) AWS's fully managed message queuing service. It offers Standard queues and FIFO queues.
Google Cloud Pub/Sub Google's globally scalable, fully managed real-time messaging service.

In cloud-native environments, these managed services are gaining popularity. They offer the advantage of significantly reducing operational overhead and allowing flexible scaling through pay-as-you-go pricing. These services are often the first choice, especially for startups and cloud-native applications.

Brokerless Implementations

Implementation Overview
ZeroMQ (ØMQ) A lightweight messaging library. It allows building various communication patterns (Pub/Sub, Request/Reply, Push/Pull, etc.) on a socket basis without an intermediate Broker.

Brokerless approaches are chosen for specific use cases where ultra-low latency is required. By omitting the intermediate Broker, communication delay can be minimized, but they are generally inferior to broker-based systems in terms of reliability and scalability.

Challenges and Considerations

While distributed message queue systems are powerful, there are several challenges and considerations for their introduction and operation.

Performance Tuning

Challenge Description
Trade-offs Throughput, latency, and reliability (ACK levels, persistence settings, etc.) are in a trade-off relationship. It is necessary to find the optimal parameter settings for each use case.
Parameter Optimization There are many configuration items, and finding the optimal combination can sometimes be difficult. Research into tuning based on load tests and, recently, automated optimization using machine learning (e.g., DMSCO) is progressing.

Operational Complexity

Challenge Description
Cluster Management Expertise is required for the construction, monitoring, scaling, and upgrading of Broker clusters.
Coordination Services Operations for coordination and management services, such as ZooKeeper/KRaft in Kafka, may also be necessary.

Operational complexity is one of the biggest hurdles to adopting distributed message queue systems. Especially with in-house operations, securing engineers with specialized knowledge is a challenge. This point is a significant advantage for cloud-based managed services.

Message Ordering Guarantees

Challenge Description
Intra-Partition Guarantee Order is guaranteed within the same Partition.
Limitations of Inter-Partition Guarantees Message ordering across multiple Partitions is basically not guaranteed. If strict ordering is required, it is necessary to use a single Partition or reconstruct the order on the application side.

Scalability Challenges

Challenge Description
Partition Count Constraints Increasing the number of Partitions too much can increase management overhead (especially during leader election or rebalancing).
Resource Consumption Increased load on network bandwidth and coordination services as the number of Brokers or Consumers increases.

Difficulty of Exactly-once Processing

Challenge Description
Implementation Complexity While theoretically possible, implementation is complex and has a significant impact on performance.
Practical Approach In many cases, At-least-once + ensuring idempotency on the application side (ensuring the results remain the same even if processed multiple times) is the practical solution.

Exactly-once processing is one of the "holy grails" of distributed systems. Even if theoretically possible, actual implementations tend to be complex. In most real-world systems, a combination of "at-least-once" guarantees and application-side measures for handling duplicates is adopted.

Summary

The world of distributed message queue systems is like a highly organized postal system. Messages (parcels) are delivered from the Producer (sender) to the Consumer (recipient) via the Broker (post office). During this process, mechanisms such as ACKs (proof of delivery) for ensuring reliability, Partitioning (sorting) for guaranteeing order, and Replication (backup) to prepare for failures are all at work.

As the core of modern distributed systems, message queues support our lives in invisible ways. From Netflix movie recommendations to bank transaction processing and IoT device sensor data collection, vast amounts of information are exchanged every day.

That item you ordered on your favorite e-commerce site today is undoubtedly being processed through information exchanges between multiple microservices via message queues behind the scenes.

I've gained a bit of understanding. There are many more topics I want to explore.

Discussion