↓ Skip to main content
  1. Engineering Notes & Articles/

IoT Backend & Time-Series Data Pipeline: Brokers, Workers, and Scalable Storage

Practical IoT Engineering - This article is part of a series.
Part 8: This Article

Getting a microcontroller to publish sensor readings over TLS MQTT is only half of an end-to-end IoT system. Once five hundred deployed nodes begin reporting temperature, vibration, power draw, and GPS coordinates every few seconds, the cloud infrastructure on the receiving end faces a completely different engineering challenge than a typical CRUD web application.

In a standard e-commerce or SaaS app, users read data far more often than they write it, and records are updated in place. IoT telemetry flips that ratio upside down: 99% of database traffic is continuous, append-only writes, while queries typically scan wide time windows to compute averages, detect anomalies, or render live dashboard charts. Pointing an MQTT broker directly at an unoptimized relational table quickly leads to lock contention, bloated B-tree indexes, and stalled dashboards.

Designing a scalable IoT backend means decoupling message ingestion from database storage, batching high-frequency writes, choosing storage engines built for time-series data, and streaming real-time updates to operators without polling loops.


End-to-End Cloud Ingestion Architecture
#

Rather than having one monolithic server maintain thousands of stateful TCP sockets while simultaneously running heavy SQL aggregations, production IoT backends split the pipeline into four specialized stages:

[Edge Nodes] ──(MQTT/TLS)──> [MQTT Broker] ──(Rule Engine / Webhook / Queue)──> [Ingestion Workers] ──(Batch Insert)──> [Time-Series DB]
                                   │                                                                                         │
                            (MQTT over WS)                                                                            (Analytical API)
                                   │                                                                                         │
                                   v                                                                                         v
                        [Live Operator Dashboard] <──────────────────────────────────────────────────────────────────────────┘
  1. MQTT Broker (Connection & Routing Tier): Handles tens of thousands of persistent TLS connections, enforces per-device topic ACLs, manages Last Will and Testament (LWT) presence states, and filters traffic using built-in SQL rule engines (such as in EMQX or HiveMQ).
  2. Message Queue / Buffer (Shock Absorber): When thousands of cellular nodes reconnect simultaneously after a regional tower outage and replay their offline flash ring buffers, a queue (such as Kafka, NATS, or Cloudflare Queues) absorbs the write spike so downstream databases are never overwhelmed.
  3. Stateless Ingestion Workers: Lightweight serverless functions or worker containers (running on edge runtimes like Cloudflare Workers with Hono, or Node.js/Go services) validate JSON/binary schemas, enrich payloads with site metadata from a device registry, and batch rows together.
  4. Dual-Storage Split (Metadata vs. Telemetry): Device inventory, user permissions, and alert thresholds live in a standard relational database (PostgreSQL / SQLite), while high-frequency sensor readings flow into a dedicated Time-Series Database (TSDB).

Bridging the MQTT Broker to Serverless Workers
#

A common architectural pitfall is writing a single custom Node.js or Python script that connects to the MQTT broker as a standard client (mqtt.connect()) and subscribes to +/+/telemetry/#. While simple for prototypes, a single subscriber client becomes a bottleneck and a single point of failure—if that script restarts or lags behind, messages pile up or drop.

Modern brokers solve this cleanly using Rule Engines and HTTP Data Bridges (Webhooks) or Shared Subscriptions:

  • Broker Rule Engine + HTTP Webhook Bridge: Brokers like EMQX evaluate lightweight SQL rules directly inside the broker (SELECT topic, payload, clientid, timestamp FROM "rikode/+/+/+/telemetry/#"), batch multiple messages together, and forward them via authenticated HTTPS POST requests to auto-scaling serverless workers.
  • MQTT 5.0 Shared Subscriptions ($share/<group>/<topic>): If you run multiple backend worker instances, subscribing to $share/ingest-workers/rikode/+/+/telemetry/# instructs the broker to load-balance incoming messages round-robin across active workers rather than duplicating every message to every worker.

Idempotent Ingestion and Schema Validation
#

As established in Part 3, MQTT QoS 1 guarantees at-least-once delivery—meaning network hiccups inevitably produce occasional duplicate packets. Your ingestion worker should validate incoming payloads and write them idempotently:

import { Hono } from 'hono';

interface TelemetryEvent {
  topic: string;
  clientId: string;
  timestampMs: number;
  payload: {
    seq: number;
    temp: number;
    humidity: number;
    battery_mv: number;
  };
}

const app = new Hono();

app.post('/ingest/telemetry', async (c) => {
  const batch: TelemetryEvent[] = await c.req.json();

  // Filter malformed payloads before touching the database
  const validRows = batch.filter((evt) =>
    evt.payload &&
    typeof evt.payload.temp === 'number' &&
    evt.payload.temp >= -50 &&
    evt.payload.temp <= 125
  );

  // Deduplicate using composite key (device_id, recorded_at, seq)
  // via ON CONFLICT DO NOTHING in TimescaleDB / PostgreSQL
  await insertTelemetryBatch(validRows);

  return c.json({ ingested: validRows.length }, 202);
});

Choosing a Time-Series Database (TSDB)
#

Once telemetry is validated, where should it live? Standard B-tree indexes in general-purpose relational databases fragment rapidly when millions of timestamped rows are inserted out of order across hundreds of devices. Time-series engines organize data into time-partitioned chunks and apply columnar compression (such as Gorilla delta-of-delta encoding for timestamps and XOR compression for floating-point sensor values), often shrinking storage footprints by 80%–90%.

The table below compares leading database architectures used for IoT telemetry pipelines (with performance and operational overhead varying by hardware sizing, cardinality, and query patterns):

Database Engine Underlying Architecture Strengths for IoT Workloads Trade-Offs & Operational Fit
TimescaleDB PostgreSQL extension using time-partitioned Hypertables. Full SQL support, joins directly with relational device/tenant tables, continuous aggregates, automated retention policies. Best when teams already run PostgreSQL and want relational + time-series data in one engine.
QuestDB Column-oriented engine purpose-built for low-latency ingestion. Extremely high single-row and batched write throughput, native InfluxDB Line Protocol (ILP) over TCP, fast ASOF JOIN queries. Focused primarily on time-series analytics; pairs well with a separate relational DB for user/tenant metadata.
InfluxDB 3 Apache Arrow / Parquet-backed columnar time-series store. Native ecosystem support (Telegraf agents, SQL queries), compact columnar storage. Requires careful tag cardinality management to avoid memory pressure on high-uniqueness IDs.
ClickHouse Distributed columnar OLAP database. Blazingly fast analytical aggregations across billions of historical rows and fleet-wide logs. Optimized for batched inserts (thousands of rows per block) rather than frequent single-row writes.
Edge SQLite / D1 Lightweight embedded/distributed SQL. Zero-ops setup and ultra-low cost for low-frequency fleets (e.g., 50 devices reporting every 5 minutes). Not suited for high-frequency sub-second streaming across thousands of concurrent sensors.

Automated Downsampling and Retention Policies
#

Raw 1-second vibration or power readings are valuable for diagnosing an incident that happened yesterday, but rarely needed at full resolution two years later. Production TSDB pipelines automate lifecycle management through two mechanisms:

  • Continuous Aggregates (Rollups): Background database jobs pre-compute 1-minute, 1-hour, and 1-day summary tables (min, max, avg, count) so a dashboard displaying a 90-day trend queries 2,160 hourly summary rows instead of scanning 7.7 million raw points.
  • Tiered Retention & Compression: Raw chunks older than 7 days are automatically compressed into columnar blocks, and raw chunks older than 30 or 90 days are dropped while the compact hourly rollups remain stored for years.

Real-Time Dashboards Without Polling Loops
#

A frequent mistake on the frontend is configuring a web dashboard to send GET /api/devices/node-01/latest every two seconds. With 200 operators viewing dashboards simultaneously, polling generates thousands of redundant database queries even when sensor values have not changed.

Instead, split dashboard data delivery into two paths:

  1. Historical Charts (HTTP REST / GraphQL): Queried once when the user opens a page or changes a date range, hitting pre-aggregated TSDB rollups.
  2. Live Telemetry & Online Status (MQTT over WebSockets or Server-Sent Events): The browser subscribes directly to rikode/bandung-lab/esp32-env/node-01/telemetry/# and .../status/online over secure WebSockets (wss://), updating gauges and LWT offline indicators within milliseconds of the device publishing—without touching the database at all.

4 Common IoT Backend & Storage Mistakes to Avoid
#

  1. Inserting One Database Row Per MQTT Message: Opening a database transaction and committing a single row for every incoming MQTT packet exhausts connection pools and disk IOPS under load. Buffer incoming messages in your ingestion worker (for example, flushing every 500 rows or every 1 second) and execute bulk INSERT statements.
  2. Indexing Every JSON Tag or High-Cardinality ID: Using high-cardinality values—such as random UUIDs, exact floating-point coordinates, or dynamic error strings—as indexed tags in a time-series database causes index memory to grow unboundedly. Keep indexed tags limited to low-cardinality identifiers (site_id, device_type, device_id) and store variable measurements as unindexed fields.
  3. Storing Raw Telemetry Inside a Transactional Application Table Without Partitioning: Dumping 50 million sensor rows into a standard unpartitioned telemetry table makes DELETE FROM telemetry WHERE created_at < ... lock tables and bloat vacuum processes for hours. Time-partitioned chunks let the database drop expired weeks instantaneously via DROP TABLE on old chunks.
  4. Relying on Server Arrival Time Instead of Device Acquisition Time: When an offline edge node reconnects and replays two hours of buffered flash records, recording DEFAULT NOW() on the server collapses two hours of physical history into a single timestamp. Store both recorded_at (the edge device’s NTP-synced UTC timestamp) and ingested_at (server arrival time) so charts remain historically accurate while still allowing operators to monitor network lag.

Moving Forward in the Series
#

With an MQTT broker bridging securely into batched ingestion workers, time-series storage handling continuous write loads, and WebSockets powering live views, your cloud infrastructure is ready to support real fleets at scale. Yet even the best firmware and cloud pipeline cannot save a deployment if physical enclosures trap condensation, lightning surges fry unprotected sensor lines, or battery budgets are miscalculated by a factor of ten.

In Part 8: Field Deployment & Fleet Management: Power Budgeting, Enclosures, and Device Monitoring, the final installment of this series, we step back into the physical world—covering mathematical battery lifespan modeling, IP-rated enclosure protection, and fleet heartbeat observability.

Practical IoT Engineering - This article is part of a series.
Part 8: This Article