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

Use Transactions With the Cache API

Group related cache operations into ACID transactions. Choose between pessimistic and optimistic concurrency, configure isolation levels, and use EntryProcessor for atomic mutations.

Introduction

The cache from Cache-Aside Under Load cannot carry multi-key transactions. Each entry arrived from the database at its own moment, so the cache never held a consistent snapshot that a transaction could protect.

When state lives in the cache as the source of truth, multi-key consistency becomes the cache's job. Session data, reservations, counters, loyalty points, in-memory work queues. In each case, several keys have to change together, and the cache is what makes that possible.

You add a customer-credits cache that tracks store credit per customer. The cache stores balances as BigDecimal in TRANSACTIONAL atomicity mode. A referral bonus transfers credit from one customer to another, and both balances must change together so the total credit across all customers stays conserved.

The rest of the tutorial runs the scenario through failure modes and contention, closing on a single-key case that needs no transaction at all. Write-through with CacheStore is the other path to multi-key atomicity across a cache and a database; a later guide covers that pattern.

Prerequisites

  • A running single-node cluster from Start a Local Cache Development Cluster

  • Cache API familiarity from Work with the Cache API

  • Java 17 or later for the client runtime. The Maven project in Step 2 compiles to Java 17 bytecode, the same version the server JVM runs. Step 6 ships a class to the server, and the server rejects bytecode newer than its own JVM.

  • Maven 3.6 or later

  • Docker Compose 2.23 or later

If you have the cache-client/ Maven project from Work with the Cache API, you add a new package (com.example.transactions) to it. If you arrived here fresh, Step 2 starts a new project with the same dependency footprint.

The last step of this tutorial uses EntryProcessor, which requires an additional cluster-side setting. Step 6 explains the requirement and walks through the config change.

Returning to these tutorials? Verify your cluster is running.

Check that the cluster container is up:

docker ps --filter name=gridgain8-node1 --format "table {{.Names}}\t{{.Status}}"

Expected output:

NAMES             STATUS
gridgain8-node1   Up X hours

If the container is stopped, restart it:

docker compose -f cache-cluster/docker-compose.yml start

If the cluster was destroyed (docker compose down), recreate it from your existing setup. The cluster runs in-memory, so destroying it discards the cache. Run Step 2's ConfigureCache again to recreate the cache and seed balances.

What You Will Learn

In this tutorial, you:

  • Configure a TRANSACTIONAL cache and seed customer credit balances

  • Observe the partial-write failure mode that two sequential put calls produce under a crash

  • Wrap the same transfer in ignite.transactions().txStart() and watch rollback preserve the invariant

  • Run two concurrent transfers under pessimistic concurrency and watch them serialize on key locks

  • Switch to optimistic concurrency with SERIALIZABLE isolation and handle TransactionOptimisticException with a retry loop

  • Use cache.invoke(key, EntryProcessor) for a single-key atomic mutation that does not open a transaction

Configure a TRANSACTIONAL Cache

Before any code opens a transaction, the cache has to be configured to allow one. That configuration setting is called the cache's atomicity mode. Every cache has one, and the choice is made when the cache is first created.

Two modes exist:

  • ATOMIC is the default. Each put, get, and remove runs as an independent operation. The cache does not track groups of operations as a unit, so transactions are not supported. ATOMIC caches are faster because the cache skips the lock coordination and two-phase commit that transactions need.

  • TRANSACTIONAL is the opt-in mode that supports txStart(). Writes to a TRANSACTIONAL cache acquire key-level locks and commit through a two-phase protocol, which is what makes multi-key atomicity possible.

If you skip the setting and try to open a transaction on an ATOMIC cache anyway, the first cache operation inside the transaction throws.

Since 8.9.0, atomic operations inside transactions are not allowed by default. The exception message names two escape hatches:

Both escape hatches still exist on current GG8 builds. The IGNITE_ALLOW_ATOMIC_OPS_IN_TX system property flips the default cluster-wide, and cache.withAllowAtomicOpsInTx() opts in a single cache. Neither is recommended for tutorial code. They exist to ease migration of legacy applications that mix atomic operations into transactional blocks, and using them here would defeat the atomicity guarantee this tutorial is about to teach.

To use transactions, opt into TRANSACTIONAL mode explicitly on the cache configuration:

The mode is part of the cache's initial configuration and cannot be changed later. Switching modes requires destroying the cache with ignite.destroyCache("customer-credits") and creating a fresh one with the new configuration. The decision is worth making deliberately: a TRANSACTIONAL cache pays a small coordination cost on every write in exchange for the ability to group writes, while an ATOMIC cache trades that cost for simpler semantics and higher throughput.

Create a Maven project if you do not already have one, or add a transactions package to your existing cache-client/ project. The pom.xml declares a GridGain 8 -core dependency and targets Java 17 bytecode so classes shipped to the server in Step 6 load on the server's JVM:

The GridGain 8 Docker images run a Java 17 JVM on the server. The CacheEntryProcessor class in Step 6 ships from the client to the server through peer class loading. If the class is compiled with bytecode newer than the server JVM supports, the server JVM halts with UnsupportedClassVersionError when the closure arrives. Setting maven.compiler.release=17 matches the bytecode to the server.

Create ConfigureCache.java in the com.example.transactions package. The class starts a thick client, creates the customer-credits cache with TRANSACTIONAL atomicity mode, and seeds three customer balances:

Compile and run:

Expected output:

The cache holds three customers with balances that sum to 225. That sum is the application invariant the rest of the tutorial protects. No matter what transfers run, the total across all customers stays at 225.

BigDecimal stores decimal values exactly, without the rounding errors that double introduces around 0.1 + 0.2. Money calculations need exact arithmetic. Using BigDecimal from the start avoids a rewrite later, and it reads identically at the API level: the cache stores whatever serializable type you give it.

Transfer Credit Without a Transaction

Start without a transaction. A referral bonus transfers 30 credit from customer 1001 to customer 1002. In code that means: read both balances, compute the new values, then write each balance back. Two sequential put calls.

Create UnsafeTransfer.java in the same package:

The transferUnsafe method debits the source account, throws a RuntimeException to simulate a process crash, then tries to credit the destination. The crash prevents the second put from running. In a real system, this could be a JVM failure, a thrown exception from downstream code, or a network timeout between the two cache calls.

Run it:

Customer 1001 was debited. Customer 1002 was not credited. The total credit in the system dropped from 150 to 120. The application's invariant (total credit is conserved) is broken, and nothing in the cache can recover the missing 30.

The problem is not the crash. Every real system can fail mid-operation. The problem is that two sequential put calls express the transfer as two independent writes, and a caching layer has no way to know those two writes are related. A transaction is the mechanism that ties both writes to the same commit decision: either both land or neither does.

Transfer Credit With a Transaction

A transaction groups cache operations into one all-or-nothing unit. Three calls make up the API:

  • ignite.transactions().txStart() opens a transaction; every cache operation on the same thread joins it.

  • tx.commit() makes the operations durable and releases locks.

  • tx.rollback() undoes them and releases locks.

Java's try-with-resources handles rollback automatically. The Transaction object implements AutoCloseable, so the JVM calls tx.close() on scope exit. When the block exits after reaching tx.commit(), close is a no-op. Otherwise close rolls the transaction back. Your code only needs to call commit() on the happy path; exception paths handle themselves.

Create SafeTransfer.java with two scenarios: the same simulated crash as before, and a clean commit path:

The transferWithCrash method does the same debit-crash-credit sequence as before, but the three cache operations live inside try (Transaction tx = ignite.transactions().txStart()). The throw exits the try block before tx.commit() runs. The close() method triggered by try-with-resources calls rollback(), and every put the transaction performed is undone.

The transferAndCommit method shows the happy path: read, modify, write, write, commit. No crash, both balances move.

Run it:

In the first scenario, the crash triggered rollback. Both balances are unchanged. Total credit holds at 150.

In the second scenario, tx.commit() made the transfer durable. Customer 1001 dropped to 70, customer 1002 rose to 80, and the total stayed at 150. The invariant holds whether the transaction commits or rolls back. That is the guarantee a transaction provides that two sequential put calls cannot.

The txStart() call with no arguments uses the default concurrency (PESSIMISTIC) and the default isolation (REPEATABLE_READ). Those defaults are the right starting point. The next two steps show the alternatives and when to reach for them.

Handle Contention With Pessimistic Concurrency

One client with one transaction is only half the problem. Real applications have many clients, and they reach for the same keys at the same time. When two transactions both try to transfer credit between customers 1001 and 1002, one of them has to wait.

PESSIMISTIC concurrency answers that question by locking keys on access. Recall from the cache API tutorial that every key has a primary node: the one server node in the cluster that owns the canonical copy of that key's value. When a transaction first touches a key, it takes a lock on that key's primary node. Any other transaction that tries to read or write the same key blocks until the lock is released. Locks are released when the first transaction commits or rolls back. The wait shows up in the timings.

Create PessimisticTransfers.java. Two threads run transfers on the same two keys at the same time. Each holds a 500ms sleep inside the transaction so the contention is visible in the output:

Two CountDownLatch instances coordinate the threads. The first latch confirms both transactions have reached the start line, then the second latch releases them into contention at the same nanosecond. The 500ms sleep inside each transaction makes the contention visible in the timings. Production workloads do not hold locks on purpose.

Run it:

Both threads call txStart() within one microsecond of each other. T1 wins the race for the primary-node lock on key 1001 and reads the pre-transfer balances (100, 50) at 21ms and 36ms. T2 tried to read key 1001 at roughly the same moment, but its read blocked on T1's lock.

T1 sleeps for 500ms holding the locks, then commits at 564907us. At that moment T1's locks release. T2 unblocks and reads the post-T1 values (90, 60) at 564981us and 567836us, 74us after T1's commit returned. T2 sleeps 500ms of its own and commits at 1083458us.

The total wall time is ~1083ms, very close to the sum of both sleeps. The two transactions serialized cleanly on the key locks. The second transfer waited for the first to finish.

The final balances are 75 and 75. Both transfers applied in full: 100 minus 10 minus 15 equals 75, and 50 plus 10 plus 15 equals 75. Total credit stays at 150. The invariant holds, and the cost is that contended transactions run one at a time.

Microsecond timestamps keep the printed order consistent with the causality GridGain enforces. Millisecond resolution is too coarse. A commit and an unblocked read downstream of that commit often fall in the same millisecond, and the two print statements order themselves by output-buffer flush rather than by wall time. If you see a read of a post-commit value timestamped before the commit on a ms-resolution log, that is a logging artifact, not a consistency violation.

Pessimistic is the right choice when contention is common and the application can tolerate the serialized execution. If two transactions want the same keys, one waits. Nothing unusual happens; the waiting client holds a connection until its turn arrives. If waiting is not acceptable for your workload, optimistic concurrency trades waiting for retries.

Handle Contention With Optimistic Concurrency and Retry

Pessimistic concurrency puts the cost of coordination on wait time. The second transaction sits on a lock until the first one commits. Safe, but contended keys process one transaction at a time.

Optimistic concurrency trades waiting for the possibility of failure. Both transactions read in parallel without locks, work against their own in-transaction view, and race to commit. At commit, GridGain checks whether any key in the transaction's read set was modified by another transaction that already committed. If it was, the commit throws TransactionOptimisticException and the application decides what to do next.

The sequence diagram below contrasts the two models on the same two-thread scenario you are about to run:

Three properties of the optimistic model matter for how you write the code:

  • There is no waiting phase. Both transactions proceed as fast as the network allows.

  • One of them can fail. The loser's commit throws and the transaction's writes are rolled back.

  • The application owns the retry. GridGain does not retry for you. Your code catches the exception, reads fresh values, and tries again.

Only TransactionIsolation.SERIALIZABLE turns on the commit-time validation. Without it, OPTIMISTIC does not detect conflicts at all, and contending transactions silently overwrite each other's writes. That is almost never what multi-key logic wants. This tutorial uses SERIALIZABLE.

Create OptimisticTransfers.java:

The try (Transaction tx = ...) block sits inside a bounded retry loop. Three attempts is enough to show the pattern. Production retry budgets depend on the workload. On a TransactionOptimisticException, the enclosing try-with-resources has already rolled the transaction back, so the loop continues without cleanup.

Run it:

Both threads read the same pre-transfer values (100, 50) at t=6ms. No lock acquisition, no blocking. Both proceed to modify their in-transaction view and reach commit around the same time.

T2 commits first at t=259ms. T1's commit arrives moments later and throws TransactionOptimisticException: the validation step detected that T2 had modified keys in T1's read set. The retry loop catches the exception and starts attempt 2.

On attempt 2, T1 reads the post-T2 values (85, 65), applies its own transfer, and commits shortly after. The total wall time is roughly half the pessimistic run on the same scenario, because the losing transaction detected the conflict and retried instead of sitting on a lock while the other finished. Final balances 75 and 75, total credit 150. The invariant holds with a different cost shape.

The exact exception message varies depending on which key conflicted first. Common prefixes that appear in the logs:

Either message means the same thing. Another transaction won the race on at least one of your keys. The application retries.

When does each concurrency mode fit? PESSIMISTIC with REPEATABLE_READ is the right default: correct under any contention, at the cost of serialized execution on contended keys. OPTIMISTIC with SERIALIZABLE and a retry loop is the right choice when throughput matters more than the handful of transactions that retry, and when the application can carry the extra complexity of the retry path.

Earn Credit With an EntryProcessor

Not every atomic cache operation involves multiple keys. "Customer 1003 earns 25 credit" is a single-key read-modify-write: read the current balance, add the bonus, write the new balance. Wrapping it in a transaction works, but the machinery is overkill for one key. The cache API has a tool designed for exactly this shape.

cache.invoke(key, EntryProcessor) ships a closure to the primary node that owns the key. The closure receives a MutableEntry, reads the current value, computes a new value, and writes it back. All of that happens in a single server-side operation, atomically, without opening a transaction. On a distributed cluster, the closure also eliminates the read round-trip that a client-side get followed by a put would cost: the read, the computation, and the write all happen on the node that already owns the key.

Two constraints apply:

  • Serialization. The processor class has to be Serializable because GridGain ships it across the network. org.apache.ignite.cache.CacheEntryProcessor is a subinterface that adds Serializable to the JSR-107 EntryProcessor.

  • Server-side class loading. The server node has to load the class. Peer class loading handles that when both client and server have the flag enabled and the class bytecode is compatible with the server's JVM.

Confirm peer class loading is enabled on the cluster. The flag has to match on every node, so the client's setPeerClassLoadingEnabled(true) call in every class you have written so far has to pair with a matching server-side setting:

If you started your cluster from a configuration that does not include this setting, add it and restart the node.

Create EarnCredit.java:

AddCredit is a stateless, Serializable processor. It reads the entry's current value, adds the increment passed in the args varargs, writes the new value with entry.setValue(), and returns the new balance. GridGain ships the AddCredit class to the primary node for key 1003, runs it there, and returns the result.

Run it:

The read, the add, and the write happened atomically on the primary node. No transaction was opened, no lock coordinator was engaged. EntryProcessor is the tool for single-key atomic mutations and behaves the same on ATOMIC and TRANSACTIONAL caches.

If you call cache.invoke(key, processor) inside a try (Transaction tx = ...) block on a TRANSACTIONAL cache, the invoke participates in the enclosing transaction. A tx.rollback() reverts the processor's changes along with the rest of the transaction. This step runs invoke outside any transaction, which is the common case. Use the composition when you need an EntryProcessor-style atomic mutation to be part of a larger multi-key unit of work.

Summary

You now have three tools for cache atomicity, each sized to a different shape of problem.

Use a transaction when two or more keys have to change together. PESSIMISTIC + REPEATABLE_READ is the default pairing and is correct under any contention; the cost is that contended transactions run one at a time. Reach for OPTIMISTIC + SERIALIZABLE with a retry loop when throughput matters more than avoiding the occasional retry.

Use an EntryProcessor for single-key atomic mutations. One network round trip, one server-side step, atomic by construction. Works on any cache atomicity mode. Run it standalone, or compose it with a transaction when the single-key change is part of a larger multi-key unit of work.

Use plain put when you do not need atomicity beyond the single key, and the cache is configured as ATOMIC. Those operations are the fastest path the cache offers.

Most cache operations a real application performs are single-key, which means EntryProcessor is the tool you reach for most often in practice. Transactions are a narrower case: they earn their place when multi-key invariants live in the cache, and they require the cache to be configured TRANSACTIONAL at creation time.

This tutorial closed the Foundations path. You have seen the cache in three modes: as a self-managing bounded store with eviction and expiry, as a read offload in front of a database, and as a primary transactional store. Together those three modes cover the space of caching use cases a senior developer encounters in a real project.

What's Next

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

Last updated

Was this helpful?