Derived Data Out of Sync: Why Two Datasets That Should Agree Don't
When a cache, search index or warehouse table disagrees with its source, find out whether the derived data is late or wrong, and which write path lost it.
- derived data
- data reconciliation
- change data capture
- materialized views
- root cause analysis
Every team eventually discovers that it does not have one copy of its data. It has one copy and a dozen opinions about it.
The orders table says a customer has 14 open orders. The search index finds 12. The warehouse report says 13, the cache behind the account page says 14 but with an old total, and the CRM sync says 11. Each of these is meant to be the same information, derived from the same source, and each was built by a different mechanism at a different time. When they disagree, the question “which one is right?” is the easy part: usually the source. The hard part is “why did this copy stop matching, and is it still getting worse?”
Martin Kleppmann’s Designing Data-Intensive Applications closes with a long discussion of exactly this situation. It distinguishes systems of record, which hold the authoritative version of the data, from derived data, which is anything built from them by a repeatable process: caches, search indexes, materialised views, denormalised tables, analytics models, machine learning features. Derived data is redundant by design, and that redundancy is useful. It is also a standing invitation for copies to drift. This article is about investigating that drift: telling a copy that is late from one that is wrong, finding the write path that lost or changed data, and writing a finding that keeps the copies honest.
Table of Contents
- Systems of record and everything else
- Late or wrong: the first question
- How derived data gets out of sync
- Find the divergence point
- Reconciliation that explains, not just detects
- Investigating a derived data incident
- Rebuilding is a feature, not a fix
- Frequently asked questions
- Copies drift; make the drift explainable
- Related reading
Systems of record and everything else
Kleppmann’s distinction is simple and worth adopting as team vocabulary. A system of record is the source of truth: when a new fact arrives, it is written there first, and if anything else disagrees with it, the system of record wins by definition. Derived data is the result of taking existing data and transforming or processing it in some way. If you lose derived data, you can recreate it from the source.
Most production systems derive a great deal:
| Derived dataset | Built from | Built by | How it usually drifts |
|---|---|---|---|
| Cache | A database row or query result | Application code on read or write | Invalidation missed or raced; entry outlives its TTL assumptions |
| Search index | Records in the primary store | Dual write, change stream, or periodic reindex | Missed updates or deletes; indexing errors swallowed |
| Materialised view | Base tables | Database refresh, scheduled or incremental | Refresh failed or skipped; incremental logic misses a case |
| Warehouse table or model | Operational databases, events, files | Batch or streaming pipelines | Late data, filters, duplicate loads, schema changes |
| Denormalised read model | Events or normalised tables | Consumer or projection code | Consumer lag; a bug in one event handler |
| Third-party copy (CRM, billing, support tool) | Your database | Sync job or webhooks | Rate limits, partial failures, mapping changes |
Writing this list for your own system is a useful exercise before an incident. It names each copy, its source and its mechanism, which together are most of what an investigation needs. It also tends to expose copies whose source is not clear, and those are the ones that cause the longest arguments.
Late or wrong: the first question
Kleppmann makes a distinction in his discussion of correctness that is the most useful single question in a derived-data investigation. He separates timeliness, meaning users see the system in an up-to-date state, from integrity, meaning the data is not corrupted, lost or contradictory. A violation of timeliness is temporary: wait, and the copy catches up. A violation of integrity is permanent: waiting does not help, and the copy will stay wrong until someone repairs it. His point is that in most applications integrity matters much more than timeliness.
Applied to an incident, the question becomes: is the derived copy late, or is it wrong?
| Late (timeliness) | Wrong (integrity) | |
|---|---|---|
| What waiting does | The copy converges with the source | Nothing; the difference persists |
| Typical mechanisms | Consumer lag, refresh interval, replication lag, slow indexing | Lost update or delete, failed write never retried, logic bug, wrong mapping |
| Evidence | Differences are recent; older records match | Differences include old records; the set does not shrink |
| Urgency | Depends on who reads the copy and how stale they can tolerate | Usually higher; data must be repaired, not just waited for |
| Fix | Capacity, scheduling or routing | Repair the data and fix the write path |
The test is cheap. Run the same comparison twice, some time apart. If the differences are all recent and the set shrinks, the copy is late. If the differences include old records, or the set does not shrink, the copy is wrong. Many investigations skip this test, spend an afternoon on consumer lag, and then discover that the missing records are three weeks old.
How derived data gets out of sync
The mechanism that keeps a derived copy updated determines which failures are possible. Kleppmann discusses three broad approaches, and each has a characteristic way of going wrong.
Dual writes
The most common approach in application code is a dual write: the application writes to the database and then also writes to the cache, the index or the other system. It is simple and it fails in two ways that the book describes in detail.
The first is partial failure. The database write succeeds and the second write fails, times out or is never attempted because the process crashed in between. Unless the application retries reliably, the copies now differ permanently. This is an integrity failure, not a timeliness one.
The second is a race condition. Two clients update the same record at nearly the same time. Their database writes happen in one order and their index writes in the other, so the database holds the second value and the index holds the first. Neither write failed. No error was logged. The copies disagree and will keep disagreeing until that record is updated again.
Dual-write race: two updates to customer 88213
client A: db.write(status=active) index.write(status=active)
client B: db.write(status=closed) index.write(status=closed)
^ B's index write lands first
Database final value: closed (B wrote last)
Index final value: active (A wrote last)
Dual writes are the first suspect whenever differences are scattered across records, permanent, and not explained by any single failure in the logs.
Change data capture and its gaps
The alternative Kleppmann argues for is to make the database’s own log of changes the single ordered source, and derive every other copy by consuming it. Change data capture (CDC) reads the database’s replication or transaction log and publishes each change as an event, in the order the database applied it. Tools such as Debezium do this for several databases. Kleppmann’s essay Turning the database inside out is an earlier and more opinionated version of the same argument: treat derived stores as materialised views over a log of changes.
CDC removes the dual-write race, because every consumer sees changes in the same order. It has its own failure modes, and each is a hypothesis in an investigation:
- Initial snapshot gaps. A consumer that started from a snapshot plus the log can miss or double-apply changes made while the snapshot was taken, if the hand-over position was wrong.
- Log retention. If a consumer is down longer than the database or broker retains the log, it cannot catch up. It needs a new snapshot, and anything skipped is gone from that path.
- Schema changes. A column renamed, a type changed, or a table recreated can make the connector or a consumer stop, skip events, or write nulls.
- Changes the log does not show. Bulk operations, truncates, and changes made outside the captured tables may not appear as row-level events, depending on the database and configuration.
- Consumer bugs. The log is ordered and complete, but the code that applies events to the derived store mishandles one event type, such as deletes.
Scheduled rebuilds and refreshes
Materialised views, warehouse models and periodic reindexes derive data on a schedule. Their failure modes are those of any scheduled job: the refresh did not run, ran over incomplete input, ran twice, or ran successfully with logic that changed. Incremental refreshes add a class of their own: the logic that decides which rows changed since last time can miss updates that do not touch the column it relies on, such as an updated_at that some write paths forget to set.
Find the divergence point
A derived dataset usually sits at the end of a chain, and the copies along the chain tell you where things went wrong. For the warehouse report that disagrees with the operational database, the chain might be: source table, CDC events, raw landing table, staging model, reporting model, dashboard. The investigation narrows quickly if you count the same thing at every stage.
-- Where does the count first diverge? One bounded window, every stage.
-- Read-only; each stage is a separate system, so run the counts where they live
-- and line them up, or run them here if the stages share a warehouse.
SELECT 'raw_landing' AS stage, COUNT(*) AS rows FROM raw.orders_cdc
WHERE op <> 'd' AND created_at >= '2026-11-01' AND created_at < '2026-11-08'
UNION ALL
SELECT 'staging', COUNT(*) FROM stg.orders
WHERE created_at >= '2026-11-01' AND created_at < '2026-11-08'
UNION ALL
SELECT 'reporting', COUNT(*) FROM rpt.orders_daily
WHERE order_date >= '2026-11-01' AND order_date < '2026-11-08';
The first stage where the count departs from the source is where the investigation goes next. Everything before that point is working, so hypotheses about it can be set aside. This is the same idea as the stage-by-stage counts in your pipeline succeeded and the rows are missing, applied to any chain of derived copies rather than one load.
Two cautions. Counts can agree while contents disagree, if one stage has duplicates and another has gaps of the same size. And every stage needs the same definition of the window and the same treatment of deletes, or the comparison will show differences that are artefacts of the query.
Reconciliation that explains, not just detects
Most teams that have been bitten by drift add a reconciliation check: compare counts or sums between the source and the copy, and alert when they differ. That is good for detection. Data quality tools such as those compared on the Great Expectations and dbt pages are built for this kind of test. For an investigation, a count is not enough. You need to know which records differ and how.
Classifying the differences
A record-level comparison by primary key sorts every difference into one of a small number of classes, and each class points at a different set of mechanisms.
-- Record-level comparison between a source table and its derived copy.
-- Read-only. Compare a stable subset of columns, and bound by time if the tables are large.
SELECT CASE
WHEN d.id IS NULL THEN 'missing_in_derived'
WHEN s.id IS NULL THEN 'extra_in_derived'
WHEN s.status <> d.status
OR s.total <> d.total THEN 'different_values'
ELSE 'match'
END AS outcome,
COUNT(*) AS records,
MIN(COALESCE(s.updated_at, d.updated_at)) AS oldest_change,
MAX(COALESCE(s.updated_at, d.updated_at)) AS newest_change
FROM app.orders s
FULL OUTER JOIN derived.orders d ON d.id = s.id
GROUP BY 1
ORDER BY 1;
| Class | What it means | Likely mechanisms |
|---|---|---|
| Missing in derived, recent only | The copy has not caught up | Consumer lag, refresh interval, indexing backlog |
| Missing in derived, including old records | Writes never reached the copy | Failed dual write without retry, CDC gap, consumer skipped events, filter in the derivation |
| Extra in derived | The copy kept records the source removed | Deletes not propagated; source truncated or rebuilt without an event |
| Different values | Both have the record but disagree | Dual-write race, missed update, transformation bug, reference data changed |
| Different values, clustered in time | Many records diverged at once | A deploy, a schema change, a consumer restart, a backfill |
The oldest_change and newest_change columns do the timeliness-versus-integrity test in the same query. If the oldest differing record is minutes old, the copy may simply be behind. If it is weeks old, it is wrong.
Investigating a derived data incident
The method is hypothesis-driven debugging; the specific steps are:
- Name the source of truth and the copy. If the team disagrees about which one is authoritative, settle that first. It is a surprisingly common cause of long incidents.
- Late or wrong? Run the comparison twice, some time apart, and look at the age of the oldest difference.
- Find the divergence point in the chain with counts at each stage.
- Classify the differences at the stage where they first appear.
- Write rival hypotheses from the mechanism that maintains that stage: dual write, CDC, or scheduled refresh.
- Confirm with independent evidence: the code at the deployed version, logs from the writer and the consumer, and the timeline of deploys, schema changes and restarts.
| Hypothesis | Predicts | Ruled out if |
|---|---|---|
| Copy is behind | Only recent records differ; the set shrinks over time | Old records differ, or the set does not shrink |
| Dual-write partial failure | Scattered missing or stale records; errors or timeouts on the second write in logs | No failures on the second write in the window, or writes go through a log |
| Dual-write race | Records with concurrent updates hold the earlier value in the copy | Differing records had no concurrent updates |
| Deletes not propagated | Extra records in the copy, all deleted in the source | Extra records were never deleted in the source |
| Consumer bug for one event type | Differences limited to one kind of change, starting at a deploy | Differences span all event types, or predate the deploy |
| Derivation filter or logic change | Differences correlate with an attribute; start at a code change | Differences are spread evenly across attribute values |
A worked example: the search index that forgot deletes
This is an illustrative example; the numbers are invented for the explanation.
Symptom. Customers report that cancelled listings still appear in search results and lead to a “not found” page. Support has seen a handful of these a day for about two weeks. The listings table in the primary database is correct.
Late or wrong? A record-level comparison between the listings table and the search index finds about 3,100 documents in the index that no longer exist in the source, and almost no other differences. Run again an hour later, the number is 3,180. The oldest extra document was deleted from the source sixteen days ago. The index is not late; it is wrong, and getting more wrong.
Hypotheses.
- H1: the indexing consumer mishandles delete events (consumer bug).
- H2: deletes are performed by a bulk cleanup job that bypasses the change stream (changes the log does not show).
- H3: the CDC connector stopped capturing deletes after a configuration change (capture gap).
Discriminating tests. All extra documents are deleted listings, which fits all three. The differences are in how the deletes happened. H2 predicts that only listings removed by the bulk cleanup job are affected, while listings deleted by users through the application are removed from the index normally. H3 predicts that delete events are missing from the change stream itself. H1 predicts that delete events are present in the stream but not applied.
The change stream topic contains delete events for a sample of the affected listings, which rules out H3 and H2 for those records: the deletes were captured. The consumer’s logs show those events being received and acknowledged, with no corresponding index operation. The consumer’s code, at a commit sixteen days ago, refactored event handling into a mapping from operation type to handler, and the mapping has entries for create and update but not for delete. Unknown operation types are logged at debug level and acknowledged.
Confirmation. Three independent lines of evidence: the record-level comparison (only deletes are affected, from sixteen days ago), the consumer logs (delete events received and acknowledged without action), and the code change at the matching date. H1 is confirmed. H2 and H3 are rejected with the observations that ruled them out.
Finding and action items. “A refactor of the indexing consumer sixteen days ago dropped the handler for delete events. Deletes were received and acknowledged without being applied, and unknown operation types were logged at debug level, so nothing alerted.” The action items: restore the handler, repair the index by removing the extra documents or by reindexing from the source, make unknown operation types an error rather than a debug line, and run the record-level comparison daily with an alert on extra documents older than an hour.
Rebuilding is a feature, not a fix
The most valuable property of derived data is in its definition: it can be rebuilt from the source. Kleppmann leans on this throughout the book. Batch outputs can be regenerated by rerunning over immutable inputs; derived views can be rebuilt by replaying a log or reprocessing the source. That property is what makes it safe to experiment with new indexes and models, and it is the standard way to repair a derived copy.
It is not a root cause fix. Rebuilding the search index in the example above would have removed the 3,180 stale documents and left the consumer still ignoring deletes. The rebuild repairs the data; the investigation repairs the write path. Do both, in that order of importance.
Rebuilds also deserve some caution of their own:
- A rebuild uses today’s code and today’s reference data. It will not reproduce the copy as it was, which matters if someone needs to know what users saw last week.
- A rebuild can hide the evidence. Run the record-level comparison and keep its output before rebuilding, or you will not be able to measure the incident’s scope afterwards.
- A rebuild can fail partway, leaving a copy that is a mix of old and new. Rebuild into a new location and switch over, where the system allows it.
- A rebuild needs the source to be complete. If the log has been truncated or the source itself was corrected in place, the rebuild produces a different answer, not the original one.
Frequently asked questions
What is derived data?
Derived data is any dataset built from other data by a repeatable process: a cache, a search index, a materialised view, a denormalised read model, a warehouse table, or a copy in a third-party tool. Kleppmann contrasts it with a system of record, which holds the authoritative version. If derived data is lost or wrong, it can in principle be recreated from the system of record, which is both its main strength and the reason drift can go unnoticed.
Why do two datasets that should match not agree?
Because they are maintained by different mechanisms that fail differently. Common causes are a write to one system that failed or was never retried, two concurrent updates that reached the two systems in different orders, deletes that were not propagated, a consumer that fell behind or skipped events, a refresh that did not run, and transformation logic that changed in one place. A record-level comparison classifies the differences, and each class points to a short list of mechanisms.
How do I tell whether a derived copy is late or wrong?
Compare the source and the copy at the record level, note the age of the oldest difference, and repeat the comparison some time later. If only recent records differ and the set shrinks, the copy is behind and will converge. If old records differ, or the set does not shrink, the copy has lost or changed data and needs repair as well as a fix to whatever maintains it.
Is change data capture better than dual writes?
For keeping derived copies consistent, usually yes. Change data capture derives every copy from one ordered log of changes, which removes the race conditions and the partial failures that dual writes suffer from. It has its own failure modes, such as snapshot hand-over errors, log retention limits, schema changes and changes that never appear in the log, so it still needs reconciliation and monitoring. It moves the risk to fewer, better-understood places rather than removing it.
Should I just rebuild the derived data?
Rebuild to repair the data, but only after you have captured the evidence and found the mechanism. A rebuild removes the symptom and keeps the cause, so the copy will drift again. Keep the output of the record-level comparison from before the rebuild so the scope of the incident can be measured, and rebuild into a new location if you can, so a failed rebuild does not leave a half-updated copy.
Copies drift; make the drift explainable
Derived data is one of the most useful ideas in system design and one of the most reliable sources of quiet incidents. Copies drift because the mechanisms that maintain them fail in ways that do not raise errors: a dual write that lost a race, a consumer that acknowledged an event it did not apply, a refresh that ran over incomplete input. The investigation goes fastest when the team asks the questions in order: which copy is the source of truth, is the other one late or wrong, where in the chain does the divergence start, and which class of difference is it?
The same questions apply whether the disagreement is between a database and an index, as here, or between a stream job and a batch job, or a replica serving stale reads. Detection tools, including the data observability products on our Monte Carlo comparison, will tell you that two datasets disagree. Decim works on the next step: it reads code and commits from GitHub, logs from Google Cloud Logging and tickets from Jira, writes a read-only check for your team to run when the deciding evidence is in a database, and keeps the rejected hypotheses with the evidence that ruled them out, as the investigations page describes.
Related reading
- Stream vs batch processing: why the same events give two different answers.
- Stale reads and consistency models: what each copy was allowed to return.
- Replication lag and failover: the replica case, with lost writes on failover.
- Your pipeline succeeded and the rows are missing: stage-by-stage counts for a silent shortfall.
- Root cause analysis guide: the full method from symptom to confirmed cause.
Decim investigates incidents in your own system and returns a diagnosis where every claim links to the log line, code or check behind it, with the rejected explanations kept so your team learns where its copies drift. It reads code from GitHub, logs from Google Cloud Logging and tickets from Jira, never runs SQL and never merges a fix. Learn more at decim.dev or see pricing.
Related articles
- Faults vs Failures: What Reliability Means When You Investigate an Incident Faults vs failures: a fault is never the whole root cause. Find out which safeguard should have absorbed it, and why this time it turned into an outage. Read the article →
- Hot Partitions and Partial Failures: Investigating Incidents in Sharded Systems A hot partition hides behind healthy averages. How to investigate skewed keys, rebalancing and partial failures in a sharded system, one slice at a time. Read the article →
- Root Cause Analysis Tools and Rules: An Odyssey Follow a stalled search index through seven root cause analysis tools, from the deploy everyone blamed to the replay that proved why one queue stopped. Read the article →
- ETL Root Cause Analysis: A Warehouse Odyssey Follow an ETL root cause analysis from a wrong refunds total to the warehouse join that inflated it. Verify the fix with a reconciliation and backfill. Read the article →
Decim investigates pipeline incidents
It reads your code, logs and tickets, works through the pipeline step by step, and confirms the cause with evidence you can check: every claim links to the log line, commit or check behind it. Then it proposes the fix and writes the report.
Request a demo