Design Keys for Colocation
Three mechanisms control where related entries live in the cluster: composite keys with @AffinityKeyMapped, the AffinityKey wrapper, and CacheKeyConfiguration.
Introduction
A partitioned cache distributes entries across nodes by hashing the key. That behavior works for lookups, but a production schema needs more control. When a customer has a hundred invoices, the cluster has no reason to keep them together. Invoice keys hash independently of the customer's key, so the invoices land on whichever nodes their hashes pick.
A cross-cache read walks the network. A cross-cache join ships rows between nodes. A compute job pulls bytes from wherever the data happens to be.
Colocation fixes this. You tell the cluster to hash each invoice by its customer ID instead of by the invoice's own key, so every invoice for customer 42 lands on the same partition as customer 42 itself. Reads, joins, and compute all stay local.
GridGain 8 exposes three mechanisms for declaring this relationship. All three produce the same runtime placement. They differ on one dimension, the location of the declaration: on the key class, at the call site, or on the cache configuration. Each location fails differently when something goes wrong. Picking among them is a design decision about which failure mode your team can catch.
You build three small programs in this tutorial, one per mechanism, against a Customer and Invoice schema. Each program creates two caches, puts three customers and three invoices per customer, and uses Affinity.mapKeyToNode to confirm every invoice lands on its customer's node. The comparison at the end turns the three mechanisms into a decision framework.
Prerequisites
A running 3-node cluster from Understand How Your Cache Is Distributed. Use the
docker-compose-3nodes.ymlfile from that tutorial.Familiarity with the Affinity API. This tutorial uses
ignite.affinity(cacheName).mapKeyToNode(key)as the confirmation tool without reintroducing it.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 colocation-keys/ alongside cache-distribution/. The cluster setup is unchanged.
What You Will Learn
Build a Customer + Invoice schema with a shared client-side Labels utility for readable output
Declare colocation with the
@AffinityKeyMappedannotation on a composite key classDeclare colocation with the
AffinityKey<K>wrapper at the call site, using a plainIntegercache keyDeclare colocation with
CacheKeyConfigurationon the cache, using a plain key class with no annotationsCompare the three mechanisms and pick the one you would use for a real schema
Create the Colocation-Keys Project
Create a Maven project named colocation-keys/ with the following layout:
You create three of the files in this step. The other three, one per mechanism, come in the steps that follow.
The pom.xml targets Java 17 bytecode and suppresses the engine's startup logs so the program output stands out:
Create the two domain POJOs. They carry no affinity-related annotations because colocation is a key-side concern. The same Customer and Invoice value types work for all three mechanisms.
The Labels utility gives each cluster node a stable node1/node2/node3 synonym so program output never shows Docker-generated UUIDs. Each of the three mechanism classes uses it to format its output.
Compile the project:
The build succeeds with only the three files above plus the pom.xml. The three mechanism classes come next.
Mechanism 1: Annotation on the Composite key
The first mechanism puts the colocation declaration on the key class. InvoiceKey carries two fields: invoiceId identifies the invoice, and customerId drives partition placement because of the @AffinityKeyMapped annotation. Every caller that constructs an InvoiceKey carries the colocation intent automatically.
If you came from From Key-Value to SQL, this is the annotation you used to fix a JOIN. Here it is one of three mechanisms, and the reason it fixed the JOIN is the same reason it colocates any parent-child relationship in a real schema.
Create AnnotationColocation.java:
Run it:
Expected output:
Your specific node assignments differ from the output above. Docker regenerates node IDs on every restart, so the rendezvous function picks different primaries. The invariant is what matters. For each customer, every invoice row in that customer's line shows the same node as the customer itself. Nine out of nine.
Delete the @AffinityKeyMapped annotation from customerId, rebuild, and rerun, and the colocation invariant breaks. The invoice key's default hash has nothing to do with the customer ID, so invoices scatter. The annotation is the contract.
Mechanism 2: AffinityKey Wrapper at the Call Site
The second mechanism moves the declaration from the key class to the call site. AffinityKey<K> is a library-provided wrapper. You construct it with two values: the invoice ID (the cache key) and the customer ID (the affinity key). The invoice cache has no custom key class. Colocation is declared once per put, by the caller.
This is the right mechanism when the key class cannot be changed. Third-party types, generated code, or a legacy key that already ships in production all fit this shape. It is also useful when colocation is conditional on runtime state, where one code path wraps the invoice with the customer ID and another wraps it with a different value entirely.
Create WrapperColocation.java:
Run it:
Expected output:
Same invariant, same 9/9. The cache key here is a plain Integer. Colocation lives in the new AffinityKey<>(invoiceId, customerId) call. If a caller writes new AffinityKey<>(invoiceId) (single-argument constructor, no explicit affinity key), the wrapper falls back to using the invoice ID as the affinity key, and the invoice scatters off the customer.
Mechanism 3: CacheKeyConfiguration on the Cache
The third mechanism moves the declaration off the key class entirely and onto the cache configuration. CacheKeyConfiguration names the affinity field by type name and field name. The key class stays a plain POJO with no annotations. The cache knows which field drives partitioning because the cache configuration says so.
This is the right mechanism when the same key class ships into caches with different colocation rules, when the key class is generated code that cannot carry annotations, or when operators and schema owners are different people and the colocation decision belongs in infrastructure rather than domain code.
Create ConfigurationColocation.java:
Run it:
Expected output:
Same 9/9. The InvoiceCompositeKey class is indistinguishable from any other two-field POJO. The colocation declaration lives entirely in the CacheKeyConfiguration argument to setKeyConfiguration. Rename customerId to customerIdRef in the key class without updating the string in the cache config, and the affinity field is no longer resolvable. The cache still creates and the puts still succeed, but the invariant silently breaks.
Compare the Three Mechanisms
You have three programs that produce the same runtime outcome. The differences are about code structure and where the declaration breaks when something goes wrong.
Dimension
@AffinityKeyMapped
AffinityKey<K> wrapper
CacheKeyConfiguration
Where the declaration lives
On the key class
At each call site
On the cache configuration
Carrier type
Custom key class
Library wrapper on plain key
Plain key class
Discoverable by IDE Find Usages
Yes (on the annotation or field)
Yes (on the AffinityKey constructor)
No (the field name is a string)
Fails when...
The annotation is removed or moved to a different field (runtime, silent)
A caller omits the two-arg constructor (runtime, silent)
The field name and cache config drift apart (runtime, silent)
Same key used by multiple caches with different affinity
Not possible. One annotation per class.
Possible. Each caller picks its own affinity key.
Possible. Each cache has its own CacheKeyConfiguration.
Default when nothing applies
The whole key drives affinity
The whole key drives affinity
The whole key drives affinity
The three mechanisms are not a ranking. They are three places to put the colocation decision. Pick by the failure mode your team can catch:
If the key class owns the schema and survives unchanged,
@AffinityKeyMappedputs the declaration somewheregit blameand IDE refactoring can reason about. This is the common case.If you cannot modify the key class, or colocation is decided by runtime context,
AffinityKey<K>lets the call site carry the decision. Wrap the construction in a factory method and tests become the gate.If the same key type lives in multiple caches with different affinity needs, or the key class is generated, or cache configuration belongs to a different team than the domain model,
CacheKeyConfigurationputs the decision in infrastructure. Document the contract because tools will not find it.
Summary
Three mechanisms declare cache-to-cache colocation. All three produce identical runtime placement. The mechanism you pick decides where the colocation contract lives, and therefore how it fails when the contract is wrong.
The annotation puts the contract on the key class. Discoverable by IDE and tied to the schema. The contract breaks silently when the annotation is removed or moved to a different field; the project still compiles and tests still pass. The next tutorial, Verify Colocation Is Working, builds the verification toolkit that catches this. The annotation is the default choice when you own the key.
The wrapper puts the contract at the call site. No custom key class, per-put flexibility, silent at runtime if a caller forgets the two-argument constructor. The choice when the key is someone else's or colocation depends on runtime state.
The configuration puts the contract on the cache. No annotations on the key, multiple affinity policies for the same key type, opaque to IDE refactoring. The choice when schema and infrastructure are owned by different teams or the same key serves multiple caches.
mapKeyToNode is the same confirmation tool either way. Nine out of nine in every program, regardless of which mechanism put it there.
What's Next
Verify Colocation Is Working teaches the verification pattern that proves colocation is holding across a running cluster, including the system views and the diagnostic queries for catching silent breakage.
Affinity-Aware Compute at Scale uses colocation for compute gravity: running the job where the data already lives, without pulling bytes to the client.
When to Break Colocation teaches the inverse decision: reference tables that belong in
REPLICATEDcaches and fact-dimension patterns.
Related
Understand How Your Cache Is Distributed introduced the
AffinityAPI and the 3-node cluster used here.From Key-Value to SQL: The JOIN Problem uses
@AffinityKeyMappedas a JOIN-correctness fix, the same mechanism from a different direction.
This page is: Copyright © 2026 MariaDB. All rights reserved.
Last updated
Was this helpful?

