BT San Technology

10 November 2026

Gateway store and forward: getting through a dropped link without losing or double-counting data

22 min read · Automation

Illustration: a laptop on a pickup tailgate cabled to a gateway in a weatherproof box at a pump house, its screen showing a queue of waiting data
AI-generated illustration

A pump station sits 30 kilometers from the office. The gateway in its cabinet sends the volume pumped every minute over a mobile connection. One morning the signal dropped at 07:10 and came back at 08:30. The hourly report says the 07:00 hour pumped 1,208 liters and the 08:00 hour pumped 13,102 liters, even though the pump ran the same every hour, at about 7,200 liters per hour. Whoever reads the report sees a low first hour and thinks the pump has a problem. They see a high next hour and think it fixed itself.

Worse, the four-hour total looks almost right. The report says 28,728 liters. The real figure is 28,836 liters, because the lost data and the double-counted data partly cancel out. If you only look at the daily total, nobody notices. But every hourly figure in that window is wrong, and so is the electricity cost per cubic meter calculated from those figures.

This article walks through what the gateway and the receiving side need so the numbers come out right. It uses TypeScript that Node 24 runs directly with nothing to install. It covers an outbound queue that gives every value a sequence number (seq) and keeps it until it is acknowledged (ack), deduplication on the receiving side with a device + seq key, finding the ranges that went missing, and the case where the gateway reboots and the sequence numbers start over. Every step has real output to look at.

The real problem: a dropped link does not only lose data

The three scenarios below are hypothetical cases that are common in remote site monitoring. They are not any customer's project.

  • No queue: the gateway sends each value as soon as it reads it, and drops it if it cannot send. Everything in the outage is lost. The chart draws a straight line across the gap, or the report counts zero, even though the pump kept running.
  • A queue but no sequence numbers: the link returns and the gateway sends all the backlog, but the ack for the first batch is lost on the way. The gateway sends that batch again. The receiving side sees it as new data, so the total is over by one batch.
  • Counting by arrival time: values held back for 80 minutes land in the hour they arrive. One hour looks abnormally low and another abnormally high, so the team inspects the pump at the wrong time.

In all three cases the raw data may be complete or nearly complete, yet the numbers the user sees are wrong, and nothing says they are wrong. A good system must answer three questions: when did this value happen at the site, has this value already been received, and which periods really have no data.

What the documentation says, and what this example chooses

TopicWhat the documentation saysEffect on our example
Store and forwardHold the data at an intermediate point, then forward it when the destination is ready (Wikipedia)The gateway is the holding point. The outbound queue keeps the data until the receiving side confirms it
MQTT QoS 1Delivered at least once. The sender may resend if it gets no PUBACK, so the receiver may get duplicate messages (MQTT 3.1.1 section 4.3.2)The receiving side must deduplicate itself. The example uses a device + seq key
MQTT QoS 2Delivered exactly once between the two ends of a connection, at the cost of two more round trips (MQTT 3.1.1 section 4.3.3)It does not cover resends made by the application, for example a gateway that reboots and resends its queue from disk. So we deduplicate at the destination instead
Session at the brokerMQTT 5.0 has a Session Expiry Interval so the broker keeps state and QoS 1/2 messages for a client that has dropped for a whileIt helps when the receiving side drops from the broker, but not when the gateway cannot reach the broker. So the gateway needs its own queue
IdempotentDoing it many times has the same effect as doing it once (MDN)However many times the same batch is received, the table has the same rows. One test checks this
Queue size, values per batch, ack wait timeNo standard sets these60 values and 20 values per batch are the author's choice to make the effect visible. Calculate them from the real site
Documentation read on 2026-11-23. MQTT sections are cited from the OASIS 3.1.1 and 5.0 editions

Every number in this article is made up. The volume of 100 to 140 liters per minute comes from a formula in the code, not from a real pump station or gateway.

Files in the example

FilePurpose
buffer.tsThe outbound queue at the gateway. Gives every value a seq, keeps it until acked, and when full drops the oldest value and counts it
ingest.tsThe receiving side. Stores by device + seq key, counts duplicates, and finds the missing seq ranges
demo.tsSimulates a pump-station gateway for 4 hours, with an 80-minute outage, one lost ack, and the reboot case
store-forward.test.tsA suite of 5 tests using node:test
output.txtThe real output of node demo.ts
README.mdHow to run it and the limits of the example
Everything is in the folder examples/gateway-store-and-forward/. It needs Node 22.6 or later (24 recommended) and no npm install

Step 1: give every value a sequence number and keep it until it is acked

Every value the gateway reads gets a seq that rises by one, together with the time read from the gateway's clock, and then joins the queue. If the queue is full, this example drops the oldest value and counts it in dropped. It does not stop accepting new values, because monitoring needs the current value more than the value from an hour ago. Some jobs choose the opposite, such as figures used for billing. The key point is to count what you drop, so the receiving side knows the data was lost at the gateway and not somewhere along the way.

buffer.ts · lines 18–26
  push(ts: string, value: number): Reading {
    const r = { device: this.device, seq: this.next++, ts, value };
    if (this.q.length >= this.capacity) {
      this.q.shift(); // full: drop the oldest and count it, never stop taking new readings
      this.dropped++;
    }
    this.q.push(r);
    return r;
  }
buffer.ts: push assigns the seq and drops the oldest value when the queue is full

A value leaves the queue only after the receiving side has confirmed it. If you delete it when you send it, a link drop in mid-transfer loses that batch immediately. The ack carries the highest seq received so far, and the gateway deletes every value whose seq is not greater than that.

buffer.ts · lines 32–35
  // Remove everything up to and including seq. Called only after the server confirms.
  ack(seq: number): void {
    this.q = this.q.filter((r) => r.seq > seq);
  }
buffer.ts: ack deletes only the values the receiving side has confirmed

The queue in the example lives in memory to keep it easy to read. A real gateway must save the queue and the next seq to storage that survives a power loss. Otherwise a single reboot loses all the backlog and seq starts again at 1. See the effect in part 3 of the output.

Step 2: the receiving side deduplicates by device + seq and reports the missing ranges

The receiving side stores every row under the key device + seq. If the key already exists, it counts the row as a duplicate and does not overwrite it. It then replies with the batch's highest seq as the ack. Receiving is therefore idempotent: however many times the same batch arrives, the table ends up the same.

ingest.ts · lines 9–18
  ingest(batch: Reading[]): number {
    let top = 0;
    for (const r of batch) {
      const key = `${r.device}#${r.seq}`;
      if (this.rows.has(key)) this.duplicates++;
      else this.rows.set(key, r);
      top = Math.max(top, r.seq);
    }
    return top;
  }
ingest.ts: store by device + seq key and reply with the highest seq

In a real database, let the database enforce this instead of the code, with a unique constraint on the (device, seq) pair and an insert statement that skips duplicate rows, such as PostgreSQL's INSERT ... ON CONFLICT DO NOTHING. This stays correct even when several receivers run at the same time.

Once every value has a seq, a gap in the sequence is evidence that data was lost, not that the pump stopped. The gaps function walks the stored seq values for one device and returns the missing ranges. The screen uses these ranges to show a gap together with the number of missing values.

ingest.ts · lines 20–31
  // Missing seq ranges between the first and last seq stored for one device.
  gaps(device: string): [number, number][] {
    const seqs = [...this.rows.values()]
      .filter((r) => r.device === device)
      .map((r) => r.seq)
      .sort((a, b) => a - b);
    const out: [number, number][] = [];
    for (let i = 1; i < seqs.length; i++) {
      if (seqs[i] > seqs[i - 1] + 1) out.push([seqs[i - 1] + 1, seqs[i] - 1]);
    }
    return out;
  }
ingest.ts: find the missing seq ranges

Step 3: simulate an 80-minute outage and one lost ack

demo.ts simulates one gateway from 06:00 to 09:59, one value per minute. The link is down from 07:10 to 08:29. The queue holds 60 values and sends 20 values per batch, and the first ack after the link returns is lost, so the gateway resends the same batch. Along the way the code keeps three totals: the true total by the minute the pump ran, the no-deduplication total counted by the hour the data arrived, and the receiving side's table total counted by gateway time.

demo.ts · lines 24–40
for (let t = 0; t < MINUTES; t++) {
  const hour = hhmm(clock(t)).slice(0, 2);
  add(truth, hour, flow(t));
  box.push(clock(t), flow(t));
  const up = t < DOWN_FROM || t > DOWN_TO;
  if (t === LOST_ACK_AT) loseAck = true;
  while (up && box.pending > 0) {
    const batch = box.batch(BATCH);
    for (const r of batch) add(naive, hour, r.value);
    const top = store.ingest(batch);
    if (loseAck) {
      loseAck = false; // gateway times out and sends the same batch again
      continue;
    }
    box.ack(top);
  }
}
demo.ts: the main loop, the outage, sending in batches, and the lost ack

Part 3 of the demo simulates a gateway reboot. It sends 5 values before the reboot and 5 after, with seq starting again at 1, and compares two keys. The first is device + seq. The second adds a boot id (an identifier for each power-up) to the device name.

demo.ts · lines 72–81
// 3) The gateway reboots and its seq starts again at 1.
function reboot(idAfter: string): Store {
  const s = new Store();
  let k = 0;
  for (const id of ["pump-01", idAfter]) {
    const b = new Outbox(id, 10);
    for (let i = 0; i < 5; i++) s.ingest([b.push(clock(k++), 1)]);
  }
  return s;
}
demo.ts: seq starts over after a reboot

Run it and read the result

output.txt
1) Litres per hour: true = what the pump did, naive = by arrival time with no dedupe,
   store = by gateway timestamp with dedupe on device + seq
hour     true   naive   store  rows
06:00    7202    7202    7202 60/60
07:00    7234    1208    4720 39/60
08:00    7184   13102    7184 60/60
09:00    7216    7216    7216 60/60
total   28836   28728   26322 219/240

2) What each side counted
dropped at gateway (queue full)  21
duplicates rejected at server    20
missing seq 71-91                07:10-07:30 (21 readings), shown as a gap, not as zero
left in outbox                   0

3) Gateway reboots, 5 readings before and 5 after, seq restarts at 1
key = device + seq          rows 5  duplicates 5  <- 5 real readings thrown away
key = device/boot + seq     rows 10 duplicates 0
Real output from 2026-11-23 using node demo.ts (Node 24). All data is made up

The naive column is what happened in the opening story. The 07:00 hour shows 1,208 liters because only the first 10 minutes of data arrived in that hour. The 08:00 hour shows 13,102 liters because all the backlog arrived in this hour, plus 20 more values from the resent batch. The total of 28,728 liters is less than one percent from the true figure, because the 20 double-counted values and the 21 lost values almost cancel out. The total hides the errors in the hourly figures.

The store column matches the true total in every hour where the data is complete (06:00, 08:00, 09:00). The 07:00 hour shows 4,720 liters from 39 of 60 values, missing 2,514 liters. That part cannot be recovered, because the gateway had already dropped it when the queue filled. But the system knows that seq 71 to 91 are missing, which is 07:10 to 07:30, 21 values in all. So the screen should show this hour as incomplete, 39/60, instead of just showing 4,720 liters.

Why 21 values are lost: an 80-minute outage is 80 values. The queue holds 60, so 20 were dropped. When the link returned at 08:30, the gateway read a new value into the queue before it started sending, so the oldest value was dropped too, one more. The receiving side rejected 20 duplicates from the batch whose ack was lost, and the queue was empty when the simulation ended.

Part 3 shows that the key device + seq alone is not enough if seq is lost at reboot. The five values after the reboot got seq 1 to 5, the same as the five values before it, so the receiving side threw away five real values, taking them for duplicates. With a boot id in the key, all 10 values were stored. Another fix is to write the latest seq to persistent storage before using it, so it never starts over.

The test suite

The suite has 5 tests: a full queue drops the oldest value and counts it; ack deletes only up to the confirmed seq; receiving twice stores one row per device + seq; finding the missing ranges; and a last test that checks the lost-ack case directly.

store-forward.test.ts · lines 45–53
test("lost ack: the resend adds no rows and the outbox empties after the next ack", () => {
  const box = new Outbox("d", 10);
  const s = new Store();
  fill(box, 4);
  s.ingest(box.batch(10)); // ack lost
  box.ack(s.ingest(box.batch(10)));
  assert.equal(s.rows.size, 4);
  assert.equal(box.pending, 0);
});
store-forward.test.ts: after a lost ack and a resend, no new rows appear, and the queue is empty after the next ack

Running node --test store-forward.test.ts gave 5 passed, 0 failed, on 2026-11-23.

What else to check before real use

  • Save the queue and seq to persistent storage such as eMMC or an SD card, and write in batches instead of every value, because frequent writes wear out flash quickly.
  • Put a boot id in the key, or save the latest seq to disk before using it. Either works, but you need one of them.
  • Time must come from the gateway when it reads the value, and the clock must be synced (NTP or GPS). A gateway with no clock backup battery may start with the wrong time after a power loss, and a whole batch of data will land on the wrong date.
  • Size the queue from the longest outage you accept. For example, with one value per minute and an outage of 3 days, the queue must hold 4,320 values plus a margin.
  • Send the backlog in batches, and let current values reach the screen first without waiting for the whole backlog. The status screen is then current the moment the link returns.
  • Check the SIM's data plan. Sending several days of backlog at once uses more data than usual.
  • Send the dropped count upstream too, and set an alert when the queue is more than half full, before data starts to be lost.
  • Store the time the receiving side got each row (received_at) separately from the site time, so you can look back later and see how long the data was held up.

Adapting it to your business

Pump stations and water systems

Hourly water volume is used to work out electricity cost per cubic meter and to see whether a pump is wearing out. An hour with incomplete data must be flagged, and must not be averaged in like a normal hour. Otherwise the pump will look worse every time the link drops.

Meters and cumulative values

If the device can send a cumulative value, such as a liter or kWh counter that only goes up, send the cumulative value instead of the per-minute amount. If data is lost in the middle, the total for the missing period can still be found from the difference between the cumulative values on either side. But you will not know which hours that volume belongs to, so the hourly report must still flag that period.

Machines that send events

Events such as one piece finished or machine stopped directly affect production counts and OEE if they are duplicated or lost. The same principle applies, seq and deduplication, but you must not drop the oldest values when the queue is full. Choose another approach instead, such as adding queue space or alerting when the queue is nearly full.

Common mistakes

  • Deleting a value from the queue as soon as it is sent, without waiting for the ack.
  • Using the time the receiving side got the data as the time of the data.
  • Deduplicating by time alone. When the gateway clock steps backward after a reboot, real values get thrown away.
  • Filling the gap with 0, or drawing a straight line across it without saying so.
  • Thinking that setting MQTT to QoS 1 or 2 means you do not need deduplication or a queue at the gateway.
  • Not counting the values the gateway drops, so you cannot tell where data was lost.
  • Letting seq start again at 1 on every power-up.

Checklist before real use

  1. Disconnect the antenna or disable the SIM for longer than the queue can hold, then check that the screen shows the missing period as a gap with the number of missing values.
  2. Cut the gateway's power while it holds backlog, then power it on again. The backlog must still be there and must not be counted twice.
  3. Stop the ack from reaching the gateway to force a resend, then count the rows in the database.
  4. Compare the hourly totals with the meter at the site or with a handwritten log, for at least one day with an outage.
  5. Check that the monthly report does not average in incomplete hours like normal hours.
  6. Check that an alert fires when the queue is nearly full, and that someone really receives it.
  7. Review the queue size against the longest outage the site has ever had.

Limits of this example: the queue is in memory and is not saved to disk, it does not connect to a real MQTT broker, it does not simulate clock drift, and it uses a Map instead of a database. The queue size, values per batch, and the timing of the lost ack were chosen to make the effect visible, not taken from a real site.

References

  1. Store and forward — Wikipedia (accessed 2026-11-23)
  2. MQTT Version 3.1.1, OASIS Standard (หัวข้อ 4.3 Quality of Service levels) (accessed 2026-11-23)
  3. MQTT Version 5.0, OASIS Standard (Session Expiry Interval) (accessed 2026-11-23)
  4. Idempotent — MDN Web Docs Glossary (accessed 2026-11-23)
  5. Node.js — Test runner (node:test) (accessed 2026-11-23)
  6. Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-23)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer