Atomic Operations Across Keys: The Transaction Problem
Span partitions with atomic multi-key writes, no cross-shard glue code required.
Introduction
In a sharded cache, multi-key writes are only atomic when the keys live on the same shard. Cross-shard atomicity has historically meant application-layer work: key co-location, per-shard scripting, or compensation after partial failures. Each option pushes consistency work back into your code. You already covered txStart, commit, and the optimistic retry pattern on a single-node cluster. This tutorial puts that same API on a three-node cluster, shows how OPTIMISTIC + REPEATABLE_READ silently drops writes, and ends with the production retry pattern wrapped around any optimistic transaction.
Prerequisites
A running three-node cluster using
cache-cluster/docker-compose-3nodes.ymlfrom Understand How Your Cache Is Distributed. The per-node configs incache-cluster/docker-compose-3nodes.ymlpin discovery and communication ports and register aBasicAddressResolverso a host JVM thick client can reach each container through the loopback address. Peer class loading is enabled on every server.Transaction API familiarity from Use Transactions with the Cache API
Java 17 or later for the client runtime
Maven 3.6 or later
Docker Compose 2.23 or later
This tutorial builds a fresh Maven project called cross-partition-tx/. It does not extend the cache-client/ project from the foundations path because the cache shape is different.
What You Will Learn
In this tutorial, you:
Configure a
TRANSACTIONALcache and verify its atomicity mode from a host JVM thick clientRun a
txStarttransfer between two keys on a multi-node cluster and watch the commit phase complete without any explicit cross-partition handlingWatch one transaction silently overwrite another's committed work under
OPTIMISTIC + REPEATABLE_READCatch the same conflict under
OPTIMISTIC + SERIALIZABLEasorg.apache.ignite.transactions.TransactionOptimisticExceptionand apply exponential backoff with a bounded retry budget
Configure a Transactional Account Cache
Create a Maven project called cross-partition-tx/. The pom.xml depends on gridgain-core and includes the --add-opens entries Java 17 reflection requires. The thick client joins the cluster through the discovery seeds the host can reach (127.0.0.1:47500, 47501, 47502). The per-node BasicAddressResolver maps each container's hostname to 127.0.0.1 so the rest of the protocol routes through the loopback interface. -Djava.net.preferIPv4Stack=true skips the IPv6 join attempt that otherwise costs ten seconds on a fresh client.
The Account model is a plain serializable POJO. The cluster stores the bytes and never deserializes the value server-side. Only the host JVM reads back what it wrote, so Java serialization is enough for this tutorial.
ConfigureAccountCache creates the cache with setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL) and one backup per partition. ATOMIC caches throw if you operate on them inside a transaction, as the cache transactions tutorial showed. This cache stays TRANSACTIONAL throughout.
Run it. Compile first because exec:exec does not trigger compilation on its own.
Expected output:
getOrCreateCache is idempotent. Re-running this class on an existing cache returns the existing configuration without overwriting it.
Run a Cross-Partition Transfer
Seed four accounts at 100.00 each and transfer 25.00 between two of them inside a transaction. The cluster has three nodes with 1024 partitions by default. Each account ID hashes to a partition whose primary sits on one of the three nodes. Two account IDs may land on the same primary or on different primaries depending on their hashes, and the application code stays identical either way.
Run it:
Expected output (run-to-run timing varies):
The trace records four operations and a commit:
txStartopens the transaction.The two
cache.getcalls acquire pessimistic locks on the primary owners of each key.The two
cache.putcalls write to the transaction-local view.commitruns the two-phase protocol across whichever primaries own the keys.
Commit duration is the only number that depends on whether the keys live on different nodes. Cross-node commits add a network round trip per primary. The partition layout never surfaces in the application code.
Commit-phase microseconds reflect the two-phase protocol against every primary the transaction touched. The thick client drives prepare and commit messages over the communication SPI to those primaries directly, so the wall-clock trace records the network round trips that a single-connection client would have collapsed into one figure.
Watch OPTIMISTIC + REPEATABLE_READ Silently Lose Writes
The previous step used PESSIMISTIC + REPEATABLE_READ, the default returned by the no-argument txStart(). Pessimistic locking acquires a write lock on every key the transaction touches, so two contending transactions serialize. One waits for the other to release. Switching the concurrency to OPTIMISTIC removes the locks and trades them for a commit-time validation step, but the validation runs only under specific isolation levels.
OPTIMISTIC concurrency relies on commit-time validation. When the transaction tries to commit, the cluster checks whether any key in the read set was modified by another transaction that committed first. A modified read key fails the commit. That validation runs under TransactionIsolation.SERIALIZABLE only. REPEATABLE_READ and READ_COMMITTED skip it.
That makes OPTIMISTIC + REPEATABLE_READ unsafe whenever a key is read and then written based on what was read. Two transactions reading the same pre-write value both write a value derived from it, and the second commit overwrites the first. No exception is thrown, so the lost transaction never surfaces to the application.
This step proves the behavior with a deterministic interleave. tx1 reads, tx2 commits its own transfer inside tx1's window, then tx1 writes and commits with the values it read before tx2 ran. The lost-update outcome is the same shape a concurrent race between two contending transactions produces. The sequential interleave is the honest tradeoff: same outcome, deterministic across runs, no timing assumptions baked into the code. Thick-client transactions bind to the current thread through thread-local state, so a single thread cannot hold two transactions open at once. The interleave runs on two threads inside one GridGain client. Two CountDownLatch instances enforce the order. tx1 releases the first latch after reading, which lets tx2 run a full transfer and commit. tx2 releases the second latch in a finally block, which lets tx1 wake up and write its own values.
Run it:
Expected output:
Two transactions ran, both committed, and both APIs returned without an error. Only tx1's transfer of 10.00 is visible in the final state. tx2's transfer of 25.00 is gone. The sum is still 200.00 because tx1 was an internally balanced transfer, and the application has no signal that tx2's work was discarded.
The failure mode is the contract. REPEATABLE_READ does not validate the read set, and OPTIMISTIC defers all conflict detection to commit-time validation. With validation off, both transactions read the same value, both compute writes derived from it, and both commits succeed. The second commit wins and the earlier transaction's update is silently overwritten.
SERIALIZABLE is the only isolation level that catches this. Under OPTIMISTIC + SERIALIZABLE, the cluster validates the read set at commit and throws if another transaction has modified a read key. The next step runs the same scenario under SERIALIZABLE and shows how to recover.
Catch and Retry Optimistic Conflicts
Switch the isolation level from REPEATABLE_READ to SERIALIZABLE and the same interleave produces a different outcome. The cluster now validates the read set at commit, sees that another transaction modified a key after tx1 read it, and rejects tx1's commit. The lost update from the prior step becomes a typed failure the application can catch and retry.
The thick client surfaces optimistic conflicts as org.apache.ignite.transactions.TransactionOptimisticException, a subclass of IgniteException. A catch block matched on that type is the production discriminator. No message-text inspection is required. Other failure modes (timeout, deadlock, communication failure) surface as their own typed subclasses and propagate independently.
RetryingTransfer runs two scenarios from main. The first reuses the conflict pattern from the previous step under SERIALIZABLE and catches the exception so you can see what surfaces. The second runs the same operations inside a retry loop that recovers on the next attempt.
Run it:
Expected output:
The first scenario confirms that the conflict surfaces at tx1.commit() as TransactionOptimisticException, a typed subclass of IgniteException. The catch block matches the exact exception class, so other failure modes (timeout, deadlock, communication failure) propagate out untouched. The full message names the conflicting key. On GridGain 8 it also includes a benign BinaryInvalidTypeException from the server's value-formatting path, so firstLine truncates at the first [ to keep the trace readable. The contract is the type, not the text.
The second scenario wraps the same operations inside a retry loop. Attempt 0 hits the planted conflict and sleeps 10ms. Attempt 1 sees the post-tx2 state (1001 = 105.00) and commits its own transfer cleanly. The final balances match the arithmetic: tx2 added 5.00 to 1001, tx1 subtracted 10.00 from 1001 and added 10.00 to 1006, so 1001 ends at 95.00 and 1006 ends at 110.00.
The retry budget is the production failure surface. Five attempts cover the planted conflict, but a real workload may exhaust the budget when contention is heavy enough that every retry re-collides on the same boundary. Treat budget exhaustion as a typed failure that alerts, dead-letters the work, or escalates to a human. Retrying forever is not an option.
Exponential backoff matters when more than two transactions retry the same conflict. Without backoff, every losing transaction retries at the same instant, re-collides on the next attempt, and exhausts the budget in milliseconds. Powers of two (10, 20, 40, 80) with a cap of 100ms stagger the retries so only a fraction collide on any given attempt.
Summary
You ran txStart against a three-node cluster, and the transaction committed across two partition primaries without the application code ever seeing the routing. Two interleaved transactions then ran under OPTIMISTIC + REPEATABLE_READ. Both committed without an exception, but only one transfer survived. The other was silently overwritten. You closed the loop with OPTIMISTIC + SERIALIZABLE, which catches the same conflict, and a retry-with-backoff utility that recovers automatically.
Cross-partition is not a separate API surface. The cluster routes 2PC participants to whichever primaries own the transaction's keys, so the application opens a transaction, reads, writes, and commits with the same code it would use against a single key. The partition boundary appears in cluster timing rather than in code.
The retry budget is the contract. OPTIMISTIC concurrency converts contention into commit failures the application must handle. A retry loop with exponential backoff covers the recoverable cases, and the budget bounds the unrecoverable ones. When the budget exhausts, contention has crossed a threshold that retries cannot fix, and the alert lands on a human rather than on a transaction silently looping forever.
OPTIMISTIC must pair with SERIALIZABLE. REPEATABLE_READ under OPTIMISTIC is legal Java that returns no error and silently loses writes. The default txStart() returns PESSIMISTIC + REPEATABLE_READ, which is correct. Whenever you change the concurrency to OPTIMISTIC, change the isolation to SERIALIZABLE in the same call.
What's Next
setDistributedJoins(true)for the case where colocation is not possible, covered in When to Break Colocation.Deadlock detection on
PESSIMISTICvia the four-argumenttxStart(c, i, timeout, txSize)overload. See Deadlock Detection in Performing Transactions.TransactionConfiguration, which sets cluster-wide transaction defaults. Performing Transactions shows how to set the default transaction timeout and the partition map exchange timeout.
The next tutorial in this learning path, Compute Where the Data Lives: The Round-Trip Problem, moves from atomic writes to compute. When the data is too large to pull to the client, the answer is to ship the code to the data.
Related
Use Transactions with the Cache API covers the transaction API on a single-node cluster, including the
OPTIMISTIC + SERIALIZABLEretry pattern that this tutorial extends.Understand How Your Cache Is Distributed covers the partition layout and the Affinity API for inspecting placement. This tutorial reuses that cluster.
This page is: Copyright © 2026 MariaDB. All rights reserved.
Last updated
Was this helpful?

