TL;DR
Use MQTT for IoT devices with limited battery, unreliable networks, or pub-sub messaging patterns. Use HTTP for standard web and mobile APIs. MQTT uses 2-byte headers compared with HTTP’s 100+ bytes, making it suitable for constrained devices. Modern PetstoreAPI uses MQTT for pet tracking collars and smart feeders.
Introduction
Imagine a pet tracking collar that sends a location update every five minutes. It runs on a coin-cell battery designed to last six months.
With HTTP, the battery might last only two weeks. With MQTT, it can last the full six months.
HTTP is the standard choice for web and mobile APIs, but it was designed for general-purpose request-response communication. MQTT (Message Queuing Telemetry Transport) was designed for constrained devices operating with limited bandwidth, battery power, and unreliable networks.
Modern PetstoreAPI uses both protocols:
- HTTP for web and mobile applications
- MQTT for IoT devices such as pet tracking collars, smart feeders, and health monitors
If you’re building or testing IoT APIs, Apidog supports MQTT testing alongside HTTP. You can test pub-sub patterns, validate message formats, and simulate network failures.
In this guide, you’ll learn when MQTT is a better fit than HTTP, how Modern PetstoreAPI uses both protocols, and how to test each approach.
What Is MQTT?
MQTT is a lightweight publish-subscribe messaging protocol designed for IoT applications.
How MQTT Works
MQTT clients publish messages to topics. Other clients subscribe to those topics. An MQTT broker routes messages between publishers and subscribers.
For example:
Publisher: Pet collar
Topic: pets/019b4132/location
Payload: {"lat":37.7749,"lng":-122.4194,"battery":85}
Subscriber: Mobile app
Subscription: pets/019b4132/location
Receives: {"lat":37.7749,"lng":-122.4194,"battery":85}
The collar does not need to know which applications consume the message. It only publishes to the topic. Any authorized subscriber can receive updates.
Core MQTT Features
- Small headers — MQTT headers can be as small as 2 bytes, compared with roughly 100–500 bytes for typical HTTP requests.
- Persistent connections — Clients can keep a connection open instead of creating a new connection for every message.
- Quality of Service (QoS) — QoS 0, 1, and 2 provide different delivery guarantees.
- Last Will messages — A broker can publish a message when a client disconnects unexpectedly.
- Retained messages — A broker can store the latest message on a topic and deliver it to new subscribers.
MQTT vs. HTTP
| Feature | MQTT | HTTP |
|---|---|---|
| Header size | As small as 2 bytes | Typically 100–500 bytes |
| Communication pattern | Publish-subscribe | Request-response |
| Connection | Persistent | Per request, unless reused |
| Bandwidth usage | Very low | Higher |
| Battery impact | Minimal | Significant for constrained devices |
| Browser support | Through WebSocket | Native |
Bandwidth Example
Assume a device sends 1,000 location updates per day:
- HTTP: approximately 420 KB per day, or 12.6 MB per month
- MQTT: approximately 52 KB per day, or 1.56 MB per month
In this example, MQTT uses approximately eight times less bandwidth.
Actual usage depends on payload size, connection behavior, TLS settings, and protocol overhead. The example illustrates why MQTT is useful for bandwidth-constrained devices.
When MQTT Is the Better Choice
1. Battery-Powered IoT Devices
For a pet tracking collar:
- MQTT: six months of battery life
- HTTP: two weeks of battery life
MQTT helps reduce radio usage through persistent connections and smaller protocol overhead.
Use MQTT when the device:
- Runs on a small battery
- Sends frequent updates
- Has limited processing power
- Operates over a metered or low-bandwidth connection
2. Unreliable Networks
Cellular IoT devices may frequently lose connectivity. MQTT provides features that help applications recover:
- QoS for delivery guarantees
- Automatic reconnection in client libraries
- Session persistence
- Last Will messages for detecting unexpected disconnects
A typical implementation should define what happens when a device disconnects and how it resynchronizes after reconnecting.
3. Many-to-Many Communication
MQTT topics make it easy for multiple devices and applications to exchange messages.
For a smart pet feeder:
Feeder 1 publishes to pets/019b4132/feeding
Feeder 2 publishes to pets/019b4127/feeding
App 1 subscribes to pets/+/feeding
App 2 subscribes to pets/019b4132/feeding
The + wildcard matches one topic level, so pets/+/feeding receives feeding events for all pets.
4. Real-Time Sensor Data
A pet health monitor might send an update every second:
Topic: pets/019b4132/health
QoS: 0
MQTT is useful for this workload because it avoids repeated request setup, minimizes latency, and supports high-frequency messages over a persistent connection.
When HTTP Is the Better Choice
1. Standard Web and Mobile Applications
HTTP is usually the simplest option for user-facing applications because:
- Every major language has HTTP libraries
- Browsers support it natively
- Proxies and firewalls commonly allow it
- HTTP APIs are familiar to most developers
2. Request-Response Operations
Use HTTP when a client needs to request a specific resource and receive a direct response.
For example:
GET /pets/019b4132
200 OK
Content-Type: application/json
{
"name": "Fluffy",
"species": "CAT"
}
This interaction is naturally represented by HTTP. Using MQTT would require defining request and response topics and correlating messages manually.
3. Caching
HTTP provides established caching mechanisms, including:
- Browser caching
- CDN caching
- Proxy caching
- Cache-Control headers
- Conditional requests
MQTT does not provide HTTP-style caching. Although retained messages can provide the latest value on a topic, they are not a replacement for general-purpose HTTP caching.
4. RESTful APIs
HTTP provides standard methods, status codes, and semantics:
- Methods:
GET,POST,PUT,DELETE - Status codes:
200 OK,201 Created,404 Not Found - Standard request and response handling
- Established error-handling conventions
How Modern PetstoreAPI Uses MQTT
Modern PetstoreAPI uses HTTP for user-facing APIs and MQTT for IoT device communication.
Pet Tracking Collars
A collar publishes location updates to a pet-specific topic:
Topic: pets/019b4132/location
QoS: 1
{
"lat": 37.7749,
"lng": -122.4194,
"battery": 85,
"timestamp": "2026-03-13T10:30:00Z"
}
A mobile application subscribes to the topic:
const mqtt = require('mqtt');
const client = mqtt.connect('mqtts://mqtt.petstoreapi.com');
client.on('connect', () => {
client.subscribe('pets/019b4132/location', (error) => {
if (error) {
console.error('Subscription failed:', error);
}
});
});
client.on('message', (topic, message) => {
const location = JSON.parse(message.toString());
updateMap(location.lat, location.lng);
});
The example uses QoS 1, which provides at-least-once delivery. Consumers should therefore be prepared to handle duplicate messages.
Smart Feeders
A feeder subscribes to its feeding schedule:
Topic: pets/019b4132/feeding-schedule
Retained: true
{
"times": ["08:00", "18:00"],
"amount": 100
}
The retained message allows a feeder to receive the latest schedule when it subscribes.
The feeder publishes feeding events:
Topic: pets/019b4132/feeding-events
{
"timestamp": "2026-03-13T08:00:15Z",
"amount": 100,
"dispensed": true
}
Health Monitors
A health monitor publishes high-frequency vital updates:
Topic: pets/019b4132/health
QoS: 0
{
"heartRate": 120,
"temperature": 38.5,
"activity": "resting"
}
QoS 0 is suitable when occasional message loss is acceptable and the device will publish another reading shortly.
Testing MQTT with Apidog
Apidog supports MQTT testing alongside HTTP and other protocols.
Test an MQTT Pub-Sub Flow
Use the following workflow:
- Connect to the MQTT broker.
- Subscribe to the topic used by the application.
- Publish a test message from a separate client or request.
- Validate the received topic and payload.
- Test the behavior for QoS 0, 1, and 2.
- Confirm that consumers handle duplicate or delayed messages where applicable.
For the pet location example, publish a message to:
pets/019b4132/location
Then verify that the mobile application receives and parses the expected payload.
Simulate Network Failures
Test how devices and consumers behave when connectivity changes:
- Disconnect and reconnect the client
- Test automatic reconnection
- Verify QoS 1 and QoS 2 delivery behavior
- Check Last Will messages
- Validate session persistence
- Confirm that retained messages are delivered to new subscribers
These tests are especially important for cellular devices that can lose connectivity without warning.
Compare MQTT with HTTP
Implement the same operation through both protocols and compare:
- Bandwidth usage
- Message latency
- Battery or connection overhead
- Delivery behavior
- Data consistency
- Recovery after network failures
This gives you measurable criteria for choosing a protocol instead of choosing based only on familiarity.
Conclusion
MQTT and HTTP solve different problems:
- Use MQTT for constrained IoT devices, unreliable networks, real-time sensor data, and pub-sub communication.
- Use HTTP for standard web and mobile APIs, request-response operations, caching, and RESTful resources.
Modern PetstoreAPI uses both protocols: HTTP for user-facing APIs and MQTT for IoT devices. The right choice depends on your device constraints, communication pattern, reliability requirements, and caching needs—not on which protocol is universally “better.”
Test both protocols with Apidog to determine which implementation best fits your use case.
FAQ
Can MQTT Work Over HTTP?
MQTT can run over WebSocket, which works over HTTP. This can help with firewall traversal and browser compatibility, but it adds transport overhead compared with a direct MQTT connection.
What Are MQTT QoS Levels?
- QoS 0: At most once — The message is delivered without acknowledgment. It may be lost.
- QoS 1: At least once — The message is acknowledged, but it may be delivered more than once.
- QoS 2: Exactly once — The protocol provides the strongest delivery guarantee and prevents duplicate delivery.
Choose the lowest QoS level that meets your application’s requirements.
Is MQTT Secure?
MQTT supports TLS encryption through MQTTS and username/password authentication. Modern PetstoreAPI uses MQTTS for its IoT devices.
In production, use encrypted connections, authenticate clients, and restrict which topics each client can publish or subscribe to.
Can Browsers Use MQTT?
Browsers can use MQTT over WebSocket. Libraries such as MQTT.js support browser environments.
How Does MQTT Compare with WebSocket?
MQTT is a messaging protocol that can run over WebSocket. WebSocket is a transport layer that provides a persistent, bidirectional connection.
MQTT adds IoT-specific messaging features such as:
- Pub-sub topics
- QoS levels
- Retained messages
- Last Will messages
Use WebSocket directly when you need a custom bidirectional protocol. Use MQTT when you need standardized pub-sub messaging and MQTT delivery features.
Top comments (0)