Sub topic 1
Why Use a Message Queue?
Prerequisites
Assume basic programming, HTTP request/response, and familiarity with processes, threads, and network failures. The examples use Python concepts, but the design applies to other languages.
Why use a message queue
A message queue lets one service hand work to another without waiting for the work to finish. The sender is the producer. The service that handles the work is the consumer.
A synchronous HTTP call keeps the client waiting and fails immediately if the server is slow or unavailable. A queue separates the two services. The producer can continue after submitting a message, while the consumer processes it later.
This separation helps when:
- Work takes too long for one request.
- Traffic arrives in bursts.
- The consumer needs independent scaling.
- Temporary consumer failures should not lose work.
- The producer and consumer should be deployed independently.
The trade-off is that processing becomes asynchronous. A producer cannot assume that work has finished when the message is accepted. You must also handle retries, duplicate delivery, and delayed results.
Producers and consumers
A producer creates a message containing data such as an order ID or image location. A consumer reads the message and performs the requested work. The message should contain enough information for the consumer to work without relying on the producer's memory or process state.
A useful design treats the consumer as a separate failure boundary. The consumer can restart, and the queue can retain unprocessed messages while it is unavailable.
The broker and its queues
A broker is messaging infrastructure that accepts, stores, and delivers messages. A queue is an ordered collection of messages waiting for consumers. The broker tracks which messages are available and which have been delivered but not completed.
For a work queue, one message normally goes to one consumer. Multiple consumers can share the queue to process more work concurrently. Other messaging models, such as publish/subscribe, send an event to multiple subscribers.
Acknowledging messages
An acknowledgement, or ack, tells the broker that a consumer completed a message. The consumer should acknowledge only after the required side effect succeeds. If it acknowledges first and then crashes, the broker may discard work that never completed.
If the consumer crashes before the ack, a broker can redeliver the message. Therefore, reliable consumers must tolerate receiving the same message more than once.
Exercise
Why should a consumer acknowledge a message after processing rather than before it?
Show answer
An early acknowledgement can cause lost work if the consumer crashes before processing finishes.