Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 48

Building a Distributed Message Queue with Ordering and Delivery Guarantees

This lesson is built with resources from youtube.com, systemdesignschool.io and 1 more site.

Hello! Welcome to the second lesson in our module on designing core infrastructure systems.

In our previous lesson on the URL shortener, we identified the need for a message queue to handle analytics processing asynchronously, ensuring the critical redirect path remained fast. We glossed over the internal workings of that queue, treating it as a black box. Now, it's time to open that box.

This lesson directly addresses the learning outcome: Design a distributed message queue (e.g., Kafka-like) with ordering and delivery guarantees. This is a foundational system design problem, and a strong answer demonstrates a deep understanding of trade-offs in distributed systems around scalability, durability, and consistency. For a Staff-level interview at companies like Google or Uber, mastering this topic is crucial.

1. Scoping the Problem: What Kind of Message Queue?

The term "message queue" can be ambiguous. Before diving into a solution, it's essential to clarify the model we're building. Let's begin by watching a short video that defines the problem and outlines the initial requirements.

System Design Interview - Distributed Message Queue

The video 'System Design Interview - Distributed Message Queue' provides a great starting point by defining what a message queue is and outlining its core requirements.

Watch the first three minutes of the video (00:00 - 03:06). Focus on: The role of a message queue in enabling asynchronous communication. The key distinction between a queue (one message, one consumer) and a topic (one message, many subscribers). The core non-functional requirements: scalability, high availability, performance, and durability.

The video touches on a critical distinction. The world of messaging systems is broadly divided into two families. Understanding which one to build is the most important first step.

Design a Distributed Message Queue

The article 'Design a Distributed Message Queue' from System Design School clearly explains the two main architectures for message queues. This distinction will dictate our entire design.

Read the section 'Background', focusing on the comparison between 'Traditional AMQP-style queues' (like RabbitMQ) and 'Log-based queues' (like Kafka). Pay close attention to the three reasons provided for choosing the log-based model.

Based on this, we're designing a log-based message queue. This model is the foundation of systems like Apache Kafka and is favored for modern data pipelines due to its flexibility and performance at scale.

Let's summarize our requirements:

  • Functional Requirements:
    • Publish/Subscribe: Producers publish messages to logical categories called topics. Multiple independent consumer groups can subscribe to a topic.
    • Ordering: Messages with the same key must be processed in the order they were produced.
    • Retention: Messages should persist for a configurable period (e.g., 7 days) regardless of whether they have been consumed, allowing for replayability.
  • Non-Functional Requirements:
    • Durability: Once acknowledged, messages must not be lost.
    • High Availability: The system must tolerate node failures without service interruption.
    • High Throughput: The system must handle hundreds of thousands of messages per second.
    • Low Latency: Publish and consume operations should be fast (e.g., <100ms end-to-end).
    • Delivery Guarantees: The system must provide at-least-once delivery by default, with a path to achieving "effectively-once" processing.

2. High-Level Architecture: The Commit Log

At the heart of a Kafka-like system is the concept of a distributed, partitioned, append-only log, often called a commit log. Let's build the intuition for this architecture.

Kafka System Design Deep Dive w/ a Ex-Meta Staff Engineer

The video 'Kafka System Design Deep Dive' by a former Meta Staff Engineer provides an excellent, intuitive walkthrough of how scaling challenges naturally lead to Kafka's design. This is a great way to understand the 'why' behind the architecture.

Watch from the beginning to 14:18. This extended clip is worth the time. It uses a motivating example (a real-time sports website) to introduce the core concepts step-by-step: Scaling Problem: A single queue becomes a bottleneck. Solution -> Partitions: Splitting a topic across multiple servers (brokers) into partitions to enable parallelism. Ordering Problem: Random distribution breaks order. Solution -> Partition Key: Hashing a key (e.g., game_id) to ensure all related events go to the same partition, preserving order for that key. Consumer Scaling: A single consumer can't keep up. Solution -> Consumer Groups: Allowing multiple consumers to share the load of a topic, where each partition is assigned to exactly one consumer in the group. Formal Terminology: The video then formalizes these concepts and details the lifecycle of a message, including the producer's role in specifying a key and how the broker appends it to a partition log.

This gives us the core components of our system. Let's visualize how they fit together.

Kafka Architecture Overview
A high-level view of a Kafka-like architecture. Producers write to topics, which are split into partitions distributed across brokers. Consumer groups subscribe to topics, with consumers in a group dividing the partitions among themselves. Source: gitorko.github.io

Let's solidify the key terms from the video and the diagram:

  • Broker: A server in the message queue cluster. It hosts partitions.
  • Topic: A logical category for messages (e.g., orders, user-signups).
  • Partition: The physical unit of storage and parallelism. A topic is split into one or more partitions. A partition is an ordered, immutable sequence of messages (an append-only log file).
  • Producer: A client application that writes messages to a topic.
  • Consumer: A client application that reads messages from a topic.
  • Consumer Group: One or more consumers that jointly consume a topic. Each partition is consumed by at most one consumer within the group.
  • Offset: An integer that uniquely identifies a message's position within a partition. Consumers use offsets to track their read progress.

3. Deep Dive: Core Mechanics

A Staff-level interview requires you to go beyond the high-level diagram and explain how these components work together to provide guarantees.

3.1. The Write Path: Publishing a Message

The process of a producer sending a message to a broker is optimized for throughput and durability.

Design a Distributed Message Queue

The 'Publish Messages' section in the System Design School article provides a concise, step-by-step breakdown of the write path.

Read the section '2. Publish Messages'. Focus on the five steps of the write path, the different acknowledgment modes (acks), and the role of batching.

Let's summarize the key steps and trade-offs:

  1. Routing: The producer uses a partition key (e.g., user_id). It computes hash(key) % num_partitions to pick a partition. This guarantees that all messages for that user land on the same partition, preserving order. If no key is provided, it defaults to round-robin for even load distribution.
  2. Send to Leader: The producer sends the message to the leader replica for that partition. The mapping of partitions to leaders is fetched from a central controller (like ZooKeeper or a Raft-based service) and cached by the producer.
  3. Append: The leader broker appends the message to the end of the partition log file on its local disk. This is a sequential write, which is extremely fast on spinning disks and SSDs.
  4. Replication: The leader sends the message to its follower replicas. Followers also append the message to their logs.
  5. Acknowledge: The leader responds to the producer. The timing of this response depends on the acks setting, which is a critical durability vs. latency trade-off:
    • acks=0: Producer sends and doesn't wait for a response. Fastest, but no durability guarantee (fire-and-forget).
    • acks=1: Producer waits for the leader to acknowledge the write. Durable, unless the leader fails immediately after acknowledging but before followers have replicated. This is a common middle ground.
    • acks=all: Producer waits for the leader to acknowledge the write after all in-sync replicas (ISRs) have confirmed they have the message. This provides the highest durability guarantee but has slightly higher latency. This is the recommended setting for critical data.

Batching: To achieve high throughput, producers don't send messages one by one. They collect messages in a batch (e.g., for 10ms or until 64KB is reached) and send them in a single request. This dramatically reduces network overhead.

3.2. The Read Path: Consuming Messages

The read path is designed for flexibility, allowing different services to consume data at their own pace.

Design a Distributed Message Queue

The 'Consume Messages' section in the System Design School article explains the pull model, consumer groups, and the critical rebalancing process.

Read section '3. Consume Messages'. Focus on why a pull-based model is used, how consumer groups enable both fan-out and parallel processing, and what happens during a rebalance.

Key points of the read path:

  • Pull Model: Consumers request messages from brokers ("pull") rather than brokers sending messages to them ("push"). This is crucial because it allows each consumer to control its own consumption rate. A high-throughput analytics service can pull messages aggressively, while a slower email-sending service can pull more cautiously.
  • Offset Tracking: The broker is stateless regarding consumption. Each consumer group is responsible for tracking its own progress by storing the offset of the last message it processed for each partition.
  • Committing Offsets: When a consumer successfully processes a batch of messages, it commits its new offset back to an internal topic on the Kafka cluster. If the consumer crashes, it can restart, read its last committed offset, and resume from where it left off.
  • Rebalancing: If a consumer joins or leaves a consumer group, the system must reassign partitions among the active members. This process is called rebalancing. It causes a short pause in consumption for that group, a trade-off for the simplicity and power of the consumer group model.

4. Staff-Level Deep Dives: Guarantees & Operations

Answering this question at a Staff+ level means driving the conversation into the nuanced topics of delivery guarantees, failure modes, and operational considerations.

4.1. Delivery Guarantees: The "Once" Trilemma

This is a core part of the learning outcome and a frequent source of interview questions. The interplay between processing logic and when you commit offsets determines the delivery semantics.

Kafka Deep Dive for System Design Interviews

The article 'Kafka Deep Dive' provides a clear, practical guide to handling retries and errors, which is the foundation of understanding delivery guarantees. The System Design School article then offers a superb theoretical explanation.

First, read the section 'Handling Retries and Errors' in the 'Kafka Deep Dive' article. Pay attention to the distinction between producer and consumer retries and the use of a Dead Letter Queue (DLQ).

Design a Distributed Message Queue

Now, let's dive into the theory with this excellent resource.

Read the deep dive question 'How do you achieve exactly-once delivery, and what are its limits?'. This is a fantastic explanation of the three guarantees and is crucial for a senior-level discussion. Focus on the table that summarizes the trade-offs and the key insight about consumer-side idempotency.

Let's synthesize this critical information:

  • At-most-once: Commit offset before processing the message. If the consumer crashes after committing but before processing, the message is lost forever.
  • At-least-once: Process the message before committing the offset. If the consumer crashes after processing but before committing, the same message will be redelivered upon restart, leading to potential duplicates. This is the default and most common guarantee.
  • Exactly-once: This is a nuanced term.
    • For stream processing within Kafka (e.g., reading from topic A, writing to topic B), Kafka transactions can provide true exactly-once semantics.
    • For most real-world applications involving external systems (like calling a payment API or writing to a database), the message queue cannot guarantee exactly-once processing on its own. The solution is a combination of at-least-once delivery + an idempotent consumer. The consumer must be designed to handle duplicate messages gracefully (e.g., by checking if an order ID has already been processed).

In an interview, clearly stating that you'd use "at-least-once with idempotent consumers" is a strong, pragmatic answer that demonstrates real-world experience.

4.2. Scalability and Hot Partitions

You've explained that partitions are the unit of scaling. The natural follow-up question is: "What happens when your partitioning strategy is imperfect and one partition gets all the traffic?"

Kafka Deep Dive for System Design Interviews

The 'Kafka Deep Dive' article has an excellent, dedicated section on this common interview question.

Read the subsection 'How can we handle hot partitions?' within the 'Scalability' section. Understand the three strategies presented.

Here are the strategies for handling a hot partition:

  1. Remove the Key (If Ordering is Unimportant): If you don't need strict ordering, you can stop providing a partition key for the hot messages. The producer will then distribute them round-robin across all partitions.
  2. Use a Compound Key (Salting): This is the most common solution. Instead of partitioning just by ad_id, you could partition by a compound key like ad_id + ":" + random_number_1_to_10. This splits the traffic for that single ad_id across 10 partitions. The consumer-side logic becomes more complex as it now has to read from 10 partitions to get all events for that ad, but it solves the hot spot.
  3. Back Pressure: The producer can detect that a partition is lagging (taking a long time to acknowledge writes) and temporarily slow down the rate of production for that key.

4.3. Monitoring and Operations

Demonstrating that you think about how to operate a system is a hallmark of a Staff-level engineer. What are the vital signs of a healthy message queue?

Kafka Cluster-Level Critical Metrics
A dashboard showing critical metrics for monitoring a Kafka cluster's health. Source: edgedelta.com

The key metrics to monitor, as illustrated above, include:

  • Under-replicated Partitions: The number of partitions where the number of in-sync replicas is less than the configured replication factor. A non-zero value is a critical alert, indicating a risk of data loss if another broker fails.
  • Offline Partitions: The number of partitions without an active leader. Any partition in this state is completely unavailable for reads and writes. This should always be zero.
  • Consumer Lag: The difference in offsets between the last message produced to a partition and the last message a consumer group has committed. High or growing lag indicates that consumers cannot keep up with producers.
  • ISR Shrinks/Expansions: The rate at which replicas leave or join the In-Sync Replica set. A high rate of shrinks can indicate network problems or overloaded brokers.
  • Active Controller Count: In a healthy cluster, there should be exactly one active controller broker.

Mentioning these monitoring points shows you are thinking not just about the design, but also about the long-term health and maintenance of the system.


Conclusion

In this lesson, we designed a distributed, log-based message queue inspired by Apache Kafka. We went from high-level requirements to the deep-seated mechanics of replication, delivery guarantees, and operational readiness.

Key Takeaways:

  • Log-Based is for Scale: The partitioned, append-only log model is the foundation for modern, high-throughput messaging systems.
  • Partitions are Key: They are the unit of parallelism, scaling, and ordering. Your partitioning strategy is one of the most critical design decisions.
  • Guarantees are Trade-offs: Understand the spectrum from at-most-once to at-least-once to "effectively-once" (via idempotent consumers) and be able to articulate the costs and benefits of each.
  • Think Like an Operator: Staff-level design includes discussing failure modes (hot partitions, leader failure), durability configurations (acks, ISRs), and key monitoring metrics (consumer lag, under-replicated partitions).

Preview of the Next Lesson:
We have now designed a system optimized for streaming sequential data. Next, we will shift our focus to a different class of data storage. Our next lesson is: Design a distributed key-value store with configurable consistency levels. This will allow us to explore a different set of trade-offs, particularly those related to the CAP theorem, consistency models, and data partitioning strategies like consistent hashing.