User guide
From a first comparison to a verified batch job in production. Each chapter builds on the one before, but you can jump to what you need. The README is the complete reference.
01Your first comparison
ditto compares a baseline, usually a backup taken before a batch run, with a candidate, the data after the run, and gives a verdict.
Try it with the CLI
The repository brings a MongoDB and a generator that writes a baseline plus a copy with the changes you choose. In a clone of the repository:
docker compose up -d mongo ./mvnw package -DskipTests # or download ditto-cli.jar from the latest release # 50,000 documents; 3% prices changed, 0.5% deleted, 0.5% added SEED_ARGS="--docs=50000 --changes=modify:price:0.03,delete-docs:0.005,add-docs:0.005" \ docker compose run --rm seed java -jar ditto-cli/target/ditto-cli.jar --db=ditto --collection=demo > report.json echo $? # 0 GREEN, 1 YELLOW, 2 RED, 3 error
--collection=demo compares demo_backup with demo. The report goes to
stdout as JSON; a summary and hints go to stderr. The first run is RED:
Verdict RED: keySimilarity 0.9901, unchangedRate 0.0000, 2 changed paths, 1598 ms
Hints:
- meta.syncedAt changed in 100% of matched documents and holds dates: it looks like a technical timestamp
written by every run. If so, ignore it.
--ignore=meta.syncedAtEvery document changed, but only because the sync stamps each one with the time it ran. Take the hint and run again:
java -jar ditto-cli/target/ditto-cli.jar --db=ditto --collection=demo --ignore=meta.syncedAt > report.json
# Verdict GREEN: keySimilarity 0.9901, unchangedRate 0.9711, 1 changed paths, 1529 msThat is the whole workflow in small: compare, read the hints, tell ditto about your data, compare again.
In a Spring Boot application
ditto needs Java 21 or newer and Spring Boot 4.1. For MongoDB (4.4 or newer), add the library; it uses the
application's MongoDB connection (spring.mongodb.*):
<dependency> <groupId>dev.jbaby.ditto</groupId> <artifactId>ditto-mongo</artifactId> <version>0.6.0</version> </dependency>
Then inject CollectionComparator:
@Service
class ReplicationCheck {
private final CollectionComparator comparator;
ReplicationCheck(CollectionComparator comparator) {
this.comparator = comparator;
}
Level check() {
ComparisonReport report = comparator.compareWithBackup("products"); // products_backup → products
report.hints().forEach(hint -> log.info("{}", hint.message())); // what to configure next
return report.verdict(); // GREEN, YELLOW or RED
}
}- The verdict is a value, not an exception. A RED comparison returns normally.
- An exception means the comparison couldn't be done meaningfully:
ComparisonExceptionfor a missing collection, unusable keys or an interruption, and Spring'sDataAccessExceptionfor database errors. compareruns on the calling thread and stops when that thread is interrupted. Comparisons running at the same time are independent.
For two collections that aren't a backup pair, name both, in any database of the cluster:
comparator.compare(ComparisonRequest.builder(
CollectionRef.of("archive", "products"), CollectionRef.of("products")).build());OpenSearch works the same way with ditto-opensearch and an IndexComparator; see
chapter 8.
02Reading the result
The verdict is the worst level of a handful of rules. Start at the verdict and work down: each level explains the one above.
The rules
| Rule | Looks at |
|---|---|
keySimilarity | matched / (matched + added + removed): did documents go missing or appear? |
unchangedRate | The share of matched documents with the same content |
maxPathChangeRate | The highest share of documents in which one single field changed |
structure.vanishedPaths | Fields that disappeared from every document (RED) |
structure.typeShifts | Fields whose BSON type changed, e.g. int → double (RED) |
structure.newPaths, structure.presenceDeltas | New fields, and fields that became much rarer or more common (YELLOW) |
Content is compared in a canonical form: field order doesn't matter, arrays are compared as multisets, and
numbers by value, so 42 equals 42.0. A type change is the structure check's job.
Where to look
verdictandrules: every rule that isn't GREEN explains itself inreasonand lists the offending paths indetails.keys: compareaddedwithremoved.contentandtopChangedPaths: which fields changed, how often, with before/after values.structure: schema drift, independent of values.examples: keys to look up yourself, as relaxed Extended JSON, e.g.db.products.find({_id: {"$oid": "6553f1212161972337cc2db4"}}).hints: what to configure next (chapter 3).run.decisions,run.thresholdSourceandwarnings: what ditto decided by itself, where the thresholds came from, and what limits the result.
| If you see… | It usually means… |
|---|---|
| Many removed, few added | A partial or aborted load |
| Many removed and many added | The key values changed format ("123" vs 123), or a new ID scheme |
| One field changed in ~100% of documents | A mapping or format change in that field, or a technical field to ignore; the value examples show which |
| Many fields at low rates | Normal data churn |
| A type shift with unchanged content | Same values, different type: consumers that read typed values may break |
As a page
The JSON is complete but long. To read a report comfortably:
- CLI: add
--html=report.htmlfor a self-contained page with hints, rules, changed paths and the structure diff. It makes no external requests, so it works offline and as an attachment. - Java: the
ReportHtmlbean writes the same page:reportHtml.write(report). - Any
report.json: drop it on the report viewer. It renders in your browser and uploads nothing.
03Teaching ditto your data
ditto starts without configuration, and its hints tell you what your data needs. You add each piece once.
The hints
Each hint has a message, and where there is something to configure, a ready-made property and
cliOption. ditto never ignores a field just because of its name, like updatedAt: that
could hide a sync that stopped working. It suggests, you decide.
| Hint | Situation | What to do |
|---|---|---|
IGNORE_TECHNICAL_FIELD | A timestamp changed in every document | Add it to ignored-paths |
EXPECTED_CHANGE | A field changes in many documents every run, like a price | Add it to expected-change-paths |
WILDCARD | An object with dynamic keys, i.e. a map | Add it to wildcard-paths, e.g. attributes.* |
MATCHED_ONLY | One side holds only a part of the other's keys, e.g. a test environment | Compare matched documents only, see troubleshooting |
LARGER_SAMPLE | A SAMPLE result too close to a threshold to be sure | Sample more keys, or compare in FULL mode |
INVESTIGATE | Something worth a look that no setting fixes | Read the message |
Set it once
Set what applies to every comparison as ditto.* properties:
ditto: ignored-paths: [meta.syncedAt] # removed before comparing expected-change-paths: [price, stock] # reported, but not counted against the verdict wildcard-paths: [attributes.*] # a map: reported as attributes.*, compared on the real keys order-sensitive-paths: [history] # arrays whose element order matters redacted-paths: [customer] # values shown as *** in reports
Or set it on one request; request options win over properties:
comparator.compare(comparator.backupRequest("products")
.ignoredPaths("meta.syncedAt")
.expectedChangePaths("price", "stock")
.build());Paths use one syntax everywhere. A path covers everything below it: stock also covers
stock.qty.
| Pattern | Matches |
|---|---|
meta.syncedAt | A nested field |
items[].price | Field price of every element of array items; matrix[][] for nested arrays |
attributes.* | * matches exactly one field name |
Maps with dynamic keys are usually detected without configuration, in a small sample before comparing. An
explicit wildcard-paths entry is for the ones detection misses.
Other key fields
Documents are matched by _id. Set key-field (or .keyField(...)) to match
by another top-level field. It must be present in every document and unique; ditto rejects duplicates rather
than count them wrong. In MongoDB, index it, or the server sorts the whole collection. In OpenSearch it must be
a keyword or integer field, or a text field with a keyword subfield.
Big collections
AUTO mode compares fully up to 5 million documents per side (full-scan-limit), and samples 20,000
keys per side above that (sample.size). In SAMPLE mode every rate is a 95% confidence interval, and
by default each rule judges its worse end: GREEN means "GREEN with 95%
confidence". Force a mode with .fullScan() or .sample(n), or --mode on the
CLI.
04Storing reports
Stored reports let you find the report of a job later, and let ditto learn what's normal for each pair of collections.
Report files
ditto:
persistence:
enabled: true
directory: /var/lib/ditto/reports # default: ditto-reports in the working directory
retention: 365d # optional: older report files are deleted after each save- Each report is one JSON file, the same JSON the CLI prints, named
<finishedAt>_<id>.json. Nothing is written into the compared databases. - Keep the directory on persistent storage. In a container, mount a volume. Otherwise the reports, and the history that learned thresholds need, are gone after a restart.
- Several instances can share the directory on a shared volume, and the CLI can read it while the application runs: a report is written under a temporary name, renamed, and never changed afterwards. Instances with a directory of their own learn only from their own reports.
- If storing a report fails, the failure is logged and the report is still returned.
Labels: the report of a job
Attach the job's id to the comparison. It's stored with the report:
comparator.compare(comparator.backupRequest("products")
.label("batchJobId", jobId)
.build());Labels that belong on every report, like the environment, go in the configuration:
ditto.labels.environment=test. Keys may use letters, digits, _ and -;
values are any text up to 512 characters. Labels don't affect the comparison or the metrics.
Then find the report from wherever you are:
| From | How |
|---|---|
| Java | reportStore.findByLabels(Map.of("batchJobId", jobId), 10), newest first. Inject ReportStore; also findById and findRecent |
| CLI | java -jar ditto-cli.jar report --label=batchJobId=4711 --html=report.html, with --report-dir if the reports aren't in ./ditto-reports |
| HTTP | GET /actuator/comparisons?label=batchJobId:4711 (chapter 6) |
| Shell | jq -r 'select(.labels.batchJobId == "4711") | input_filename' ditto-reports/*.json |
Storing in the database instead
With ditto.persistence.storage=database, reports go to the collection
ditto.persistence.collection (default comparison_reports) of the compared MongoDB
database, or to an index of that name in the compared OpenSearch cluster. That was the only storage up to 0.5.0.
To move from there to files and keep the history, copy the stored reports once:
java -jar ditto-cli.jar copy-reports --uri="$MONGO_URI" --db=shop --report-dir=/var/lib/ditto/reports
copy-reports only reads the database. Running it again replaces the files with the same
reports.
05Thresholds that learn
Fixed thresholds fit some collections badly: one where 8% of the documents change every day is always YELLOW. With stored reports, ditto learns what is normal for each pair.
Storing reports switches it on. For each comparison, ditto takes the last 20 comparisons of the same
baseline and candidate that weren't RED, and sets the bounds of
keySimilarity, unchangedRate and maxPathChangeRate around their mean:
- GREEN within 2 standard deviations, YELLOW within 3, in the direction that is worse for the metric.
- The standard deviation counts as at least 0.005, so a perfectly stable history still allows small deviations.
- Until 5 such runs exist, the configured thresholds apply. Thresholds set on a request always win.
- RED runs are left out, so a broken run doesn't lower the bar for the next one. A slow drift across many runs is learned, though; keep an eye on the values.
The report's run.thresholdSource says which thresholds were used and how they were derived, e.g.
unchangedRate: mean 0.9120, standard deviation 0.0071 over 14 runs -> GREEN >= 0.8978, YELLOW >= 0.8907.
ditto:
adaptive-thresholds:
history-size: 20 # runs considered
min-history: 5 # runs needed before history is used
green-sigma: 2.0
yellow-sigma: 3.0To store reports without learning from them, set ditto.adaptive-thresholds.enabled=false.
06Alerts and monitoring
Every comparison publishes a Spring event, whoever started it. Metrics and an Actuator endpoint come along if the application already has Micrometer or Actuator.
Events
@EventListener
void onComparison(ComparisonCompletedEvent event) {
if (event.report().verdict() == Level.RED) {
alerts.critical(event.report().id(), reportHtml.write(event.report())); // the page as attachment
}
}
@EventListener
void onFailure(ComparisonFailedEvent event) { // settings, exception and labels
alerts.error(event.labels().get("batchJobId"), event.exception());
}Micrometer
With a MeterRegistry, ditto records these meters, tagged with baseline and
candidate:
| Meter | Type | Meaning |
|---|---|---|
ditto.comparison | timer | Duration, also tagged with mode and verdict |
ditto.comparison.errors | counter | Comparisons that failed, tagged with exception |
ditto.comparison.verdict | gauge | Latest verdict: 0 GREEN, 1 YELLOW, 2 RED |
ditto.comparison.key.similarity, .unchanged.rate, .max.path.change.rate | gauge | Latest values of the rules |
A dashboard per collection pair and an alert on ditto.comparison.verdict == 2 cover most needs.
Labels are deliberately not tags: a job id would create a new time series per run.
Actuator
With Actuator and stored reports, the read-only comparisons endpoint lists them once you expose
it (management.endpoints.web.exposure.include=comparisons):
GET /actuator/comparisons: the 50 most recent reports, summarised; filter with?label=batchJobId:4711.GET /actuator/comparisons/{id}: one report. The viewer opens it directly withviewer.html#url=https://your-app/actuator/comparisons/{id}if your application allows the viewer's origin (management.endpoints.web.cors.allowed-origins=https://danielbartl.github.io).
07In a batch job
The situation ditto was built for: a job replaces a collection, and before anyone uses the new data you want to know whether to keep it or roll back.
- Backup: copy
productstoproducts_backup, e.g. with an$outaggregation. ditto never creates the backup; your job does. - Sync: upsert into
productsand delete stale documents. - Verify: compare, and act on the verdict. Run it as a separate step with its own retries, so it can be repeated by hand.
ComparisonReport report = comparator.compare(
comparator.backupRequest("products").label("batchJobId", jobId).build(),
progress -> progressBar.set(progress.fractionDone())); // null if the total is unknown
switch (report.verdict()) {
case GREEN -> log.info("products verified");
case YELLOW -> alerts.warn("products", report.id()); // usable; have someone look
case RED -> {
rollback.restoreFromBackup("products"); // your code
alerts.critical("products", report.id());
}
}- Retry on exceptions only. A RED verdict completes the step
normally after the rollback.
DataAccessExceptionand connection problems are worth a retry;ComparisonException(missing backup, duplicate or mixed keys) is a configuration problem that a retry won't fix: alert, and don't roll back automatically. - Rollback is yours, since only you know what "usable" means for your consumers. In MongoDB,
renameCollectionof the backup over the collection withdropTarget: trueis atomic within a database but consumes the backup; copying it back with$outor$mergekeeps it. In OpenSearch, point the alias back at the backup index. - Protect the backup: the next scheduled sync mustn't overwrite it before verification and rollback are done. Chain the jobs, or use a lock.
- Compare after the writes are done. Reads aren't a snapshot.
- Cancellation: interrupting the thread, e.g. by deleting the job in a scheduler, stops the
comparison within a few hundred documents with a
ComparisonException. - Tight time budget: a SAMPLE comparison right after the sync gives a quick verdict; a FULL comparison can follow later.
The README has a complete JobRunr example, with the progress bar and retries.
08OpenSearch
Two OpenSearch indices compare like two collections: the same verdict, metrics, hints, report and
viewer. A document is its _source; _id is its key.
<dependency> <groupId>dev.jbaby.ditto</groupId> <artifactId>ditto-opensearch</artifactId> <version>0.6.0</version> </dependency>
ditto uses the application's OpenSearchClient (opensearch-java) with whatever transport it has,
AWS SigV4 included. Without one, set ditto.opensearch.uris (and username and
password), and ditto creates a client. Inject IndexComparator and call it like the
MongoDB comparator: comparator.compareWithBackup("products"). OpenSearch 2.19 and 3.x are
supported.
- Refresh after writing. Only refreshed documents are visible:
POST /products/_refresh. ditto warns if an index has refreshing switched off, and never writes to the indices it compares. - Names are index names or aliases of exactly one index; patterns are rejected. Reports name
the cluster in place of a database, e.g.
my-cluster.products. - Keys:
_idby default. Another key field must be akeywordor integer field, or atextfield with akeywordsubfield. - Numbers and dates: numbers are read exactly, so
1and1.0are equal content._sourcehas no date type; ditto still recognises ISO-8601 timestamps that changed everywhere and suggests ignoring them. - Reading: OpenSearch can't return documents sorted by
_id, so ditto scrolls one index and looks its keys up in the other. Locally, two indices of 20,000 documents took about 2 seconds. - Incomplete results fail. If shards fail or a search times out, the comparison stops with an error rather than judge a partial result.
java -jar ditto-cli.jar --opensearch=https://search.example.com --opensearch-user=ditto --index=products
# password from DITTO_OPENSEARCH_PASSWORD09In CI and scripts
The CLI turns the verdict into the exit code and prints nothing but the report JSON on stdout.
| Exit code | Meaning |
|---|---|
0 | GREEN |
1 | YELLOW |
2 | RED |
3 | Error: bad options, missing collection, unusable keys, connection failure |
java -jar ditto-cli.jar --uri="$MONGO_URI" --db=shop --collection=products \ --ignore=meta.syncedAt --out=report.json --html=report.html > /dev/null case $? in 0) echo "GREEN" ;; 1) echo "YELLOW, continuing"; jq '.rules[] | select(.level != "GREEN") | .reason' report.json ;; 2) echo "RED, aborting"; exit 1 ;; *) echo "comparison failed"; exit 1 ;; esac
- Keep
report.htmlas a build artifact: it opens without network access. - Every library property works as an option:
--ditto.thresholds.key-similarity.green=0.995. --persiststores the report in--report-dir;reportprints a stored one, with its verdict as exit code.
10Upgrading from 0.5.0
0.6.0 renames the MongoDB library and stores reports as files by default.
- Change the dependency from
ditto-coretoditto-mongo. - Update the imports: the MongoDB classes moved to
dev.jbaby.ditto.mongo,ReportRepositoryis nowMongoReportRepositoryandComparatorAutoConfigurationisMongoComparatorAutoConfiguration. - If you store reports: either keep them in MongoDB with
ditto.persistence.storage=database, or putditto.persistence.directoryon a volume and copy the history once withcopy-reports(chapter 4). - Log levels for
dev.jbaby.ditto.comparatorno longer cover the MongoDB classes; usedev.jbaby.ditto.
The upgrade checklist in the changelog has every detail.
11Troubleshooting
The messages below are what ditto says; the rest of each row is what to do about it.
The comparison fails
| Message | Cause and fix |
|---|---|
| The baseline collection shop.products_backup does not exist | The backup step didn't run, or uses another name. Check the job, or set backup-suffix, or name both sides. |
| Duplicate key "4711" in …: the key field must be unique | The key field isn't unique. Choose a unique field, or fix the data; ditto won't count duplicates. |
| Key field 'sku' has mixed types [NUMBER, STRING] … | Keys of different types, e.g. strings and numbers. Usually a data problem; mixed-key-types=COMPARE compares them anyway, with a warning. |
| Key field 'sku' is missing in some documents … | Every document needs the key field. Choose another key, or fix the documents. |
| Comparison of … interrupted | The thread was interrupted, e.g. the job was cancelled. Run it again. |
| Key field 'name' is mapped as text … (OpenSearch) | Text can't be looked up exactly. Use a keyword field or subfield. |
| Search is incomplete: 1 of 5 shards failed … (OpenSearch) | The cluster couldn't answer completely. Check its health, and compare again. |
| OpenSearch has no databases, but … names 'x' | Give the index name only; the cluster takes the place of the database. |
The result looks wrong
| You see | Cause and fix |
|---|---|
| RED on the first run, one field changed in 100% | A technical timestamp. Follow the hint: ignore it. |
| RED on a test environment that holds part of the data | Most keys are missing on purpose. Compare with matchedOnly() / --matched-only. |
| YELLOW in SAMPLE mode, GREEN in FULL | Close to a threshold, SAMPLE judges the worse end of the confidence interval. Sample more, or use sample.verdict-basis=POINT. |
| Documents missing or appearing in OpenSearch | The index wasn't refreshed after writing. Refresh it before comparing. |
| A warning that more than 10000 distinct paths were found | A map with dynamic keys that detection missed. Add it to wildcard-paths. |
| The thresholds don't learn | Fewer than 5 earlier runs that weren't RED, or thresholds set on the request, or reports in a directory that doesn't survive restarts. run.thresholdSource says which. |
Operations
| You see | Cause and fix |
|---|---|
| A FULL comparison on a custom key is slow (MongoDB) | The key field has no index, and the report warns about it. Create the index. |
| A cursor timed out on a very large collection | One side sat idle for more than 10 minutes. Set no-cursor-timeout=true. |
| Reports are gone after a restart | The report directory isn't on persistent storage. Mount a volume at ditto.persistence.directory. |
| ditto.persistence.collection and .database have no effect at startup | An upgraded configuration: reports now go to files. Set ditto.persistence.storage=database to keep MongoDB, or remove the settings. |
No comparisons Actuator endpoint | Persistence is off, the endpoint isn't exposed, or both MongoDB and OpenSearch store reports in their databases; then define the endpoint yourself. |
| --index needs --opensearch=<url> (CLI) | Add --opensearch, or use --collection for MongoDB. |
Something else? Open an issue with the report's
run section and the message.