ditto GitHub

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:

bash
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:

stderr
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.syncedAt

Every 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 ms

That 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.*):

pom.xml
<dependency>
  <groupId>dev.jbaby.ditto</groupId>
  <artifactId>ditto-mongo</artifactId>
  <version>0.6.0</version>
</dependency>

Then inject CollectionComparator:

Java
@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: ComparisonException for a missing collection, unusable keys or an interruption, and Spring's DataAccessException for database errors.
  • compare runs 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:

Java
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

RuleLooks at
keySimilaritymatched / (matched + added + removed): did documents go missing or appear?
unchangedRateThe share of matched documents with the same content
maxPathChangeRateThe highest share of documents in which one single field changed
structure.vanishedPathsFields that disappeared from every document (RED)
structure.typeShiftsFields whose BSON type changed, e.g. int → double (RED)
structure.newPaths, structure.presenceDeltasNew 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

  1. verdict and rules: every rule that isn't GREEN explains itself in reason and lists the offending paths in details.
  2. keys: compare added with removed.
  3. content and topChangedPaths: which fields changed, how often, with before/after values.
  4. structure: schema drift, independent of values.
  5. examples: keys to look up yourself, as relaxed Extended JSON, e.g. db.products.find({_id: {"$oid": "6553f1212161972337cc2db4"}}).
  6. hints: what to configure next (chapter 3).
  7. run.decisions, run.thresholdSource and warnings: what ditto decided by itself, where the thresholds came from, and what limits the result.
If you see…It usually means…
Many removed, few addedA partial or aborted load
Many removed and many addedThe key values changed format ("123" vs 123), or a new ID scheme
One field changed in ~100% of documentsA mapping or format change in that field, or a technical field to ignore; the value examples show which
Many fields at low ratesNormal data churn
A type shift with unchanged contentSame 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.html for 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 ReportHtml bean 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.

HintSituationWhat to do
IGNORE_TECHNICAL_FIELDA timestamp changed in every documentAdd it to ignored-paths
EXPECTED_CHANGEA field changes in many documents every run, like a priceAdd it to expected-change-paths
WILDCARDAn object with dynamic keys, i.e. a mapAdd it to wildcard-paths, e.g. attributes.*
MATCHED_ONLYOne side holds only a part of the other's keys, e.g. a test environmentCompare matched documents only, see troubleshooting
LARGER_SAMPLEA SAMPLE result too close to a threshold to be sureSample more keys, or compare in FULL mode
INVESTIGATESomething worth a look that no setting fixesRead the message

Set it once

Set what applies to every comparison as ditto.* properties:

application.yml
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:

Java
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.

PatternMatches
meta.syncedAtA nested field
items[].priceField 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

application.yml
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:

Java
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:

FromHow
JavareportStore.findByLabels(Map.of("batchJobId", jobId), 10), newest first. Inject ReportStore; also findById and findRecent
CLIjava -jar ditto-cli.jar report --label=batchJobId=4711 --html=report.html, with --report-dir if the reports aren't in ./ditto-reports
HTTPGET /actuator/comparisons?label=batchJobId:4711 (chapter 6)
Shelljq -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:

bash
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.

application.yml
ditto:
  adaptive-thresholds:
    history-size: 20      # runs considered
    min-history: 5        # runs needed before history is used
    green-sigma: 2.0
    yellow-sigma: 3.0

To 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

Java
@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:

MeterTypeMeaning
ditto.comparisontimerDuration, also tagged with mode and verdict
ditto.comparison.errorscounterComparisons that failed, tagged with exception
ditto.comparison.verdictgaugeLatest verdict: 0 GREEN, 1 YELLOW, 2 RED
ditto.comparison.key.similarity, .unchanged.rate, .max.path.change.rategaugeLatest 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 with viewer.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.

  1. Backup: copy products to products_backup, e.g. with an $out aggregation. ditto never creates the backup; your job does.
  2. Sync: upsert into products and delete stale documents.
  3. Verify: compare, and act on the verdict. Run it as a separate step with its own retries, so it can be repeated by hand.
Java
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. DataAccessException and 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, renameCollection of the backup over the collection with dropTarget: true is atomic within a database but consumes the backup; copying it back with $out or $merge keeps 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.

pom.xml
<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: _id by default. Another key field must be a keyword or integer field, or a text field with a keyword subfield.
  • Numbers and dates: numbers are read exactly, so 1 and 1.0 are equal content. _source has 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.
CLI
java -jar ditto-cli.jar --opensearch=https://search.example.com --opensearch-user=ditto --index=products
# password from DITTO_OPENSEARCH_PASSWORD

09In CI and scripts

The CLI turns the verdict into the exit code and prints nothing but the report JSON on stdout.

Exit codeMeaning
0GREEN
1YELLOW
2RED
3Error: bad options, missing collection, unusable keys, connection failure
bash
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.html as a build artifact: it opens without network access.
  • Every library property works as an option: --ditto.thresholds.key-similarity.green=0.995.
  • --persist stores the report in --report-dir; report prints 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.

  1. Change the dependency from ditto-core to ditto-mongo.
  2. Update the imports: the MongoDB classes moved to dev.jbaby.ditto.mongo, ReportRepository is now MongoReportRepository and ComparatorAutoConfiguration is MongoComparatorAutoConfiguration.
  3. If you store reports: either keep them in MongoDB with ditto.persistence.storage=database, or put ditto.persistence.directory on a volume and copy the history once with copy-reports (chapter 4).
  4. Log levels for dev.jbaby.ditto.comparator no longer cover the MongoDB classes; use dev.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

MessageCause and fix
The baseline collection shop.products_backup does not existThe 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 uniqueThe 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 … interruptedThe 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 seeCause 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 dataMost keys are missing on purpose. Compare with matchedOnly() / --matched-only.
YELLOW in SAMPLE mode, GREEN in FULLClose 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 OpenSearchThe index wasn't refreshed after writing. Refresh it before comparing.
A warning that more than 10000 distinct paths were foundA map with dynamic keys that detection missed. Add it to wildcard-paths.
The thresholds don't learnFewer 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 seeCause 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 collectionOne side sat idle for more than 10 minutes. Set no-cursor-timeout=true.
Reports are gone after a restartThe report directory isn't on persistent storage. Mount a volume at ditto.persistence.directory.
ditto.persistence.collection and .database have no effect at startupAn upgraded configuration: reports now go to files. Set ditto.persistence.storage=database to keep MongoDB, or remove the settings.
No comparisons Actuator endpointPersistence 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.