Affinity-Aware Compute at Scale
Three compute techniques that run on the node that owns the key: broadcast with local scan, single-key affinityCall, and cross-cache affinityCall.
Introduction
Pulling a distributed dataset to the client to compute on it does not scale. At 100,000 customers with three invoices each, the client fetches roughly 12 MB of invoice rows to produce a ten-row top-10. Running the same aggregation on the servers that own the rows returns under 1 KB. This tutorial builds three compute patterns that do that, then measures them against pull-to-client at 1,000, 10,000, and 100,000 customers.
Each pattern fits a different workload. Broadcast with local scan handles batch aggregation by running one job per server against its primary partitions. The client merges three per-node top-N lists. affinityCall per key handles service-time lookups by sending one job to the customer's primary owner. The Collection-overload affinityCall maps the key with the first named cache and reserves that partition in the other named caches. That matters when a job reads several caches that are colocated by design.
Every technique relies on peer class loading. The closure classes live in your client JVM and the cluster has never seen them. At invoke time the client serializes the closure, ships the class bytes to the target server, and the server deserializes and runs the code. The cluster config from Understand How Your Cache Is Distributed already has peerClassLoadingEnabled=true on every server. The flag must be the same on every node, clients included: a client with true cannot join servers with false, and the join fails with Remote node has peer class loading enabled flag different from local. If the flag is off on the whole cluster, every closure in this tutorial fails at deserialization with ClassNotFoundException.
Prerequisites
Completion of Verify Colocation Is Working. You have colocated Customer and Invoice caches with
@AffinityKeyMappedoncustomerIdand know how to prove the contract holds.A running 3-node cluster using
docker-compose-3nodes.ymlfrom Understand How Your Cache Is Distributed. Every server must havepeerClassLoadingEnabled=true.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 affinity-compute/ alongside verify-colocation/ and colocation-keys/. The cluster setup is unchanged from the previous tutorials.
What You Will Learn
Build a compute project that targets three affinity-aware patterns at the same dataset
Broadcast a callable across every server, aggregate per node, merge the top-10 on the client
Call
affinityCallat one customer key and confirm the closure ran on the customer's primary ownerUse the Collection overload to declare that a job must land on a node owning the key in every named cache
Interpret a three-approach scale experiment at 1,000 / 10,000 / 100,000 customers and decide which pattern fits a workload
Create the Affinity-Compute Project
Create a Maven project named affinity-compute/ with the layout:
The pom.xml targets Java 17 bytecode and suppresses GridGain's startup logs so each class's output stands out.
Create the shared model classes. The shape matches the previous tutorials, with one addition: Customer gains a country field so the synthetic data has a second dimension a reader could aggregate on in a later experiment.
Labels carries forward from the previous tutorial without changes. Copy it from verify-colocation/src/main/java/com/example/verify/Labels.java, change the package to com.example.compute, and save. The implementation is node-label bookkeeping. The cluster does not know that names like node1, node2, node3 exist. The utility assigns them in consistentId order on the client side so every run against the same cluster labels the same nodes the same way.
Two more small utilities hold the connection and cache configuration boilerplate. Both are referenced by every reader-facing class in this project.
The synthetic dataset is generated programmatically. DataLoader seeds the cluster with N customers and 3N invoices and is called from every reader-facing class in the project. Using IgniteDataStreamer keeps the seed under two seconds at 100,000 customers (the batched per-node buffering amortizes the network cost). Revenue is a deterministic function of (customerId, seq) so re-runs produce the same top-10 results and the tutorial output is stable across test runs.
Compile the project and load a small dataset to confirm the cluster accepts the write:
Expected output (your topology line's node IDs vary):
The first load pays a fixed startup cost for the DataStreamer and the GridGain client. Subsequent loads against the running JVM take under two seconds.
Act 1: Broadcast and Local Scan
Top-10 customers by total invoice revenue across every customer in the cluster. Pulling every invoice to the client and summing on the client wastes the network. Send a callable to every server, aggregate each server's primary partitions locally, and return a per-node top-10. The client merges three lists and takes the overall top-10. IgniteCompute.broadcast fans the closure out to every server. ScanQuery.setLocal(true) pins each server's scan to its own primary partitions.
The first closure class to ship to the servers is the per-node top-N computation. Servers receive the class via peer class loading on first invocation and cache it for later calls.
The main method defaults to 100,000 customers. Run it:
Expected output. The top-10 customer IDs and revenues are deterministic and stable. Wall-clock varies by product and machine.
Reporting nodes: 3 confirms the broadcast landed on every data node. The thick client is not a data node, so the callable does not run there. One compute invocation produced the result across 300,000 invoices. The wall-clock is dominated by per-node scan time, not by the network.
Act 2: AffinityCall per Customer
The top-10 was an aggregation over every customer. A service-time request for one customer's total revenue is a different workload. Broadcasting to every server scans three nodes' primary partitions when only one node owns the customer. IgniteCompute.affinityCall(cacheName, affKey, callable) runs the closure on the primary owner of the key and nowhere else.
The closure body is shared across Acts 2 and 3, so you factor it into its own class.
The driver class:
Defaults are scale=1000 and customerId=47. Edit main for a different customer or scale.
Expected output. Your node label varies per run, but customer 47's name, country, and revenue are deterministic and stable.
The Primary owner line reports what the client's affinity function computes before dispatching. The Closure ran on line reports what the closure itself observed. They agree. One request, one node, one round-trip. Different labels would mean the cluster is mid-rebalance and the client's cached partition assignment lags the server's. affinityCall follows the fresh assignment, not the stale one.
Act 3: Cross-Cache AffinityCall
Act 2 targeted one customer on one cache. The closure read from both caches and got the right answer because both caches use the same RendezvousAffinityFunction with the same partition count, so customerId values land on the same node in both caches. The scheduler does not enforce that symmetry. It falls out of the two caches being configured identically.
The IgniteCompute.affinityCall(Collection<String> cacheNames, Object affKey, IgniteCallable) overload declares the multi-cache constraint in code. It maps the key to a partition using the first cache in the collection, sends the job to the primary node of that partition, and reserves the same partition in the other named caches while the job runs. It does not search for a node that owns the key in every cache. Use it for caches that are colocated by design, with the same affinity function and partition count.
The closure body is the same as Act 2. Only the call site changes:
Run it against the same customer:
Expected output (the specific node label varies per run):
The result matches Act 2. On caches that share an affinity function, the single-cache form and the Collection overload pick the same target, so both produce the same answer.
The difference shows up when a cache drifts. If one cache changes its partition count, adds a node filter, or swaps in a custom AffinityFunction, the Collection overload does not detect it. It still maps the key with the first cache only, so the closure either gets the wrong answer or pays a cross-node read for the other cache. The overload is a contract for caches that are colocated by design. Check the colocation, as the previous tutorial shows, instead of relying on the call to enforce it.
Scale Experiment: Three Approaches, Three Scales
One question: top 10 customers by total invoice revenue. Three ways to compute it.
Approach A (pull-to-client). Stream every invoice to the client with a non-local
ScanQueryand aggregate client-side. Most readers write this first. It degrades sharply as the dataset grows.Approach B (broadcast + local scan). Act 1's shape. One job per node, each scans its primary partitions, returns a per-node top-10. Client merges three lists.
Approach C (partition-parallel affinityCall). One job per partition. The
(Collection<String>, int partId, IgniteCallable)overload sends each job to the primary owner of that partition. 32 jobs run in parallel on this cluster, and each closure usesScanQuery.setPartition(partId)to read exactly one partition.
ScaleExperiment runs all three at 1,000, 10,000, and 100,000 customers and prints a summary table. It destroys the caches between scales so the smaller measurements are not inflated by leftover larger-scale rows.
Run the full experiment:
Expected output. Wall-clock varies by cluster and run. Byte counts are derived from data shape and are identical across runs.
Read the columns.
A (pull-to-client): bytes grow 100x from 1k to 100k, climbing to 12 MB at 100,000 customers. Only Invoice rows cross the wire because the Customer cache stays on the servers. Wall-clock grows 10x. On a loopback network the time grows less dramatically than the bytes because the network has abundant bandwidth. On a production network with real latency and shared bandwidth, the ratio tracks the byte ratio. The byte column predicts what a production network sees. The ms column reports what localhost did on this run.
B (broadcast + local scan): bytes are flat at ~960 B because three nodes each return a ten-row list. Scan time grows with per-node data while return size stays fixed.
C (partition-parallel affinityCall): bytes are flat at ~10,240 B because 32 partitions each return a ten-row list. Wall-clock scales with per-partition scan time plus the scheduling overhead of 32 jobs instead of 3.
The interesting contrast is B vs C at 100k. On GridGain 8, C (256 ms) beats B (396 ms). Partition-parallelism pulls ahead when per-job scan time drops below the scheduling overhead ceiling. The ordering depends on cluster size and data distribution. Broadcast is the safest default for batch aggregation. Partition-parallel wins when finer granularity matters, including streaming early results to the client, handling skewed partitions, or running a job that must run exactly once per partition for correctness.
Run the experiment three times and the wall-clock numbers move ±30%. The A-at-worst / B-and-C-under-A ordering holds across runs.
Which Technique Answers Which Workload
Each technique ships the code to a different unit of the cluster: the whole cluster, one key owner, or every partition. Match the technique to the workload.
Full-dataset aggregation ("top 10 customers by revenue")
IgniteCompute.broadcast(callable) + ScanQuery.setLocal(true)
Per-node list, merge client-side
Single-key service query ("what is customer 47's revenue?")
IgniteCompute.affinityCall(cacheName, key, callable)
One result, one round-trip
Single-key cross-cache read ("everything for customer 47 across these three caches")
IgniteCompute.affinityCall(Collection<String>, key, callable)
One result; the partition is reserved in every named cache
Per-partition batch ("one job per partition, stream as they finish")
IgniteCompute.affinityCallAsync(Collection<String>, partId, callable)
One result per partition
Two constraints apply to all four. The closure class ships to the servers via peer class loading, so every node in the cluster, clients included, must have the same peerClassLoadingEnabled value, and it must be true. A node whose value differs cannot join the cluster, and with the setting off everywhere every compute call fails with ClassNotFoundException. Closures also serialize every field they capture. A non-serializable field throws NotSerializableException at submission. Inject the server-side Ignite handle with @IgniteInstanceResource instead of handing it through the closure's constructor.
Most readers reach for pull-to-client first by reflex. At 100,000 customers pull-to-client moves 12 MB of row data to produce a ten-line result. Broadcast moves 960 B for the same result. The byte ratio crosses four orders of magnitude and grows with N.
Summary
Three compute patterns cover the workload shapes that show up in production.
Broadcast with local scan for batch aggregation. One job per server, each reading its primary partitions via ScanQuery.setLocal(true) and returning a per-node summary. The client merges one list per node. The full dataset never leaves the servers. Partition-parallel is the alternative when per-partition scan time drops below broadcast's per-node overhead. The measurements in this tutorial show broadcast ahead at 10,000 customers and partition-parallel ahead at 100,000, on the same hardware.
affinityCall per key for service-time single-key queries. One round-trip, one target node, one result. Use it whenever a service request names one customer, one order, or one account.
The Collection-overload affinityCall for multi-cache reads. The key is mapped with the first named cache, and the same partition is reserved in the other named caches while the job runs. On caches that share an affinity function the single-cache and Collection forms pick the same node. The call does not detect caches whose configurations later drift apart, so verify the colocation.
Shared plumbing. Peer class loading ships your closure class bytes to the servers at invoke time. @IgniteInstanceResource injects the server's local Ignite handle into the closure. Three failure modes recur: ClassNotFoundException (peer class loading disabled), NotSerializableException (closure captures non-serializable state), and IgniteException (target cache does not exist).
At 100,000 customers the pull-to-client approach moves 12 MB to answer a ten-row question. Broadcast moves under 1 KB. In the sample run, pull-to-client takes 806 ms and broadcast 396 ms for the same top-10. On a production network the wall-clock gap widens with the byte ratio. Affinity-aware compute runs the closure on the node that owns the key, so the row data stays on that node.
What's Next
When to Break Colocation teaches the inverse design decision: reference tables in
REPLICATEDcaches, fact-dimension star schemas, and the cases where distributed joins replace colocated compute.How to Choose a Partition Count for Your Workload covers the tradeoff this tutorial parked: 32 partitions on 3 nodes versus the 1,024 default, and what changes as cluster size and data volume shift. Opens in a new tab so this tutorial stays in your sidebar.
Related
Verify Colocation Is Working built the
ScanQuery.setLocal(true)pattern this tutorial uses as the unit of local work.Design Keys for Colocation declared the
@AffinityKeyMappedcontract that makes Customer and Invoice colocate.
This page is: Copyright © 2026 MariaDB. All rights reserved.
Last updated
Was this helpful?

