Message Queue - Kafka and RabbitMQ
Message Queue
a. Benefits of Message Queue?
- Decoupling: Producers and Consumers don’t need to know each other. Each does its ownjob, and either one can go online or offline without affecting the other
- Reduce Load During Peak Time: Traffic During Peak periods is stored on the message queues first, then the backend service process the message at its own pace to avoid overwhelmed
- Asynchronous processing: After a user place an order, they don’t have to wait for point calculation, SMS notificcations, and etc to finish. The main flow returns first and other operations are done asynchronously in the background
Async processing vs. service decoupling Async processing is about time, is about let the caller return a response quickly withou waiting Servcie Decoupling is about dependency, is to let the upstream service no need to care the downstream serveice. For Example, the order service sends a message to the points service. If you emphasize the user gets a fast response after placing an order, it is async processing. if you empahsize that adding a marketing service or data service without requires changes to the order service, it is service decoupling
b. Queue Model vs Pub Sub Model
Queue model: One Producer sends messages to a queue, and multiple consumers compete for them. Each message is processed by only one consumer
Pros: Good real-time performance, messagse reach consumer immediately
Publish/Subscribe model: One produceer ssends messages to a Topic, and multiple subscribers each indenpendently receive a copy of every message.
c. Push mode vs Pull mode
Push mode: The message queue (broker) actively pushes messages to consumers Pros: Good real-time performance, because messages reach consumers immediately Cons: Hard to control consumption rate, which can overload consumers under high concurrency scenario
Pull mode: Consumers actively pull messages from the message queue (broker) Pros: Consumers decide how often to pull based on their ownload, avoiding overload. Cons: Message might delay (Not as real time as push mode) if the pull interval is long
d. Handing duplicate messages (Idempotency)
To avoid duplicate message, the only solution is to make the consumer idempotency, so consume same message will produce the same result regardless of number of times
- Deduplicate by unique ID
- Generate a global unique ID (UUID, Snowflake algo)
- When a consumer receive a message, Consumer check for duplicates in Redis or Database
- If Exist: Return/Discard immediately (Treat as duplicate)
- If Not Exist: Execute Business Logic and save in Redis or Database
- Use Business logic’s own idempotency
- Method A: Use Database index
- For example, in a money transfer, use the order number as a unique database index. A duplicate insert triggers a unique-constraint violation, and the transaction rolls back automatically, so no money is deducted twice
- Method B: State machine control
- Design a strict state machine: once an order changes from “Pending Payment” to “Paid,” any further “payment succeeded” message fails the state check and is simply discarded.
- Method A: Use Database index
e. How to Prevent message lost
1) Production stage
After sending a message, the producer must wait for the Broker’s acknowledgment. If the Broker returns a failure or times out, the producer must retry. For synchronous sends, handle the return value. For asynchronous sends, handle failures in the callback.
2) Storage stage
After receiving a message, the Broker must persist it to disk before returning success. If it tells the producer “received” while the message is still only in memory, a power loss means the message is gone. In a clustered deployment, ideally configure the message to be replicated to at least 2 replicas before returning the acknowledgment.
3) Consumption stage
The consumer must send the ACK to the Broker only after the business logic has actually finished. Never acknowledge immediately on receiving the message. If the consumer crashes halfway through processing, that message is lost.
f. Ways to guarantee message order
Single producer and single consumer:
- Use one producer to send messages to a single queue, processed by a single consumer. This guarantees messages are consumed in the order the producer sent them.
- Simple, but it easily becomes a performance bottleneck and can’t take advantage of concurrency.
Partitions and Partition Key:
- In message queues that support partitions (e.g., Kafka, RocketMQ), you can use a Partition Key to send messages to a specific partition. Each partition is ordered internally, so messages with the same Partition Key are consumed in order.
- For example, in an order processing system, use the order number as the Partition Key so all messages for the same order are routed to the same partition, guaranteeing that order’s message sequence.
Ordered Queue:
- Some message queue systems (e.g., RabbitMQ) support ordered queues, where messages are stored and delivered in the same order. If you use a single ordered queue, messages are consumed in order.
g. Message Backlog in Message Queue
A message backlog happens when messages are produced much faster than they are consumed, so large numbers of messages pile up in the queue.
- Increase the number of consumer threads in single instance
- Increase the number of consumer instances
- Optimize consumer logic to check consumer code to reduce processing time (fewer I/O Operatio, batch processing, optimize database operations)
- Rate-limit the producer side to reduce the production rate and keep the backlog from getting worse.
- Drop or delay non-critical messages and keep only high-priority ones, to improve system responsiveness.
Note on point 2: the number of partitions for the Topic is greater than or equal to the number of consumer instances. else number of consumers > number of partitions, will cause the some consumer instance idle
Follow-up questions
Q: If a consumer restarts or crashes, will the backlogged messages be lost? A: No. The messages are still stored on the Broker. Kafka persists messages on disk, and the Consumer Group’s offsets are persisted too, so after restarting, the consumer resumes from the last offset.
Q: A consumer takes 1 second to process one message, and the QPS requirement is 10,000. How would you design this?

- A: At 1 second per message, 10,000 QPS requires 10,000 concurrent workers. If each machine runs 100 consumer threads, you need 100 consumer machines, and the Topic needs at least 100 partitions, with each consumer bound to one partition. If the per-message time truly can’t be reduced, you just have to add machines.
- The better approach is to analyze why processing takes 1 second and look for optimizations, like batch processing or async I/O.
Kafka
a. Kafka Theory

- Producer: Produce messages to topic
- Topic:
- 1 topic can split to multiple partitions and stored in multiple broker
- 1 topic = 1 type of business data (click rate for the product page)
- Partition
- Each Partition is spit to multiple brokers
- Broker
- Each broker have different partitions in different topic
- Consumer Group
- Each consumer group consume one complete topic data
- but consumers in same consumer group do not compete data with other consumer
b. Relationship between Partition and Consumer
When Consumer Less than Partition, the consumer will consume both partition

When No of Consumer = No of Partition
1 consumer consume 1 partition

When No of Consumer > No of Partition, some consumer will idle (usually is oldest consumer)

c. Kafka Partition Ordering

Kafka guarantee within a single partitions, the offset order of message is consistent with the order in which the messagees were produced. the newer the message in same partition, the larges its offset
Offset/order in different partition cannot compare
A Consumer consumes every message in a partition in order. It can report (commit) to Kafka the position it has currently read up to (offset) after each message it reads, or it can report intermittently (commit once every N messages, or once every certain interval of time).
When a Consumer restarts, Kafka uses the largest offset that the Group last committed to decide where to start consuming from.
Different Consumer Group can have different offset of same partition
Message in partition won’t deleted after received, so it can be replay early message by offset to early offset
So, when a user want to update the inventory and delete the inventory, but due to network delay, delete may run first then update, but since inventory already deleted, it is not point to update, and this may cause error
Solotion 1:
- When construct the Kafka message, use the productID as th key, Kafka use the hash function to ensure that same key maps to one definite partiions. And since one partitions map to one definie consumer. Hence all messages produced by a single product/inventory will be consumed by sequence by the same consumer
Solution 2 (Better Approach):
- We can add a deleteAt and updateAt timestamp, and if we delete first then upate (due to network delay), then since deleteAt is after updateAt timestamp, so when update event reach, just discard the update event, since it is happened before delete
d. How producer write to partition
A producer can write to partition is 3 ways
- Producer explicitly choose a partition to send
- If no partition is specified, a Partitions is chosen based on message’s key via hash algo
- When no partition is specified and no partition key, partitions are choosen in a round-robin order
e. Kafka Cluster Replication
In one Kafka Cluster, a topic single partition may in 3 broker, one of its is leader and other will follower.
- The Producer queries the Kafka Cluster to obtain the Leader of a specific Partition of a specific Topic.
- The Producer sends the data to the Leader, and the Leader writes the data to its local disk.
- Followers pull the data from the Leader and write the data to their local disks.
- Followers return an ACK to the Leader, confirming success.
- The Leader returns an ACK to the Producer, confirming success.
f. Kafka with Go
For more information: check for https://github.com/Fulim13/kafka
common.go
package common
const (
TOPIC = "user_click"
)
producer/main.go
package main
import (
"context"
"errors"
"fmt"
"time"
"kafkademo/common"
"github.com/segmentio/kafka-go"
)
// Produce messages.
func writeKafka(ctx context.Context) {
writer := &kafka.Writer{
Addr: kafka.TCP("localhost:9092"), // variadic, multiple broker ip:port values are supported
Topic: common.TOPIC, // one topic for every message. Without it, each kafka.Message{} has to carry its own Topic
Balancer: &kafka.Hash{}, // hash the message key to pick the partition
WriteTimeout: 1 * time.Second, // write timeout
RequiredAcks: kafka.RequireNone, // RequireNone does not wait for an ack: fastest, least safe. RequireOne waits until the leader has written the message. RequireAll waits until the leader and all followers have written it.
AllowAutoTopicCreation: true, // create the topic if it does not exist. In production this is usually false and an operator creates the topic with the right partition count.
}
defer writer.Close() // remember to close the connection
for { // endless loop, keep sending messages to kafka
for i := 0; i < 3; i++ { // allow up to 3 attempts
if err := writer.WriteMessages(ctx, // batch write, atomic: either all messages are written or none are
kafka.Message{Key: []byte{1}, Value: []byte("hello")},
kafka.Message{Key: []byte{1}, Value: []byte("how")},
kafka.Message{Key: []byte{1}, Value: []byte("are")},
kafka.Message{Key: []byte{2}, Value: []byte("you")}, // equal keys always land in the same partition
kafka.Message{Key: []byte{2}, Value: []byte("lady")},
); err != nil {
// Writing to a brand new topic fails until the broker has created it and elected a
// leader, which the first write itself triggers. Both errors are expected once, so
// back off briefly and retry instead of reporting them.
if errors.Is(err, kafka.LeaderNotAvailable) || errors.Is(err, kafka.UnknownTopicOrPartition) {
time.Sleep(500 * time.Millisecond)
continue
} else {
fmt.Printf("batch write message failed: %v", err)
}
} else {
break // one success is enough, stop retrying
}
}
time.Sleep(time.Second) // small pause between batches
}
}
func main() {
ctx := context.Background()
go writeKafka(ctx)
select {} // main never exits
}
// go run ./producer
consumer/main.go
package main
import (
"context"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"kafkademo/common"
"github.com/segmentio/kafka-go"
)
var (
reader *kafka.Reader
)
// List every partition together with the topic it belongs to.
func listTopicAndPartition() {
conn, err := kafka.Dial("tcp", "localhost:9092")
if err != nil {
panic(err.Error())
}
defer conn.Close()
partitions, err := conn.ReadPartitions()
if err != nil {
panic(err.Error())
}
for _, p := range partitions {
if strings.HasPrefix(p.Topic, "__") {
continue
}
fmt.Printf("partition %d topic %s\n", p.ID, p.Topic)
}
}
// Consume messages.
func readKafka(ctx context.Context) {
reader = kafka.NewReader(kafka.ReaderConfig{
Brokers: []string{"localhost:9092"}, // multiple broker ip:port values are supported
Topic: common.TOPIC,
CommitInterval: 1 * time.Second, // how often the offset is committed automatically, i.e. how often we report back to kafka how far we have read
GroupID: "recommend_biz", // a message is delivered only once within a group. Note: without a GroupID a reader can only consume a single partition, so you need at least as many consumers as partitions to consume everything
// Partition: 0, // Partition and GroupID cannot be set at the same time
StartOffset: kafka.FirstOffset, // where to start when a partition has no committed offset yet (e.g. the first time it is read). Only FirstOffset or LastOffset are valid; LastOffset skips the data produced before the consumer started. StartOffset only takes effect when GroupID is set.
})
// defer reader.Close() // the loop below never ends under normal conditions, so readKafka() never returns and the defer never runs. Instead we listen for signals 2 and 15 and close the reader there, which is why reader is a package-level variable.
for { // new messages can arrive at any time, so this is an endless loop, similar to reading from a channel
if message, err := reader.ReadMessage(ctx); err != nil {
fmt.Printf("read message from kafka failed: %v", err)
break
} else {
offset := message.Offset
fmt.Printf("topic=%s, partition=%d, offset=%d, key=%s, message content=%s\n", message.Topic, message.Partition, offset, string(message.Key), string(message.Value))
}
}
}
// Listen for signals 2 and 15 and close the reader when one arrives.
func listenSignal() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) // register signals 2 and 15
sig := <-c // block until a signal arrives
fmt.Printf("receive signal %s\n", sig.String())
if reader != nil {
reader.Close() // flush the offsets that have not been committed yet
}
os.Exit(0) // exit the process
}
func main() {
ctx := context.Background()
listTopicAndPartition()
go listenSignal()
readKafka(ctx)
}
// Try opening 3 terminals and starting 3 consumers. A partition is assigned to at most one consumer
// in the group, so any consumer beyond the topic's partition count sits idle and receives nothing.
// A topic created automatically by the producer has a single partition unless configured otherwise.
// go run ./consumer
Open Kafka with docker
docker run -d --name kafka -p 9092:9092 apache/kafka:4.1.2
Create 2 partition for topicc user_click
docker exec -it kafka /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --create --topic user_click --partitions 2
Run the producer to produce data to partition 1 and partition 2 of user_click topic
go run ./producer
Run 3 consumer to receive data from partition Note: You will see only 2 consumer is receive the data, this is because data in one partition is only consume by one consumer
go run ./consumer
go run ./consumer
go run ./consumer
First Consumer

Second consumer

Third Consumer

RabbitMQ
a. RabbitMQ Architecture (Direct, Topic, and Fanout)
A picture is worth a thousand words.

- Producer: produce message to an exchange
- Consumer: consume the message
- Exchange: decide the where the messages should go to which queu based on binding key
- One Exchange can route messages to multiple queue
- Queue: receive messages from exchange based on binding key and consumed by consumer
- A Queue can have multiple consumers
- Multiple consumer can compete for one queue messages
- Normally, 1 message is deliver to one competing consumer
- Consumer in different queue do not compete with each other.
- Each queue gets its own copy if the exchange routes the message to both.
- Hence, If you want multiple independent services to receive the same event, give them separate queues.
- Binding Key: a key pattern that bind the exchange and queue, when the pattern match, the exchange send to the queue
-
- Direct: Sends a message only to queues whose binding key exactly matches the message’s routing key (e.g.
errorgoes only to theerrorqueue).
- Direct: Sends a message only to queues whose binding key exactly matches the message’s routing key (e.g.
- Topic: Sends a message to queues whose binding pattern matches the routing key, using wildcards:
*for one word and#for zero or more words (e.g.order.*matchesorder.created). - Fanout: Sends a copy of every message to all bound queues and ignores the routing key completely, like a broadcast.
b. ACK, NACK and Dead Letter Queue
- ACK: the consumer confirms receive the message and broker remove the mesages from queue
- Temporary fails ➡️ NACK (requeue = true): the message goes back into same queue
- Permanent fails ➡️ Dead-letter-exchange/queue/consumer, let the dead letter consumer handle the message when TTL expired, queue full or Permanent fails
- Permanent fails ➡️ NACK (requeue = false), discard permanently from queue
- If consumer channel closes before it acks, the messages automatically requeue

c. Prefetch
Prefetch = how many unacknowledged message the broker will push to consumer at once
This show that the first three messages will send to the consumer A at once (batch), then another three message will send to consumer B and another three message will send to consumer C
d. Durable vs transient
| Queue | Message | After restart |
|---|---|---|
| durable | persistent | Queue and Message survives |
| durable | transient | Queue survices, Message lost |
| transient | persistent | Queue and Message both lost |
| transient | transient | Everything lost |