The user wants me to design a message queue system with guaranteed delivery. This is a classic system design problem that touches on distributed systems concepts like availability, durability, consistency, and fault tolerance.
1. Deconstruct the Request:
- Core Component: Message Queue System.
- Key Requirement: Guaranteed Delivery (at-least-once or exactly-once semantics).
2. High-Level Architecture:
A message queue typically involves three main actors:
- Producer: Sends messages.
- Broker (The Queue): Stores and manages messages.
- Consumer: Receives and processes messages.
For a robust design, I need to handle failures at every step.
3. Key Concepts for Guaranteed Delivery:
- Durability: Messages must survive crashes. This implies disk persistence (WAL - Write Ahead Log).
- Acknowledgments (ACKs): Producers need to know the broker got it. Consumers need to know the broker knows they finished it.
- Retries: If an ACK isn't received, retry.
- Idempotency: Since we have retries, we might have duplicates. The system (or the consumer) needs to handle this.
4. Detailed Design Steps:
-
Step 1: The Producer-Broker Interaction (Publishing)
- Problem: Network fails between producer and broker.
- Solution: Producer retries.
- Mechanism:
send(message) -> Broker writes to disk -> Broker sends ACK.
- Optimization: Batching/Async writes (but this risks data loss, so for guaranteed delivery,
fsync is crucial).
-
Step 2: The Broker Internals (Storage)
- Structure: Needs to be efficient. A log-structured merge tree or a simple Commit Log (like Kafka) is best.
- Durability: Write to Write-Ahead Log (WAL) before acking.
- Replication: Single point of failure? No. Need replication (Leader-Follower model).
-
Step 3: The Consumer-Broker Interaction (Consumption)
- Problem: Consumer pulls message, processes it, crashes before sending ACK.
- Solution: "At least once" delivery.
- Flow:
- Consumer pulls message.
- Broker marks message as "in-flight" (unacknowledged) but keeps it stored.
- Consumer processes.
- Consumer sends ACK.
- Broker deletes/marks message as processed.
- Visibility Timeout: If the consumer doesn't ACK within X seconds, the message becomes visible again.
-
Step 4: Handling Duplicates (Idempotency)
- Since we retry on the producer side and re-deliver on the consumer side, duplicates are inevitable.
- Producer side:
MessageID.
- Consumer side: Needs to de-duplicate (e.g., check DB unique constraint or use a cache of processed IDs).
5. Scalability & Availability (Distributed System concerns):
- Partitioning/Sharding: Split queues by key to scale throughput.
- Replication: Synchronous vs. Asynchronous. For guaranteed delivery, synchronous replication to at least one replica is preferred (min.insync.replicas in Kafka terms).
6. Structuring the Answer:
I should organize the design logically:
- Introduction: Define "Guaranteed Delivery" (At-least-once).
- Core Components: Producer, Broker, Consumer.
- Key Mechanisms:
- Persistence (WAL).
- Replication.
- Acknowledgments.
- Workflow (The "Happy Path" and "Failure Path"):
- Producing flow.
- Consuming flow.
- Handling Edge Cases (Exactly-Once Semantics): Briefly mention idempotency and transactional messaging.
- Diagram/Visual Representation (Text-based): A sequence diagram or component diagram is helpful.
7. Refining the "Guaranteed Delivery" definition:
- Strictly speaking, "guaranteed" usually means At-Least-Once.
- Exactly-Once is much harder and requires application-level cooperation. I should make this distinction clear. I will focus the design on achieving At-Least-Once and then layer Exactly-Once on top.
8. Self-Correction/Review during drafting:
- Initial thought: Just write to disk.
- Correction: If the disk fails, you lose data. Must mention replication.
- Initial thought: Push model to consumer.
- Correction: Pull model (like Kafka) is often better for high throughput/batching, but Push (like SQS/RabbitMQ) is easier for "guaranteed" logic visibility timeouts. I'll describe a general Pull/Push hybrid or standard Pull with offsets. Let's stick to a generic model where the consumer asks for work.
9. Final Polish:
- Use standard terminology (WAL, ACK, Offset, Partition).
- Highlight the "Idempotent Producer" pattern.
(Self-Correction during drafting details):
Make sure to mention the "Outbox Pattern" for the producer side. That is a critical design pattern for guaranteed delivery from the producer's application database to the queue.
Let's assemble the response.
- Title: High-Level Architecture.
- Section 1: The Definition: What does guaranteed mean? (Durability + ACKs).
- Section 2: The Producer Side (Durability): WAL, Replication.
- Section 3: The Consumer Side (Delivery Semantics): At-least-once, Visibility Timeout.
- Section 4: Handling Duplicates: Idempotency.
- Section 5: The "Outbox Pattern": Ensuring the producer actually sends.
This looks solid. I will produce the output now.
Designing a message queue with guaranteed delivery implies that a message sent by a producer will eventually be received and processed by a consumer, regardless of network failures, node crashes, or consumer errors.
To achieve this, we cannot rely on in-memory storage or "fire-and-forget" protocols. We need persistence, acknowledgments, and redelivery mechanisms.
Here is the architectural design for such a system.
1. High-Level Architecture
We will use a Distributed Log architecture (similar to Apache Kafka or RabbitMQ's persistent queues).
Core Components:
- Producer: The application sending messages.
- Gateway (Load Balancer): Distributes incoming requests across Broker nodes.
- Broker Cluster: The server-side infrastructure that stores and routes messages.
- Metadata Store (ZooKeeper/etcd): Tracks cluster state, leader election, and offset positions.
- Consumer: The application receiving messages.
2. Detailed Design & Mechanics
To guarantee delivery, we must solve failure scenarios at every step.
A. Message Durability (The "Write" Path)
When a message is sent, it must not be lost if the Broker crashes immediately after receiving it.
- Write-Ahead Log (WAL): The core storage engine is an append-only log on disk.
- Replication Factor (N): The message queue is clustered. When a Broker receives a message, it does not acknowledge the producer until that message has been replicated to N nodes (e.g., 3 nodes: 1 Leader, 2 Followers).
- acks Configuration: The Producer configures
acks=all. This ensures the Leader waits for confirmation from all In-Sync Replicas (ISR) before sending a success response to the Producer.
B. The "At-Least-Once" Handshake
Guaranteed delivery usually implies At-Least-Once semantics. This means a message might be delivered twice, but it will never be lost.
The Flow:
- Producer Send: Sends message with a unique
MessageID.
- Broker Persist: Broker writes to WAL and replicates.
- Broker ACK: Broker sends
ACK(Persisted) to Producer.
- Failure Mode: If the Producer times out waiting for an ACK, it must retry sending the message. This creates the possibility of duplicates.
- Idempotent Producer (Optional): To handle the retry duplicates mentioned above, the Broker can maintain a cache of recent
MessageIDs. If a duplicate arrives, it simply ACKs again without rewriting.
C. The Consumption Model (The "Read" Path)
This is the most critical part of the guarantee. We use an Explicit Acknowledgment model.
- Pull Model: Consumers pull messages (or the Broker pushes them via Long Polling).
- Unacked State: When a message is delivered to a Consumer, the Broker marks it as Unacked (In-Flight) but keeps it stored.
- Visibility Timeout: If the Consumer crashes or disconnects without processing, the message remains in the queue. It is not deleted.
- Consumer ACK: Only after the Consumer successfully processes the message logic does it send an
ACK back to the Broker.
- Commit/Deletion: Upon receiving the Consumer's ACK, the Broker marks the message as consumed (deletes it or marks the offset).
3. Handling Failure Scenarios
Here is how the system guarantees delivery during specific failures:
| Failure Scenario | System Reaction | Result |
|---|
| Broker crashes before writing to disk | Producer receives timeout/error. Producer retries. | Message delivered to new Leader. |
| Broker crashes after writing, before Replication | (If acks=all configured) Producer never receives ACK. Producer retries. | Message re-sent. |
| Broker crashes after Replication, before Consumer ACK | New Leader takes over. Consumer reconnects. Since no ACK was received, the message is still in the queue. | Message redelivered. |
| Consumer crashes during processing | Broker detects disconnect or Visibility Timeout expires. Message becomes visible in the queue again. | Message redelivered to another Consumer. |
| Network partition | System uses a consensus algorithm (Raft/Paxos) to determine the Leader. Minors are cut off. | Consistency maintained. |
4. Data Structure: The Write-Ahead Log
We don't use a random-access database; we use a sequential log.
Structure:
- Queue Name:
orders
- Segment File 1:
[Msg1, Msg2, Msg3...] (Immutable)
- Segment File 2:
[Msg4, Msg5...] (Active writing)
- Index: An in-memory or sparse on-disk index mapping
MessageID -> ByteOffset.
Consumer Offsets:
Instead of deleting messages immediately (which is slow on disk), we track a Cursor (Offset) for each consumer group.
- If Offset = 5, the consumer has processed up to message 5.
- If the consumer crashes, they reconnect and request: "Give me messages starting at Offset 6".
5. Ensuring Order (FIFO)
In a guaranteed delivery system with retries, order is hard. If Message 1 fails processing but Message 2 succeeds, what happens?
- Strict FIFO: The Broker will not send Message 2 until Message 1 is ACKed. If Message 1 fails and goes into a retry loop, the entire queue is blocked for that consumer.
- Best Effort: Allow Message 2 to process. (Most systems prefer this for throughput).
To implement Strict FIFO with Guaranteed Delivery:
- Use Sharding (Partitioning).
- Route all messages for a specific entity (e.g.,
OrderID=100) to the same Partition.
- The Consumer processes the Partition sequentially. If
Msg 1 fails, only that Partition stalls, not the whole queue.
6. Handling Duplicates (Idempotency)
Because we allow retries (to guarantee delivery), we will inevitably have duplicates.
- Scenario: Consumer processes Message A successfully, but the network fails before sending the ACK back to the Broker. Broker resends Message A.
- Solution: The Message Queue cannot solve this alone; the Consumer must be Idempotent.
- The Consumer logic should be:
IF NOT processed(MessageID) THEN process(MessageID) AND mark_processed(MessageID).
Summary of Guarantees
- Persistence: Every write is flushed to disk and replicated before ACK.
- Resilience: Automatic Leader failover ensures the queue is available even if nodes die.
- Delivery: Messages are redelivered indefinitely until an explicit ACK is received from the consumer.
- Safety: Unacknowledged messages are never lost.