Existing customer? Login
When building IoT applications or data streaming systems, choosing the right messaging protocol is crucial. This guide compares MQTT and Kafka, helping you determine which is best for your specific use case.
MQTT (Message Queuing Telemetry Transport) is a lightweight publish-subscribe messaging protocol designed for constrained devices and low-bandwidth, high-latency, or unreliable networks.
Key characteristics:
Apache Kafka is a distributed event streaming platform designed for high-throughput, fault-tolerance, and durability of data streams.
Key characteristics:
MQTT uses a publish-subscribe (pub/sub) model where:
Kafka uses a distributed log model where:
MQTT focuses on message delivery with configurable persistence:
Kafka prioritizes persistence and processing:
Feature | MQTT | Kafka |
---|---|---|
Primary Use Case | IoT communication, constrained devices | Data streaming, event sourcing, log aggregation |
Message Size | Small (optimized for low overhead) | Large (optimized for throughput) |
Throughput | Moderate (thousands of msg/sec per broker) | High (millions of msg/sec across cluster) |
Latency | Very low (milliseconds) | Low to moderate (milliseconds to seconds) |
Message Ordering | Per-topic ordering (with QoS 1 or 2) | Strong ordering per partition |
Client Resource Requirements | Very low (can run on microcontrollers) | Moderate to high (JVM-based) |
Message Retention | Limited (offline message queuing) | Extensive (configurable log retention) |
Protocol | TCP/IP, WebSockets | TCP/IP |
Scalability | Vertical, limited horizontal (clustering) | Highly horizontally scalable (distributed) |
In many IoT architectures, MQTT and Kafka work together as complementary technologies:
MQTT at the Edge, Kafka in the Backend: A Common Architecture for IoT Data Processing
A common pattern is to use MQTT at the edge for device communication, then bridge to Kafka for backend processing:
This architecture leverages the strengths of both protocols:
Publishing sensor data with MQTT using Python:
import paho.mqtt.client as mqtt
import json
import time
import random
# Connect to MQTT.pro broker
client = mqtt.Client("sensor_publisher")
client.username_pw_set("username", "password")
client.connect("broker.mqtt.pro", 1883, 60)
# Publish temperature readings every 5 seconds
while True:
temperature = round(random.uniform(20.0, 25.0), 1)
payload = json.dumps({"device_id": "sensor-001", "temperature": temperature, "timestamp": time.time()})
# Publish with QoS 1 to ensure delivery
client.publish("sensors/temperature", payload, qos=1)
print(f"Published: {payload}")
time.sleep(5)
Consuming and processing the same data with Kafka using Python:
from kafka import KafkaConsumer
import json
# Connect to Kafka broker
consumer = KafkaConsumer(
'sensors.temperature',
bootstrap_servers=['kafka-broker:9092'],
auto_offset_reset='earliest',
value_deserializer=lambda m: json.loads(m.decode('utf-8'))
)
# Process incoming messages
for message in consumer:
data = message.value
device_id = data['device_id']
temperature = data['temperature']
timestamp = data['timestamp']
# Process data (e.g., alert on high temperatures)
if temperature > 24.0:
print(f"ALERT: High temperature of {temperature}°C detected from {device_id}")
else:
print(f"Normal temperature of {temperature}°C from {device_id}")
Simple bridge to connect MQTT topics to Kafka using Python:
import paho.mqtt.client as mqtt
from kafka import KafkaProducer
import json
# Kafka producer setup
producer = KafkaProducer(
bootstrap_servers=['kafka-broker:9092'],
value_serializer=lambda m: json.dumps(m).encode('utf-8')
)
# MQTT callback when message is received
def on_message(client, userdata, msg):
try:
# Convert MQTT topic to Kafka topic (replace / with .)
kafka_topic = msg.topic.replace("/", ".")
# Parse JSON payload
payload = json.loads(msg.payload.decode('utf-8'))
# Send to Kafka
producer.send(kafka_topic, payload)
print(f"Forwarded message from MQTT topic {msg.topic} to Kafka topic {kafka_topic}")
except Exception as e:
print(f"Error processing message: {e}")
# Set up MQTT client
client = mqtt.Client()
client.username_pw_set("username", "password")
client.on_message = on_message
# Connect and subscribe
client.connect("mqtt.broker.com", 1883, 60)
client.subscribe("sensors/#") # Subscribe to all sensor topics
# Start the loop
client.loop_forever()
MQTT and Kafka serve different but complementary purposes in modern data architectures:
Understanding the strengths and limitations of each protocol allows you to choose the right tool for each part of your architecture. In many cases, using both together provides the ideal solution for end-to-end IoT data processing.
With MQTT.pro's serverless MQTT broker service, you can quickly set up the edge communication layer of your IoT architecture, providing a reliable foundation that integrates seamlessly with Kafka and other backend systems.
Implement your MQTT edge communication layer today.