In an IoT system, receiving messages continuously is usually considered a good sign. Devices are connected, telemetry is flowing, and the backend is receiving data.
But there is a point where receiving messages faster than you can process them becomes a problem.
Imagine a fleet of 2,000 devices publishing telemetry to an MQTT broker. Everything works fine until a network outage disconnects a large portion of the fleet. When connectivity returns, hundreds of devices reconnect almost simultaneously and begin sending their buffered messages.
The MQTT broker is receiving messages. Your consumers are running. But the database is processing data slower than the application is receiving it.
Queue sizes start increasing, memory consumption grows, processing latency rises, and eventually the ingestion service becomes unstable.
This is not necessarily an MQTT problem or a database problem alone. It is a capacity and flow-control problem within the entire ingestion pipeline.
In this article, I want to explore how I would approach this problem while designing a reliable IoT backend.
1. Why More Consumers Do Not Always Solve the Problem
A typical telemetry ingestion pipeline might look like this:
IoT Devices
|
v
MQTT Broker
|
v
Telemetry Consumers
|
v
Database
|
v
Analytics / Dashboard
Each component has its own processing capacity.
The devices generate messages, the broker handles message delivery, the consumers process incoming telemetry, and the database persists it.
The problem begins when the incoming rate consistently exceeds the processing rate of one of the downstream components.
For example, imagine the following numbers:
Component | Approximate capacity |
|---|
Incoming telemetry | 8,000 messages/sec |
Consumer processing | 6,000 messages/sec |
Database write capacity | 4,500 messages/sec |
These are hypothetical numbers, but they illustrate the problem.
The consumers may be capable of processing 6,000 messages per second, yet the database can only sustain 4,500 writes per second under the current workload.
The actual bottleneck is the database.
Adding more consumers may increase the number of concurrent database operations, but it will not necessarily increase the database's sustainable write capacity.
In some cases, it can make the situation worse by increasing connection pressure, lock contention, transaction overhead and resource consumption.
This is why I would first identify the bottleneck before scaling any component.
A useful way to think about a pipeline is that its sustainable throughput is constrained by its slowest component, assuming the components are sequentially dependent and the bottleneck cannot be bypassed.
Increasing capacity elsewhere does not remove that constraint.
2. Understand Backpressure and Bounded Queues
Backpressure is a mechanism or strategy that prevents an upstream component from overwhelming a downstream component when the latter cannot process work at the incoming rate.
In a telemetry ingestion system, I would not allow the consumer to accept unlimited work into memory.
Consider a simple Python queue:
import asyncio
queue = asyncio.Queue()
By default, this queue does not impose a maximum size.
If incoming messages continuously arrive faster than the worker processes them, the queue can grow indefinitely, consuming more memory.
Instead, I would consider a bounded queue:
import asyncio
queue = asyncio.Queue(maxsize=1000)
Now the queue has a defined capacity.
When the queue reaches its limit, producers attempting to add more items using await queue.put() will wait until space becomes available.
This is useful because it introduces a limit to the amount of work buffered in memory.
However, there is an important distinction when working with MQTT.
Blocking an application-level queue does not automatically provide backpressure to the MQTT broker. Depending on the client library and its architecture, messages may continue accumulating in internal buffers, callbacks may become blocked, or the application may experience different behavior.
Therefore, bounded queues should be part of a broader flow-control design that includes:
MQTT in-flight message limits where supported.
Controlled consumer concurrency.
Bounded application buffers.
Broker capacity and configuration.
Durable message handling.
Appropriate acknowledgement behavior.
A bounded queue is one mechanism, not a complete solution.
If the downstream database cannot keep up, the system needs a deliberate way to reduce, defer, buffer or otherwise manage incoming work.
3. Not Every Telemetry Message Needs the Same Processing Policy
This is one of the decisions I consider particularly important when designing IoT systems.
Not every message represents the same kind of business information.
For example, consider these messages:
Current temperature reading.
Current device battery level.
Machine vibration measurement.
Production cycle completed.
Equipment alarm triggered.
Configuration changed.
Device maintenance event.
Treating all these messages identically may be convenient, but it can be inefficient or even incorrect during overload.
Suppose a device sends its temperature every second.
If the backend is temporarily overloaded and has not yet processed the temperature reading from 10:00:01, the reading from 10:00:02 may already be available.
For a use case that only needs the latest temperature, storing every intermediate reading may not always be necessary.
However, if the device reports a production cycle completion event, dropping it because a newer event arrived would be a completely different decision.
I would classify telemetry according to its business meaning and retention requirements.
Message type | Possible processing strategy |
|---|
Latest temperature | Coalesce or retain latest state where appropriate |
Battery percentage | Latest-state update |
Historical sensor readings | Durable ingestion |
Production completion event | Preserve and process durably |
Equipment alarm | Prioritized durable handling |
Configuration change event | Preserve and audit |
Diagnostic message | Sampling or controlled retention, depending on requirements |
<text color="secondary" size="sm">These are example policies, not universal rules. Whether a message can be discarded, coalesced or delayed depends on its business purpose, regulatory requirements and downstream consumers.</text>
For example, if I only need to display the latest battery percentage on a dashboard, a state-oriented storage strategy may be sufficient.
But if I need to analyze battery degradation over six months, every relevant measurement may need to be preserved.
The difference is between storing the current state of a device and preserving the history of its events.
That distinction can significantly influence the architecture of an IoT ingestion system.
4. Batch Database Writes Without Losing Reliability
One of the practical ways I would improve telemetry ingestion is by batching database writes.
Instead of writing every message individually, consumers can collect a group of messages and persist them together.
For example:
Message 1 --->|
Message 2 --->|
Message 3 --->|----> Batch Insert ---> Database
Message 4 --->|
Message 5 --->|
Batching can reduce the overhead associated with individual database operations, especially when the database and driver support efficient bulk inserts.
However, batch size and flush interval should be carefully chosen.
A large batch may improve throughput but can also increase latency, memory consumption and the cost of retrying failed batches.
A small batch may provide lower latency but result in more database operations.
I would generally consider both a maximum batch size and a maximum time interval for flushing the batch.
For example, a batch could be flushed when either 100 messages have accumulated or 250 milliseconds have elapsed.
A simplified Python worker:
import asyncio
BATCH_SIZE = 100
FLUSH_INTERVAL = 0.25
async def process_telemetry(queue):
while True:
first = await queue.get()
batch = [first]
try:
while len(batch) < BATCH_SIZE:
try:
message = await asyncio.wait_for(
queue.get(),
timeout=FLUSH_INTERVAL,
)
batch.append(message)
except asyncio.TimeoutError:
break
# Persist the batch before acknowledging
# the corresponding MQTT messages.
await telemetry_store.insert_batch(batch)
for message in batch:
await message.ack()
finally:
for _ in batch:
queue.task_done()
This is a simplified illustration of batching, not a complete production MQTT consumer.
It assumes the queue contains message objects with acknowledgement methods and that the MQTT integration supports the required manual acknowledgement behavior.
It also assumes the storage layer handles duplicates appropriately.
If a batch insert fails, the messages must not be acknowledged as successfully persisted. The application needs a retry or recovery mechanism, and that mechanism must avoid uncontrolled retry loops.
The acknowledgement strategy also matters.
If messages are acknowledged as soon as they enter an in-memory queue, a process crash could result in data loss before the messages reach the database.
For messages that must be preserved, I would generally acknowledge them only after the required durable processing has succeeded, or after responsibility has been transferred to another durable system with an appropriate guarantee.
5. Handle Duplicate Messages and Recovery Properly
In distributed systems, retrying is unavoidable.
A consumer may successfully persist a message but fail before acknowledging it. The broker may redeliver that message.
The backend could therefore process the same telemetry more than once.
MQTT QoS 1 provides at-least-once delivery within its defined delivery protocol, meaning duplicate deliveries are possible. QoS 2 provides an exactly-once protocol-level delivery exchange, but that does not automatically guarantee that your database, application logic or physical device operation executes exactly once.
I would not rely on the MQTT QoS level alone to protect business data from duplicate processing.
Instead, I would design the persistence layer around idempotent processing wherever possible.
For example, a telemetry message could include:
{
"device_id": "device-1042",
"message_id": "msg-20261127-00125",
"event_timestamp": "2026-11-27T05:30:00Z",
"temperature": 34.7
}
The backend could use a unique constraint on an appropriate combination of identifiers, such as the device ID and message ID, to prevent duplicate historical records from being inserted.
For example:
CREATE TABLE telemetry (
device_id TEXT NOT NULL,
message_id TEXT NOT NULL,
event_timestamp TIMESTAMPTZ NOT NULL,
temperature NUMERIC,
PRIMARY KEY (device_id, message_id)
);
The application could then use an insert strategy that handles duplicate keys appropriately.
The exact implementation depends on the database, but the important idea is that message identity should be part of the persistence design.
If the consumer retries a message after a failure, the backend should not blindly create another historical record for the same logical event.
I would also consider recovery mechanisms for abandoned processing, bounded retries, dead-letter handling where supported, and monitoring for persistent failures.
6. Design for Reconnection Storms and Monitor the Pipeline
A healthy IoT backend should not assume that devices will always publish telemetry at a perfectly steady rate.
Network outages, firmware changes, power restoration and scheduled reconnects can create bursts of traffic.
For example, 2,000 devices might reconnect within a short period and begin transmitting buffered telemetry.
The backend should be prepared for this behavior.
Depending on the system, I would consider:
Device-side randomized reconnect delays.
Controlled telemetry publishing rates.
Bounded consumer concurrency.
Batch database writes.
Message prioritization.
Broker in-flight limits.
Durable buffering for critical data.
Capacity planning for reconnect scenarios.
I would also monitor the ingestion pipeline rather than relying only on service health checks.
Some useful metrics include:
Metric | Why it matters |
|---|
Incoming messages per second | Measures incoming workload |
Processed messages per second | Measures processing capacity |
Queue depth | Indicates accumulated work |
Oldest queued message age | Detects delayed processing |
Database write latency | Identifies storage bottlenecks |
Consumer processing latency | Measures ingestion efficiency |
Retry count | Indicates processing failures |
Duplicate message count | Tracks duplicate delivery |
Memory usage | Detects uncontrolled buffering |
Broker connection count | Tracks fleet connectivity |
Failed or rejected messages | Measures ingestion problems |
For me, queue depth alone is not enough.
A queue containing 10,000 messages may be perfectly manageable if consumers process them quickly. But a queue containing 500 messages that have been waiting for 20 minutes could indicate a serious problem.
I would pay particular attention to the age of the oldest unprocessed message, processing latency and the rate at which the backlog is growing.
If incoming messages consistently exceed processing capacity, the backlog will continue growing until the system runs out of available resources or reaches some other limit.
The goal is not to prevent every temporary backlog. The goal is to make sure the system handles overload predictably and recovers without losing data that must be preserved.
Conclusion
A reliable IoT ingestion pipeline is not simply about connecting devices to an MQTT broker and inserting messages into a database.
It is about understanding how each component behaves when the system receives more work than it can process.
Backpressure, bounded queues, batching, idempotent persistence, acknowledgement strategies and recovery mechanisms are all parts of that design.
I would also avoid treating every telemetry message as equally important. The business meaning of the data should determine whether it can be coalesced, delayed, sampled or must be preserved.
Adding more consumers is not always the answer. Sometimes the better solution is to control the flow of data, optimize the persistence layer, reduce unnecessary processing and make the system's overload behavior explicit.
Because in production IoT systems, receiving messages is only the first part of the problem. Processing them reliably is what matters.
Join the conversation! Your thoughts help the community grow.