Published

Reliable IoT data pipelines: duplicates, gaps and device clocks

A web client mostly behaves. A device in the field loses its network for hours, reboots halfway through a send, and reports the wrong year after a dead clock battery. Designing an IoT pipeline for the happy path gives you numbers that look fine and are quietly wrong.

Three problems account for most of the damage: duplicates, gaps and bad timestamps.

Assume every message may arrive twice

If a device doesn't get an acknowledgment, it should send again. It can't tell a lost message from a lost acknowledgment, so the only delivery you can really offer is at least once. MQTT's QoS 1 says exactly that in its specification. QoS 2 promises more but only covers one hop, between client and broker.

So the receiver has to make duplicates harmless. Give each reading an identity that the device creates:

CREATE TABLE reading (
    device_id   text        NOT NULL,
    boot_id     integer     NOT NULL,
    seq         bigint      NOT NULL,
    device_time timestamptz,
    received_at timestamptz NOT NULL DEFAULT now(),
    value       double precision NOT NULL,
    PRIMARY KEY (device_id, boot_id, seq)
);

INSERT INTO reading (device_id, boot_id, seq, device_time, value)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (device_id, boot_id, seq) DO NOTHING;

The identity must not depend on a timestamp, because two real readings can share one. boot_id matters because many devices restart their counter from zero on reboot. Without it, every reading after a restart looks like a duplicate and gets silently dropped. Store the boot counter in flash and increment it on startup.

Buffer on the device

When the network goes away, the device has to put readings somewhere. A small store-and-forward spool is enough on anything that can run Python, such as a Raspberry Pi:

import sqlite3

db = sqlite3.connect("/var/lib/agent/spool.db")
db.execute("PRAGMA journal_mode=WAL")
db.execute("""CREATE TABLE IF NOT EXISTS spool (
    id INTEGER PRIMARY KEY AUTOINCREMENT, boot_id INTEGER, seq INTEGER, device_time TEXT, value REAL)""")

def record(boot_id, seq, device_time, value):
    with db:
        db.execute("INSERT INTO spool (boot_id, seq, device_time, value) VALUES (?, ?, ?, ?)",
                   (boot_id, seq, device_time, value))

def flush(send, batch_size=200):
    rows = db.execute("SELECT * FROM spool ORDER BY id LIMIT ?", (batch_size,)).fetchall()
    if rows and send(rows):  # True only once the server has acknowledged the batch
        with db:
            db.execute("DELETE FROM spool WHERE id <= ?", (rows[-1][0],))

Rows are deleted only after an acknowledgment. If the device dies between the send and the delete, the batch goes again, which is exactly what the primary key above is there for.

Decide in advance what happens when the buffer fills. For most telemetry I'd drop the oldest data and count how much was dropped, because recent readings are usually worth more. Also think about flash wear: frequent small writes shorten the life of SD cards, so batch them where you can.

Add random jitter to reconnect delays as well. When a site's network returns, a thousand devices retrying on the same schedule will take down the service they're trying to reach.

Make gaps visible

Sequence numbers also tell you what never arrived, which a timestamp can't do. A window function finds the holes:

SELECT device_id, boot_id, prev_seq + 1 AS missing_from, seq - 1 AS missing_to
FROM (
    SELECT device_id, boot_id, seq,
           lag(seq) OVER (PARTITION BY device_id, boot_id ORDER BY seq) AS prev_seq
    FROM reading
) r
WHERE seq > prev_seq + 1;

A gap might be temporary, because the device is still catching up from its spool, so wait a while before raising an alert. It's useful to distinguish three states on a dashboard: reporting, delayed and silent. "Zero readings" and "no data" are very different statements, and charts are good at hiding the difference.

Keep two clocks

Device clocks drift. They start at the epoch after a power loss, and they jump when NTP finally connects. Never overwrite one timestamp with the other. Store both:

  • device_time says when the device believes the measurement happened.
  • received_at says when the server got it, and comes from a clock you control.

The first is what you want for analysis, when it can be trusted. So define what trust means, for example:

from datetime import datetime, timedelta

MAX_FUTURE = timedelta(minutes=5)
MAX_AGE = timedelta(days=30)  # no longer than the device can buffer

def usable_time(device_time: datetime, received_at: datetime) -> datetime | None:
    if device_time > received_at + MAX_FUTURE:
        return None
    if device_time < received_at - MAX_AGE:
        return None
    return device_time

Don't reject the reading if its time fails the check. Keep it and mark the time as unknown, or estimate the time from neighboring sequence numbers. A device can also report its current clock when it connects, which lets the server calculate an offset and correct a whole batch.

Always use UTC on the device. Local time brings daylight-saving changes, and those produce an hour of apparently duplicated data each year.

Late data is normal

A device that was offline for two days will deliver two-day-old readings. If hourly totals are calculated once and never revisited, they're wrong for good. Either recompute the affected windows when late data arrives, or accept a defined cutoff and count what falls outside it.

None of this is complicated. It just has to be in the design from the start, because a historical table of readings with no identity and only one timestamp can't be repaired afterwards.