---
title: "Do the two counts differ by lag, by loss, or by definition? | Proofline"
description: "When the orders database and the warehouse disagree on today's count, the warehouse is behind, has lost rows for good, or counts something else."
url: https://proofline.sh/learn/two-systems-disagree-on-a-count-lag-or-loss/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# Do the two counts differ by lag, by loss, or by definition?

When the orders database and the warehouse disagree on today's count, the warehouse is behind, has lost rows for good, or counts something else. The definitions can differ in the day boundary, a status filter or deleted orders. Recount a closed time window later, then compare the ids. Missing ids that are all among the newest point at lag, missing ids scattered through the day point at loss, and no missing ids at all point at a different definition of the count.

Schema conflicts The Proofline team November 24, 2026 8 min read

## The symptom and three explanations

A fictional shop runs its orders in PostgreSQL and copies them to a warehouse for finance. At 16:00 UTC on 2026-11-17 the operations dashboard shows 10,306 orders today, and the finance report from the warehouse shows 10,270. Thirty-six orders are unaccounted for, and three explanations fit:

-   The warehouse lags. Its copy is a few minutes behind and has not received the newest orders yet.
-   The copy lost rows. A load job skipped some orders, and they will never arrive.
-   The two counts mean different things. The dashboard counts the day in Berlin time and the warehouse in UTC, or one of them leaves out cancelled, test or deleted orders.

All three predict a gap of a few dozen. The obvious next step, refreshing both numbers a few minutes later, can mislead: with a steady lag and orders still arriving, today's gap stays about the size of the lag's worth of orders, so a lagging copy looks as stuck as a lossy one. [Choose the observation where explanations disagree](/learn/which-observation-separates-two-explanations/)

## Where the predictions differ

| Observation | Lag | Loss | Definition |
| --- | --- | --- | --- |
| Today's count, refreshed later | still short | still short | still short |
| The same closed window, recounted later | gap closes | gap stays | gap stays |
| Ids in the database and not in the warehouse | the newest | scattered through the day | none |
| Hourly counts, each system's own query | the last hour differs | many hours differ a little | a boundary hour differs |
| Newest row in the warehouse against the clock | minutes behind | current | current |

A recount of a closed window, such as midnight to 16:00, separates lag from the other two, because no new orders can enter it. The id comparison then separates loss from a different definition. A copy that lost rows is missing ids, and a copy that counts differently holds every id and puts some of them outside its count.

## The lab: one day of orders, three copies

The script generates a day of orders with Python's standard library, quiet at night and about 17 a minute in the day, with a few transactions that take 5 to 60 seconds to commit. It builds three warehouse copies in SQLite. The `lag` copy is a change stream two minutes behind. The `loss` copy is a job that runs every minute and copies rows created after the newest timestamp it copied before, so a row that commits late, after a newer row was already copied, is skipped forever. The `definition` copy is complete, but its count starts at midnight UTC instead of midnight in Berlin. The mechanism of the loss has its own guide. [Why a watermark copy misses a row that commits late](/learn/postgres-backfill-watermark-late-commit/)

```
import random, sqlite3, sys
from datetime import datetime, timedelta

if len(sys.argv) < 2 or sys.argv[1] not in ("lag", "loss", "definition"):
    sys.exit("usage: python3 count.py lag|loss|definition [seed]")
world = sys.argv[1]
seed = int(sys.argv[2]) if len(sys.argv) > 2 else 1
rng = random.Random(seed)
START = datetime(2026, 11, 16, 23, 0)            # midnight in Berlin (CET), in UTC
NOW = 17 * 3600                                  # 16:00 UTC, in seconds after START

orders, t = [], 0.0                              # (id, created_at, committed_at)
while t < NOW + 3600:
    night = (START + timedelta(seconds=t)).hour in (23, 0, 1, 2, 3, 4, 5)
    t += rng.expovariate((0.5 if night else 17) / 60)
    slow = rng.random() < 0.006                  # a few transactions commit late
    orders.append((len(orders) + 1, t, t + (rng.uniform(5, 60) if slow else 0.05)))

def copy_at(when):
    """The warehouse's rows at time `when`, as each world loads them."""
    if world == "lag":                           # change capture, two minutes behind
        return [o for o in orders if o[2] <= when - 120]
    if world == "loss":                          # every minute, rows created after the watermark
        rows, mark = [], -1.0
        for run in range(60, int(when) + 1, 60):
            batch = [o for o in orders if o[1] > mark and o[2] <= run]
            rows += batch
            mark = max([o[1] for o in batch], default=mark)
        return rows
    return [o for o in orders if o[2] <= when]   # "definition": a complete copy

def load(db, table, rows):
    db.execute(f"DROP TABLE IF EXISTS {table}")
    db.execute(f"CREATE TABLE {table} (id INTEGER PRIMARY KEY, created_at TEXT)")
    db.executemany(f"INSERT INTO {table} VALUES (?, ?)",
                   [(o[0], (START + timedelta(seconds=o[1])).isoformat(" ")) for o in rows])

db = sqlite3.connect(":memory:")
load(db, "src", [o for o in orders if o[2] <= NOW])
day_src = "2026-11-16 23:00"                     # the orders database counts the Berlin day
day_wh = "2026-11-17 00:00" if world == "definition" else day_src   # the warehouse counts the UTC day
END = "2026-11-17 16:00"
by_hour = ("SELECT substr(created_at, 12, 2), count(*) FROM {} "
           "WHERE created_at >= ? AND created_at < ? GROUP BY 1")

def compare(label, when):
    load(db, "wh", copy_at(when))
    src = dict(db.execute(by_hour.format("src"), (day_src, END)).fetchall())
    wh = dict(db.execute(by_hour.format("wh"), (day_wh, END)).fetchall())
    print(f"  {label}  db {sum(src.values())}  warehouse {sum(wh.values())}")
    return src, wh

print(f"world={world} seed={seed}")
src, wh = compare("count at 16:00  ", NOW)
diff = " ".join(f"{h}h:{wh.get(h, 0) - n:+d}" for h, n in sorted(src.items(), key=lambda x: x[0] < "23")
                if wh.get(h, 0) != n)
print("  hours that differ", diff)
missing = [r[0] for r in db.execute(
    "SELECT created_at FROM src WHERE created_at >= ? AND created_at < ? "
    "AND id NOT IN (SELECT id FROM wh) ORDER BY created_at", (day_src, END))]
print("  ids missing      ", len(missing), f"created {missing[0][11:19]} to {missing[-1][11:19]}" if missing else "")
compare("recount at 16:30", NOW + 1800)          # the same window, half an hour later
```

Save it as `count.py` and write down, for each world, whether the 16:30 recount closes the gap and where the missing ids fall. Then run:

```
for world in lag loss definition; do python3 count.py "$world"; done
```

Python 3.11 printed:

```
world=lag seed=1
  count at 16:00    db 10306  warehouse 10271
  hours that differ 15h:-35
  ids missing       35 created 15:58:03 to 15:59:44
  recount at 16:30  db 10306  warehouse 10306
world=loss seed=1
  count at 16:00    db 10306  warehouse 10270
  hours that differ 06h:-3 07h:-2 08h:-3 09h:-1 10h:-5 11h:-5 12h:-5 13h:-4 14h:-4 15h:-4
  ids missing       36 created 06:25:17 to 15:55:29
  recount at 16:30  db 10306  warehouse 10270
world=definition seed=1
  count at 16:00    db 10306  warehouse 10270
  hours that differ 23h:-36
  ids missing       0 
  recount at 16:30  db 10306  warehouse 10270
```

The three gaps at 16:00 are 35, 36 and 36. The recount closed only the `lag` gap, and its missing ids were the last two minutes of orders. The `loss` copy kept its gap, with missing ids spread from 06:25 to 15:55, a few in each busy hour. The `definition` copy was missing no ids at all; its whole gap sat in the 23:00 UTC hour, the first hour of the Berlin day. A recount that did not close the `lag` gap, or any missing id in the `definition` world, would have falsified the prediction.

Change `when - 120` to `when - 600` for a ten-minute lag. The gap grows to 178, all from the last ten minutes, and still closes on the recount: the size of a gap says how much is missing, not why. Pass a second argument, such as `python3 count.py loss 2`, for another seed.

## Read it on a real system

Everything below only reads, though a warehouse query is billed by the data it scans. First, how far behind the copy is. For a change stream from a PostgreSQL logical replication slot, `confirmed_flush_lsn` is how far the consumer has confirmed, and `pg_wal_lsn_diff` turns the distance into bytes. [pg\_replication\_slots](https://www.postgresql.org/docs/current/view-pg-replication-slots.html) · [pg\_wal\_lsn\_diff](https://www.postgresql.org/docs/current/functions-admin.html)

```
SELECT slot_name, active, confirmed_flush_lsn,
       pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) AS bytes_behind
FROM pg_replication_slots WHERE slot_type = 'logical';
```

For a batch load, compare the newest `created_at` in the warehouse with the clock. Then count a closed window with explicit UTC bounds on both sides, now and again after the copy's normal delay, so that neither side's idea of "today" enters the count:

```
SELECT count(*) FROM orders
WHERE created_at >= '2026-11-16 23:00:00+00' AND created_at < '2026-11-17 15:00:00+00';
```

Next, hourly counts on each side, run with each side's own report filters, and compare them hour by hour. In PostgreSQL, `date_trunc` takes the time zone to truncate in as a third argument. [Date/time functions](https://www.postgresql.org/docs/current/functions-datetime.html)

```
SELECT date_trunc('hour', created_at, 'UTC') AS hour, count(*)
FROM orders
WHERE created_at >= '2026-11-16 23:00:00+00' AND created_at < '2026-11-17 16:00:00+00'
GROUP BY 1 ORDER BY 1;
```

Then compare ids for the hours that differ, not the whole table. Export each side's ids for those hours, sorted, and let `comm` print the lines only the database has; `comm -13` prints the reverse, ids only the warehouse has. [comm](https://man7.org/linux/man-pages/man1/comm.1.html)

```
psql -Atc "SELECT id FROM orders WHERE created_at >= '2026-11-17 10:00:00+00' AND created_at < '2026-11-17 11:00:00+00'" | sort > db_ids.txt
# export the same hour's ids from the warehouse into wh_ids.txt, sorted the same way
comm -23 db_ids.txt wh_ids.txt | head
```

If no ids are missing, read both count queries side by side. A PostgreSQL timestamp with time zone becomes a date in the session's `TimeZone`, so `created_at::date` depends on who runs it, while BigQuery's `CURRENT_DATE()` uses UTC unless given a time zone. Status filters and the handling of deleted or test orders differ just as quietly. [PostgreSQL date/time types](https://www.postgresql.org/docs/current/datatype-datetime.html) · [BigQuery CURRENT\_DATE](https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/date_functions)

## Limits

Lag and loss can both be present, and in a batch copy they usually are. The recount separates them: what closes was lag, and what remains was lost or counted differently.

A copy can also gain rows. If the warehouse holds duplicates or orders the database deleted, those can offset missing rows until the counts agree by accident. Compare ids in both directions.

A row that changes after it was copied can move between buckets. An order whose `created_at` or status is updated, and a copy that does not apply updates, makes the hourly counts differ while every id is present. Compare the changed columns for the ids in the differing hour.

A backfill that repairs lost rows makes loss look like lag after the fact. Record the recount's time and result in the incident timeline when you take it.

## Questions

### Why does the gap stay the same size when I wait?

With a steady lag and orders still arriving, today's count gains new orders as fast as the copy catches up on old ones. Recount a window that has already ended; a lagging copy closes that gap and a lossy one does not.

### How do I compare ids between a database and a warehouse without copying everything?

Compare hourly counts first, then export ids only for the hours that differ. A few thousand ids per hour compare in seconds with `sort` and `comm`, or as a temporary table on either side.

### Which of the two counts is right?

Neither until the definition is written down: the time zone of the day, the statuses that count and what happens to deleted orders. Once both systems use the same definition, the remaining difference is lag or loss.

## One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. [Eligibility and fair-use terms](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [Why a watermark copy misses a row that commits late](/learn/postgres-backfill-watermark-late-commit/)
    
    Breaking migrations The Proofline team November 22, 2026 4 min read
    
-   ### [Compare two PostgreSQL tables in chunks with a checksum](/learn/postgres-chunked-table-checksum/)
    
    Breaking migrations The Proofline team November 22, 2026 3 min read
