Producer-Consumer
One producer, multiple consumers. Each message processed once. Perfect for task distribution.
Synchronous systems: Service A calls Service B and waits for response.
Problems:
Solution: Message Queues - Asynchronous, decoupled communication!
A message queue is a buffer that stores messages between senders (producers) and receivers (consumers). It acts as an intermediary component that enables asynchronous, decoupled communication between services or components in a distributed system.
At its essence, a message queue is a temporary storage mechanism that decouples the production of messages from their consumption. Instead of a producer directly calling a consumer and waiting for a response, the producer sends a message to the queue and continues with other work. The consumer retrieves messages from the queue when it’s ready to process them, completely independently of when the messages were produced.
This decoupling provides several critical benefits: temporal decoupling (producer and consumer don’t need to be active at the same time), spatial decoupling (they don’t need to know each other’s location), and synchronization decoupling (they don’t need to wait for each other).
One producer, one or more consumers. Each message processed once.
Characteristics:
Use cases:
One publisher, multiple subscribers. Each subscriber gets copy of message.
Characteristics:
Use cases:
Message may be lost, but never duplicated.
Characteristics:
Use when: Non-critical messages, metrics, logs
Message delivered at least once, may have duplicates.
Characteristics:
Use when: Critical messages, order processing, payments
Message delivered exactly once. Requires deduplication.
Characteristics:
Use when: Financial transactions, critical operations
Ordering ensures messages processed in sequence.
Example: User account balance updates
Message 1: Balance = 100Message 2: Balance = 150 (add 50)Message 3: Balance = 120 (subtract 30)Correct order: 100 → 150 → 120
Wrong order: 100 → 120 → 150 = 150 (wrong!)
1. Per-Partition Ordering (Kafka)
2. Per-Queue Ordering (RabbitMQ)
3. Global Ordering
At the code level, message queues translate to producer/consumer classes, message handlers, and acknowledgment logic.
Producer-Consumer
One producer, multiple consumers. Each message processed once. Perfect for task distribution.
Pub-Sub
One publisher, multiple subscribers. Each gets copy. Perfect for event broadcasting.
Delivery Guarantees
At-least-once most common. Requires idempotent consumers. Exactly-once is hardest but most reliable.
Ordering Matters
Message ordering critical for state changes. Per-partition ordering balances order and parallelism.