Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Verify Colocation Is Working

Colocation fails silently.

Introduction

Colocation has no compile-time guard and no runtime exception. The previous tutorial gave you three mechanisms that declare a parent-child colocation contract. All three mechanisms compile and produce working code, and none of them throws when the contract is wrong.

A misconfigured @AffinityKeyMapped, a CacheKeyConfiguration field name that drifted from the class, or a caller that forgot the two-argument AffinityKey constructor all look the same from outside the code. The put succeeds. The get returns the value. A JOIN issued weeks later returns wrong rows. A compute job runs at a fraction of the throughput it should. The cache had no way to know what you meant.

The verification toolkit closes the gap. Three techniques, each reading a different surface of the running cluster, each reporting a failure in a different idiom. You run all three before shipping colocation-dependent code and again as part of a pre-deploy check.

You build one Maven project with two reader-facing classes. VerifyColocation runs three verification acts against the annotation pair from the previous tutorial, and every invariant holds. BrokenColocation moves the @AffinityKeyMapped annotation to the wrong field and reruns the same three acts. The contract is still declared and the compile still succeeds, but the verification toolkit catches the bug three different ways.

Prerequisites

  • Completion of Design Keys for Colocation. You have read that tutorial and Affinity.mapKeyToNode is familiar. This tutorial builds its own customers-verify and invoices-verify caches, so the caches from the prior tutorial are not needed (each of the three mechanism programs destroyed its own caches at the end).

  • A running 3-node cluster using docker-compose-3nodes.yml from Understand How Your Cache Is Distributed.

  • Java 17 or later for the client runtime. The Maven project compiles to Java 17 bytecode, the same version the server JVM runs.

  • Maven 3.6 or later

  • Docker Compose 2.23 or later

This tutorial builds a fresh Maven project called verify-colocation/ alongside colocation-keys/ and cache-distribution/. The cluster setup is unchanged.

Returning to these tutorials? Verify the 3-node cluster is running.
docker ps --filter name=gridgain8-node --format "table {{.Names}}\t{{.Status}}"

You want three server containers in the Up state. If the cluster is stopped, start it with docker compose -f cache-cluster/docker-compose-3nodes.yml up -d and wait for the topology snapshot to report servers=3.

What You Will Learn

  • Build a verification project that proves colocation three ways against the same running data

  • Assert colocation with Affinity.mapKeyToPrimaryAndBackups and read the per-invoice OK/MISMATCH shape that fails a unit test

  • Query SYS.CACHE_GROUPS and SYS.PARTITION_STATES to describe the partition topology the cluster is running

  • Broadcast a ScanQuery.setLocal(true) scan across every server and count orphan rows per node

  • Recognize the three distinct failure signals: mismatch rows, silent-healthy structure, and named orphans

Create the Verify-Colocation Project

Create a Maven project named verify-colocation/ with the layout:

The pom.xml targets Java 17 bytecode and suppresses the engine's startup logs so each act's output stands out:

Create the two domain POJOs. Same shape as the previous tutorial. Both classes are used by VerifyColocation and BrokenColocation.

Create two composite key classes. InvoiceKey carries the annotation on customerId: the contract you declared in the previous tutorial. BrokenInvoiceKey carries the annotation on invoiceId: a deliberately miswired key the cache accepts without complaint. Both compile. The break-and-diagnose step uses BrokenInvoiceKey to show how each verification technique reports a silent contract failure.

The Labels utility produces stable node1/node2/node3 synonyms so the tutorial's output never shows Docker-generated UUIDs. Same shape as the previous tutorial, with one added accessor for looking up a label from a raw UUID returned by a system view.

Compile the project. The main class arrives in the next step:

mvn compile only builds the Java files already present in src/main/java/, so this command finishes with BUILD SUCCESS. The exec.mainClass property in the pom is consumed by the exec:exec goal at run time. Until VerifyColocation.java exists, mvn exec:exec fails with ClassNotFoundException. The compile is independent of that property.

Act 1: Runtime API Verification

Affinity.mapKeyToPrimaryAndBackups(key) returns a collection of ClusterNode: primary first, backups next. For every invoice, the primary must match the primary of its customer. That is the colocation invariant as a one-line assertion, and it is the fastest of the three techniques.

The call is a pure function of the key plus the current topology. No network round-trip. No cache read. Appropriate for a unit test run in a CI pipeline against any live cluster.

Create VerifyColocation.java with the scaffolding, the first act, and main. The system-views and local-scan acts come in the next two steps.

Compile and run:

Expected output (your specific node assignments vary because Docker regenerates node IDs on every restart):

The assertion loop is the kernel of a test case. mapKeyToPrimaryAndBackups reads nothing from the cluster. It applies the rendezvous function to the key and walks the client's cached topology view. A thousand-row sweep finishes in milliseconds, which matters because this is the check you want running on every build.

During a scale event or a node restart, a partition can temporarily report multiple owners as the engine moves primary responsibility. mapKeyToPrimaryAndBackups reflects the client's current topology view, not the cluster's in-flight state. A production verification test should tolerate a brief window of disagreement by retrying with a small delay, or should run against a stable baseline.

Act 2: System Views Verification

The runtime API told you whether the contract is wired correctly. The system views tell you the shape the cluster is running. Operations teams watch them on a live system, and a schema audit reads them when the source code is not available.

Two views carry what you need. SYS.CACHE_GROUPS describes each cache's group: partition count, backups, cache mode, the group ID used to join against other SYS views. SYS.PARTITION_STATES is one row per partition per owner, with IS_PRIMARY and STATE columns. Both are available over SQL from any cache in the cluster, including the thick-client API's cache.query(new SqlFieldsQuery(...)) path.

Add the actTwoSystemViews method to VerifyColocation.java below actOneRuntimeApi, and wire it into main after the actOneRuntimeApi call:

Update main to call the new method:

Compile and rerun:

Act 1's output is unchanged. Act 2 appears after it:

Look at the shape, not the specific counts. Both caches have the same partition count, the same backup count, the same mode, and identical per-node primary counts. That is structural health. It answers "are both caches alive and distributed across every server?" but not "does this invoice live with its customer?"

The system views describe the cluster. The cluster does not know the reader's intent. A miswired colocation contract can produce a perfectly uniform partition distribution. The break-and-diagnose step demonstrates that.

You can run the same queries without writing Java. Open a SQL shell against any node (using the gridgain8-node1 container and the sqlline.sh script under /opt/gridgain/). SELECT CACHE_GROUP_NAME, PARTITIONS_COUNT, BACKUPS FROM SYS.CACHE_GROUPS; returns the same data. The CLI query is a one-shot audit tool. The Java version belongs in the test suite, where it fails a build on regression.

Act 3: Local Scan Verification

The third technique is what production does. A colocated JOIN or a colocated compute job runs on each server, reads that server's primary-owned data, and joins against other caches whose keys hash to the same node. If an invoice's customer lives on a different node, the join misses the row or returns a stale one.

You model that pattern with a scan. ScanQuery.setLocal(true) restricts a scan to the entries primary-owned by the node running the query. A thin client also accepts the flag, but it runs the scan on the one node the client is connected to, so it cannot sweep every server. You broadcast a callable to every server, each callable scans its own customers and invoices, and each returns orphan invoices whose customer is not local.

The broadcast is a diagnostic-tool preview of compute gravity from the next tutorial in this path. Every server independently verifies that the data it owns is consistent with the contract.

Add actThreeLocalScan, the LocalScanTask callable, and the NodeReport record below Act 2. Wire actThreeLocalScan into main:

Update main to invoke the third act:

Compile and rerun. The full output appears in sequence:

Act 3's section:

Your per-node counts vary. The invariant to watch is orphan invoices = 0. Every invoice primary-owned by a node must have its customer primary-owned by the same node. (none) in every row means the contract holds for the data the cluster is serving.

Notice node3: zero customers and zero invoices. Three customers spread across 32 partitions on three nodes does not guarantee every node hosts a customer. Production data volumes eliminate the zero case, but small tutorial datasets surface the math. The invariant still holds across the two nodes that do have data.

ScanQuery.setLocal(true) reads only the partitions that the node running the query owns. A thin client accepts the flag, but it talks to a single node over a socket, so the scan covers only that node's primary partitions. To sweep every server, run the scan from a compute broadcast target, as this code does, so that each server scans its own data.

Open VerifyColocation.java and run Find Usages on the customers-verify string constant. The IDE finds every place the cache name appears. Then run Find Usages on the @AffinityKeyMapped annotation on InvoiceKey.customerId. The IDE finds every key class using the mechanism. Neither search finds the silent failure mode where a future refactor moves the annotation to the wrong field. That is the verification toolkit's job.

Break the Colocation and Diagnose it

The verification techniques all passed. A clean run proves nothing about whether the techniques can see a failure. You break the contract now and rerun each technique to see what each one says when something is wrong.

BrokenColocation is the sibling class. It uses BrokenInvoiceKey (annotation on invoiceId instead of customerId), builds its own caches, and runs the same three acts. Everything else is identical.

Run the broken variant:

Expected output:

Read each act. The same contract failure produces three different signals.

Act 1 names the failing rows. The summary line prints how many of nine invoices share a primary with their customer, and the exact split is topology-dependent. Three invoices in this reference run print MISMATCH with the specific customer primary and invoice primary. A test harness that iterates nine keys and asserts the match fails at exactly the right line. This is the signal you want from CI.

Act 2 looks identical to the good run. Same partition counts. Same per-node distribution. Same cache shape. Both caches are running correctly as independent PARTITIONED caches with 32 partitions, so the cluster is structurally healthy. The system views describe what the cluster is doing, not what the reader intended. A schema audit that relies on SYS queries alone sees nothing wrong in this output.

Act 3 names the orphans. On the reference run captured above, node1 hosts one invoice (202) whose customer lives on node2, and node3 hosts two invoices (101 and 303) whose customers live on node2 and node1. Specific invoice IDs and per-node counts vary with topology and seed. The shape (a [id, id, ...] orphan list) is what a broken JOIN returns as missing rows at production scale.

The three signals compound. If Act 1 runs in a test on every build, a regression fails the build before it merges. If Act 3 runs in a smoke test before deploy, a regression that somehow reached staging fails the smoke test. Act 2 is the audit that tells an operator the cluster is alive when none of the contract-level checks are running at all.

Which Technique Answers Which Question

The three techniques look at the same cluster through three different lenses. Pick by the question you are answering.

Question
Technique
Failure signal

Is my colocation contract wired correctly?

Runtime API (mapKeyToPrimaryAndBackups)

OK/MISMATCH per key with specific primary nodes named

What is the cluster running?

System views (SYS.CACHE_GROUPS, SYS.PARTITION_STATES)

Structural description only; cannot see contract intent

Will a cross-cache JOIN or compute job return correct rows?

Local scan broadcast (ScanQuery.setLocal(true))

Named orphan rows per node

Runtime API runs from any process with a client handle, returns in milliseconds, and reads nothing from the cluster itself. It catches a miswired contract the fastest and is the only technique that belongs in a unit test. It cannot detect problems that only manifest with real data in place, like a customer ID that never appears in the invoice cache.

System views tell you the cluster is alive and both caches are distributed. They do not read intent. Two caches with unrelated affinity contracts can produce identical partition distributions. Use them to confirm operations are healthy and to collect the CACHE_GROUP_ID values you need to correlate to partition-level data. Do not use them to prove colocation.

Local scan broadcast is the closest mirror of what a colocated JOIN does at runtime. The setLocal(true) flag pins each server's scan to its own primary partitions. The callable has to handle binary keys and values because domain classes do not live on the server classpath. withKeepBinary plus BinaryObject.field reads composite key fields without a Java class. Use it as a pre-deploy smoke test, and use it on a production sample when diagnosing a wrong-answer JOIN in the wild.

Ship all three. Each catches a category of failure the others miss, and the cost of running them compounds the other way. If one technique regresses, the others still hold the line.

Summary

Colocation fails silently because the cache has no path to reject an incorrect contract. Every put succeeds, every get returns a value, and a wrong answer looks identical to a right answer until a JOIN or a compute job exposes it. The verification toolkit is what closes the gap.

Runtime API assertions run in milliseconds and fail per-row. mapKeyToPrimaryAndBackups reads cached topology and compares expected versus actual primary ownership. Nine keys, nine assertions, one verdict. That belongs in a unit test run on every build.

System views describe what the cluster is running. SYS.CACHE_GROUPS gives you partition count, backups, and cache mode per group, while SYS.PARTITION_STATES gives you the partition-to-node map with an IS_PRIMARY flag. Together they answer "is the cluster healthy and correctly provisioned?" They cannot answer "are these two caches colocated correctly?"

Local scan broadcasts verify what the JOIN sees. ScanQuery.setLocal(true) reads one node's primary partitions. Broadcast the scan to every server, have each server check its own data against the contract, and count orphans. An orphan count of zero is the only safe number to ship.

The three techniques are not redundant. They probe different surfaces of the same cluster and fail in different ways. A production-grade verification story runs all three. The runtime API fails fast on wiring bugs, the system views confirm operational health, and the local scan catches the residual case where a wiring bug passes review but the data itself is inconsistent.

What's Next

  • Affinity-Aware Compute at Scale builds compute gravity on top of the local-scan pattern. Every server runs jobs against its own partition of the data, coordinating nothing cross-node.

  • When to Break Colocation teaches the inverse design decision: reference tables that belong in REPLICATED caches, fact-dimension star schemas, and setDistributedJoins(true) for the cases where colocation is not the right answer.

This page is: Copyright © 2026 MariaDB. All rights reserved.

Last updated

Was this helpful?