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

Cache-Aside Under Load

Implement cache-aside against a real MariaDB instance, pressure the database with a workload simulator, and measure the read offload as the cache absorbs 95% of customer lookups.

Introduction

Your relational database works. It serves correct results, enforces constraints, and survives restarts. Under growing load, customer lookups start queuing behind invoice writes, p99 latency climbs, and the operations team asks for a plan.

The benchmark from Work with the Cache API answered one question: on a single localhost hop, MariaDB is 3 to 4 times faster than the cache for primary-key lookups. A database with a warm buffer pool is hard to beat at one read. A cache earns its place by taking the read volume off the database so the database has room to handle everything else: writes, analytical queries, range scans, joins, etc.

In this tutorial, you build a cache-aside implementation that reads from the customers cache first, falls through to MariaDB on a miss, and populates the cache with the fresh row. Then you pressure MariaDB with a workload simulator that drives realistic mixed traffic and measure what the cache absorbs. On a 60-second run with 8 concurrent readers and a second client running 2,000 queries per second against the database, the cache serves 2.5 million lookups while MariaDB sees 118 additional queries from the listen harness. That is the offload.

Cache-aside is mediation, not delegation. The cache does not know about the database and the database does not know about the cache. Application code checks one, falls through to the other, and writes the result back. Everything the cache does for consistency, staleness, and concurrency is controlled by that application code and the cache configuration you already set up in Cache Sizing and Expiry.

This tutorial labels itself "beginner" for GridGain. The surrounding Java stack (Maven, JDBC, Spring XML) is assumed prior knowledge. If any of those is new, skim the linked primer before starting.

You work from a companion repository that ships the Docker configurations and a pre-built workload simulator alongside the reference code you will write. Clone it once during setup and use it through the rest of the tutorial.

Prerequisites

  • Cache API familiarity from Work with the Cache API

  • Eviction and expiry vocabulary from Cache Sizing and Expiry

  • Java 17 or later

  • Maven 3.6 or later

  • Docker Compose 2.23 or later

  • JDBC and connection-pool (HikariCP) familiarity. The tutorial writes a JDBC SELECT and wraps it in a HikariCP DataSource. If you have never touched JDBC, read the Oracle JDBC Basics tutorial first.

Clone the companion repository into your working directory:

The repository contains docker/ (MariaDB and GridGain 8 compose files), listen-harness/ (a multi-threaded driver that exercises the same cache-aside pattern you will write), and workload-simulator/ (the traffic generator). You will start the database from it in Step 1 and build the listen harness from it in Step 8. The code you write in Steps 3-6 lives in your own cache-client/ project; the harness keeps its own copy in a separate Java package (com.example.listen) so the jar builds and runs on its own.

If you completed Start a Local Cache Development Cluster, you can reuse your existing cache cluster. If you arrived here fresh, docker/gridgain8/ inside the clone starts a single-node cluster in one command.

Returning to these tutorials? Verify your cluster is running.

Check that the cluster container is up:

Expected output:

If the container is stopped, restart it:

If the cluster was destroyed (docker compose down), recreate it from your existing setup or from the companion repo's configs:

The GridGain 8 compose file requires a trial license at cache-aside/docker/gridgain8/gridgain-license.xml. Follow the license steps in cache-aside/docker/gridgain8/README.md if you do not already have one.

The cluster runs in-memory. Destroying and recreating it starts with an empty cache.

What You Will Learn

In this tutorial, you:

  • Add a MariaDB container loaded with the Chinook sample dataset alongside the cache cluster

  • Write a Customer POJO and a CustomerRepository that implements cache-aside with coalesced concurrent loads

  • Run a baseline workload simulator against MariaDB alone and record the database's response

  • Run a listen-mode client that drives the cache-aside path in parallel with the simulator

  • Quantify the read offload, interpret the serve rate, and reason about the staleness window the TTL enforces

Start MariaDB With the Chinook Dataset

The cache lives in the GridGain container from the earlier tutorials. The source of truth is a MariaDB container loaded with the Chinook sample database, which models a digital media store: 59 customers, 412 invoices, 2,240 invoice lines, and 3,503 tracks. You run MariaDB alongside the cache in a separate Docker Compose project.

The companion repository you cloned in the prerequisites ships a ready-to-run MariaDB compose file with the Chinook dump already in the init/ directory. Start the container:

What this compose file does

cache-aside/docker/music-db/docker-compose.yml is a small MariaDB 11.4 definition:

The image auto-executes any .sql or .sh file placed in /docker-entrypoint-initdb.d the first time the container starts. The repository mounts the init/ directory read-only into that location, and init/chinook.sql loads the full Chinook schema and data on first boot.

Wait about fifteen seconds for the database to accept connections and the dataset to load, then verify the row counts:

Expected output:

Customer is the read-heavy reference data the cache will absorb. Invoice and InvoiceLine are the write-heavy transactional data that stays in MariaDB. The workload simulator will exercise both.

Extend the Maven Project

If you are working through the Cache-Centric Foundations learning path, you may now have two directories side by side in your working directory: the cache-client/ Maven project you built in Work with the Cache API and Cache Sizing and Expiry, and the cache-aside/ companion repository you cloned in the prerequisites. You edit cache-client/ throughout this tutorial; cache-aside/ ships Docker configurations and pre-built tools you start using in Step 1.

cache-client/pom.xml currently declares the GridGain 8 core dependency and an exec-maven-plugin block that runs the program with the --add-opens flags the thick client needs on Java 17. Its seven classes live in package com.example and exercise the cache in isolation; none of them talk to an external database.

You make two edits to cache-client/ in this step:

  1. Add the MariaDB JDBC driver and HikariCP to pom.xml. MariaDB is the source-of-truth database the cache will fall through to on a miss. HikariCP wraps a pool of connections behind the javax.sql.DataSource interface, reuses TCP sessions across calls, and applies connection-level timeouts. The cache-aside code accepts a DataSource, so the single-threaded example in Step 6 and the multi-threaded listen harness in Step 8 share the same repository class.

  2. Create a new Java package com.example.cacheaside so the new Java files live next to the earlier classes without a name collision.

Starting fresh without `cache-client/` from the earlier tutorials

If cache-client/ does not exist in your working directory, create the directory tree now:

Then continue with the pom block below. You are creating cache-client/pom.xml for the first time rather than replacing an existing file, but the contents are the same. Skip the mkdir command further down this step; you already ran it. The Checkpoint at the end of this step passes either way.

Step 4 walks through LruEvictionPolicyFactory and ModifiedExpiryPolicy without re-introducing those APIs. Both come from Cache Sizing and Expiry; skim that tutorial if the names are unfamiliar.

Replace cache-client/pom.xml with the following:

Create the new package directory:

Confirm the project still compiles:

Maven prints a BUILD SUCCESS line. No class files exist in the new package yet; the next step adds the first one.

Define the Customer POJO

The cache stores Customer objects keyed by CustomerId. Each field maps one-to-one to a column in the MariaDB Customer table, which keeps the JDBC row-to-object translation straightforward.

The cache stores values as bytes on the server so the thick client can fetch them back later. The Java object must implement Serializable (or use a custom marshaller) for that round-trip to work. A plain POJO with a no-argument constructor and standard getters and setters is enough; no GridGain annotations are needed because this tutorial does not run SQL queries against the cache.

Create cache-client/src/main/java/com/example/cacheaside/Customer.java:

Thirteen fields. SupportRepId is Integer (not int) because the column is nullable; the other fields use primitives or String to match the schema. The serialVersionUID is explicit so later revisions of the class do not accidentally invalidate entries written by earlier versions.

Review the Cache Configuration

The customers cache configuration applies four controls from Cache Sizing and Expiry: on-heap storage, LRU eviction, eager TTL, and modified expiry.

Each line matches a decision from the previous tutorial:

  • setOnheapCacheEnabled(true) opts the cache in to the on-heap tier that LRU bounds. Without it, the cluster rejects the configuration.

  • LruEvictionPolicyFactory(1000) caps the on-heap tier at 1,000 entries. That is an order of magnitude larger than the 59-customer Chinook dataset, so every row stays hot for this tutorial.

  • setEagerTtl(true) keeps the TTL sweeper active on this cache. Eager TTL is the default on GridGain 8. The call is explicit to make the setting visible.

  • ModifiedExpiryPolicy sets the entry lifetime to 60 seconds, starting the clock on every write or update. Sixty seconds is short enough to demonstrate TTL behaviour and long enough that the cache warms before the first refresh cycle.

IgniteCache<Integer, Customer> parameterises the cache so findById accepts an int and returns a Customer without casts on either side of the call.

Implement the Cache-Aside Read

Cache-aside is four steps in a read method:

  1. Check the cache for the key.

  2. If a value is there, return it.

  3. On a miss, query the database.

  4. Write the row into the cache and return it.

That sequence describes what a single thread does. Concurrent callers introduce a second concern. On a cold key, every thread sees a miss and queries the database before any of them writes the cache. Eight threads hitting the same unpopulated key produce eight database queries for the same row.

Single-flight coalescing fixes that race. Each key has at most one in-flight database load at a time:

  • The first thread to miss on a key creates a CompletableFuture, publishes it into an in-flight map, queries the database, writes the row into the cache, and completes the future.

  • Every later thread that misses on the same key finds the future already in the map and waits on it instead of issuing its own query. When the first thread completes, all waiters receive the same value.

The database sees exactly one query per unique key per miss event.

The sequence below shows two threads racing on the same cold key. Thread A claims the in-flight slot and runs the database load; Thread B finds the slot occupied and waits on A's future.

Create cache-client/src/main/java/com/example/cacheaside/CustomerRepository.java:

Three lines in this class carry the weight of the pattern:

  • cache.get(customerId) is the fast path. A hit returns immediately in microseconds and never touches MariaDB.

  • inflight.putIfAbsent(customerId, newFuture) is the single-flight guard. The call is atomic: at most one thread publishes its future for a given key. Every other thread that misses on the same key receives the existing future and blocks in awaitLoad.

  • cache.put(customerId, loaded) before newFuture.complete(loaded) is the write-back. The value lands in the cache before any waiting thread sees it, so every caller observes a populated cache after the first miss resolves.

The try/finally around the load is what keeps the in-flight map from leaking. Whether the load succeeds, returns null, or throws, the method removes its future from the map before returning. The two-argument remove checks that the current value is still the expected future; if a race leaves a stale mapping the operation is a no-op.

Run the Cache-Aside Example

The entry point wires the cache configuration from step 4, the repository from step 5, and a two-pass loop that reads all 59 customers twice: once with a cold cache to force misses, then again with a warm cache to serve hits.

Create cache-client/src/main/java/com/example/cacheaside/CacheClient.java:

Run it:

After the cluster banner, the program prints:

Each id=N miss -> loaded in Xms -> populated line is one trip through findById: cache miss, JDBC query to MariaDB, cache populate, return. Fifty-nine of them add up to roughly 200 ms of wall-clock time, most of which is driver warmup on the first load (id=1 is 58 ms; every later load is 1-3 ms).

Pass 2 produces no per-iteration output because no misses happen. Every read hits the cache and returns without touching MariaDB. The 44 ms total is the local cache round trip done 59 times. Cache-aside delivered its first result. The hot set is warm and subsequent reads are free.

The sample customer at the end is proof that the cache round-tripped the object intact. cache.get(1) returned a fully populated Customer with name, email, and country still in place. That is the Serializable contract from step 3 doing its job: the POJO moved through the cache without a schema, without annotations, without a marshaller.

Run the Workload Simulator Alone

A single-threaded loop shows the pattern works. It does not show what happens when the database is carrying production traffic. For that, you need a second client that pressures MariaDB with realistic mixed work while you measure.

The companion repository provides a pre-built workload simulator that drives five concurrent workloads against the Chinook schema. The mix shape approximates production read-heavy traffic:

Workload
Share of total traffic
What it does

customer-lookup

70%

SELECT a Customer row by CustomerId. This is the read the cache will absorb.

order-processing

15%

INSERT an Invoice plus two InvoiceLine rows in a transaction.

customer-registration

5%

INSERT a new Customer with IDs above the high-water mark read at startup.

profile-update

5%

UPDATE Customer Phone by CustomerId.

revenue-report

5%

SUM Invoice totals grouped by BillingCountry.

Build the simulator jar from the companion repository you cloned during setup:

Maven produces cache-aside/workload-simulator/target/workload-simulator.jar. In a separate terminal, run the simulator for sixty seconds at a target rate of 2,000 queries per second:

The simulator prints a live-metrics line every five seconds and a final summary. A 60-second baseline run ends with:

The output below was captured on a laptop-class machine. Run the same simulator against MariaDB on a faster server and throughput goes up while latencies go down; on a resource-constrained environment the numbers move the other way. What matters is the shape of the run (mix percentages near 65-70% customer-lookup, zero errors) and the comparison between this baseline and the combined run in Step 8, both taken on the same machine. The absolute query counts and millisecond figures are not the signal.

That is MariaDB under mixed load with no cache in front of it. Roughly 93,000 total queries in sixty seconds, the majority of them customer lookups. Zero errors. The live-metrics ticks during the run also reported MariaDB Threads_connected=27, which is the simulator's JDBC pool plus internal MariaDB worker threads. This is the baseline measurement.

Another baseline run produces similar numbers within run-to-run noise. The comparison that matters is this baseline against the next run, where the listen harness is also active.

Run the Listen Harness Alongside the Simulator

Your code from Step 6 was single-threaded. That is enough to prove the cache-aside contract, but a single loop cannot exercise the concurrency that single-flight coalescing protects against. The companion repo ships a listen-harness/ module that does: a ListenApp main spawns eight worker threads that each call CustomerRepository.findById in a tight loop. The harness carries its own copy of the Customer, CustomerRepository, and CacheClient classes in package com.example.listen so the jar builds and runs without depending on your cache-client/ project.

Eight threads hitting a cold cache at the same time are exactly the scenario the single-flight coalescing was designed for. Without coalescing, eight threads missing on CustomerId=1 at once would produce eight MariaDB queries for the same row. The in-flight map in findById keeps the database at one query per unique key; the other seven threads wait on the future the first thread published.

What's inside `ListenApp.java`

The class lives at cache-aside/listen-harness/src/main/java/com/example/listen/ListenApp.java in the companion repository. It is test-harness plumbing around the CustomerRepository the harness ships. You do not type it, but understanding its shape is useful:

  • Arg parsing. A small helper walks args[] looking for --flag value pairs. Defaults match what this tutorial uses (MariaDB on localhost, password chinook, 8 threads, 5-second metrics interval), so running the jar with no arguments does the right thing.

  • GridGain client + HikariCP pool. Same TcpDiscoverySpi and HikariCP pattern as your CacheClient, duplicated here instead of extracted so each entry point reads end-to-end on its own. The pool is sized to threads + 2 so every worker can hold a connection during a cache miss.

  • Cache configuration. Identical block to CacheClient. Both entry points see the same customers cache because the cluster addresses the cache by name.

  • Worker loop. Eight daemon threads each call repo.findById(ThreadLocalRandom.current().nextInt(1, customerCount + 1)) in a while loop. The CustomerRepository instance is shared across all eight.

  • Metrics reporter. A single scheduled executor fires every 5 seconds, reads repo.cacheHits(), repo.dbLoads(), and repo.waitedOnInFlight(), and prints a row with the per-window throughput.

  • Shutdown hook. On SIGTERM or Ctrl+C, clears the stop flag, drains the workers, and prints the final summary.

No new cache-aside logic. All the coalescing still happens inside findById; ListenApp is just the harness that exercises it under concurrency.

Before launching the harness, reset MariaDB back to the original 59-customer state. The simulator you ran in Step 7 inserted roughly 6,000 new rows through its customer-registration workload. That is realistic production behavior, but it expands the readable ID range the harness pulls from. The dbLoads arithmetic later in this step (59 dbLoads per TTL cycle) only lines up when you start from 59 customers.

Wait about fifteen seconds for MariaDB to reload the Chinook dataset on the clean volume, then confirm the count:

The query returns 59.

Build the listen harness from the companion repo:

Open a second terminal alongside the one running the simulator. Start the listen harness first and let it run. The jar's default main is ListenApp, so java -jar goes straight to listen mode:

The harness prints a metrics header and a row every five seconds:

Wait about fifteen seconds for the cache to warm. The first row appears and reads something like 5.0s 153733 59 4 100.0 30750.2: dbLoads hold at 59 (one per unique key), waited settles in the low single digits (the threads that happened to arrive while another thread was mid-load), and the cacheHits column grows every tick. Once the cache is warm, dbLoads stops changing until the TTL expires.

Now start the simulator in the first terminal with the same arguments as the baseline run:

For the next sixty seconds, MariaDB is handling the simulator's 2,000 queries per second while the harness's eight threads pull customer rows as fast as the cache can serve them. When the simulator finishes, its final summary reads:

In the second terminal, send a Ctrl+C to the listen harness to stop it and print the final summary:

Those numbers come from the latest GridGain 8 Enterprise version on a laptop-class machine. The run reports a dbLoads count of exactly 59 per TTL cycle with a 100% serve rate.

Sustained throughput varies on GridGain 8. The Enterprise thick client does additional background work (baseline topology management, distributed metastorage updates) that interleaves with the lookup loop, and on a developer machine the lookups/s column sometimes drops to zero for several seconds at a time while a background task holds a communication channel. Under these stalls the harness completes fewer cache hits in the same wall-clock window. The cache-aside contract is unchanged; the dbLoads floor and the 100% serve rate hold. Production JVM tuning (heap size, GC options, direct memory, higher socketWriteTimeout) smooths the stalls.

Two observations deserve a pause.

The dbLoads column is 59 for the entire warm period. The final summary lists 118 only because the run crossed the 60-second TTL boundary; each cached entry expired and reloaded once on the way out. Eight worker threads hit every key concurrently during the warmup, but single-flight coalescing held the database to one query per key per TTL cycle. The waited column shows the rest of that contention: on fast hardware only a handful of threads per TTL cycle arrive while another thread is mid-load, because the load itself completes in a few milliseconds. That is what the ConcurrentHashMap plus CompletableFuture in findById is doing under real contention.

The simulator's total queries went up under the combined load, not down. The baseline was 92,588 queries; this run completed 103,199 queries with identical inputs, an 11% throughput increase. Most p99 latencies dropped on the primary-key paths (customer-lookup 1.34 ms to 0.37 ms, order-processing 3.55 ms to 2.19 ms, customer-registration 1.78 ms to 1.35 ms, profile-update 1.81 ms to 1.27 ms). The revenue-report aggregate rose from 5.13 ms to 6.47 ms p99 because the harness's eight reader threads contend with the GROUP BY BillingCountry scan in the buffer pool; the cache absorbs single-row reads, not table scans. The simulator's workload did not change. What changed is that the listen harness took 2.5 million customer lookups off the database's plate, so the database had more capacity to handle the simulator's own queries.

Interpret the Offload

The offload story has four numbers. Find them in the two summary blocks Step 8 produced:

Variable
Where to find it

cacheHits

Listen harness final summary, Cache hits: line

dbLoads

Listen harness final summary, DB loads: line

waitedOnInFlight

Listen harness final summary, Waited on in-flight: line

sim_queries

Simulator final summary, Total queries: column

Three derived values tell the rest of the story. Let harness_reads = cacheHits + dbLoads + waitedOnInFlight (the total number of findById calls the eight worker threads made):

  • Queries MariaDB actually served = sim_queries + dbLoads

  • Queries MariaDB would have served without the cache = sim_queries + harness_reads

  • Offload percentage = (harness_reads - dbLoads) / (sim_queries + harness_reads)

Applied to the reference output (laptop-class machine, 69-second harness run spanning one TTL boundary):

Step
Calculation
Value

cacheHits

from listen-harness summary

2,497,904

dbLoads

from listen-harness summary

118

waitedOnInFlight

from listen-harness summary

14

sim_queries

from simulator summary

103,199

harness_reads

cacheHits + dbLoads + waitedOnInFlight

2,498,036

MariaDB served

sim_queries + dbLoads

103,317

Without cache

sim_queries + harness_reads

2,601,235

Offload

(harness_reads - dbLoads) / (sim_queries + harness_reads)

96.0%

Plug your own numbers into the same three formulas. Expect two things to shift and one to stay the same.

dbLoads stays near 59 per TTL boundary regardless of hardware. A run that ends before t=60s lands at 59. A run that crosses the 60-second TTL expiry once lands at 118. Two crossings land at 177, and so on. If your dbLoads count is off by more than a couple from this pattern, something else is in play (not enough time to reset MariaDB between runs, a different customerCount, threads misconfigured).

cacheHits scales with your machine. Faster hardware serves more reads in the same wall-clock window, which pushes the offload percentage closer to 100%. Most developer machines land between 95% and 99.9%.

dbLoads is the exact answer to "how many queries did the listen harness send to MariaDB?" A percentage does not explain where the read work went; dbLoads does. With single-flight coalescing, dbLoads equals the number of unique keys touched during each TTL cycle. The eight worker threads produced roughly 2.5 million reads; 118 of those forced a database query (two TTL cycles × 59 unique keys) and the rest were served from the cache (cacheHits) or from an in-flight future for a load another thread started (waitedOnInFlight).

The simulator's workload mix did not change. Customer-lookup stayed near 66-68% of the simulator's own queries in both runs, and the write-to-read ratio was the same. What changed is that MariaDB's total throughput went from 92,588 to 103,199 queries in the same 60 seconds, and p99 dropped on the primary-key paths: customer-lookup from 1.34 ms to 0.37 ms, order-processing from 3.55 ms to 2.19 ms, customer-registration from 1.78 ms to 1.35 ms, profile-update from 1.81 ms to 1.27 ms. The revenue-report aggregate slowed (5.13 ms to 6.47 ms p99) because the harness's eight reader threads contend with the GROUP BY BillingCountry scan in the buffer pool; the cache absorbs single-row reads, not table scans. The listen harness took 2.5 million customer lookups off MariaDB's plate. Freeing that capacity is what produced the headroom the simulator used.

Production environments amplify this. On a single localhost, network latency to MariaDB is well below a millisecond and the cache's advantage is modest per individual read. Across a cloud region or a multi-hop network, the cache's local-memory read is tens to hundreds of times faster than the database round trip, and the load reduction has the same proportional effect on a database that is orders of magnitude larger.

Understand the Stale-Read Tradeoff

The cache does not know about the database and the database does not know about the cache. When the simulator's profile-update workload runs UPDATE Customer SET Phone = ? WHERE CustomerId = ?, MariaDB changes a row that may be cached. The cache keeps serving the old phone number until the entry expires and the next miss reloads from the database. That delay, between a write landing in MariaDB and the cache forgetting its cached copy, is the staleness window.

The ModifiedExpiryPolicy from step 4 bounds that window. Set to 60 seconds, it keeps every cached Customer row at most one minute behind MariaDB. The dbLoads pattern from Step 8 makes the mechanism visible: 59 cold-cache warmup loads, then another 59 every time a 60-second TTL boundary passes. Each batch is the TTL firing and every cached entry being re-fetched on the next access.

Shortening the TTL tightens freshness at the cost of more database queries. A 10-second TTL crosses six boundaries per minute instead of one, so dbLoads runs roughly six times higher for the same workload. The serve rate still stays above 99% because cache-served reads land in the millions while dbLoads stays in the hundreds. Longer TTLs reduce database traffic further but widen the window during which the simulator's profile updates are invisible to cache readers.

A second, narrower staleness source lives between the database read and the cache.put. If another writer updates the same row between loadFromDatabase returning and cache.put running, the cache stores the pre-update value and serves it until the TTL expires. The window is small (microseconds to milliseconds in practice) but always greater than zero. Cache-aside's three mitigations are (a) shorter TTL, (b) compare-and-set on the cache.put using a version column from the database row, and (c) switching to write-through so the application updates both stores under one call. The tutorial uses (a). Production systems that cannot tolerate this race pick (b) or (c).

There are three ways to tighten the staleness window further, all of which are out of scope for this tutorial:

  • Write-through: the application writes to the cache and to the database in the same call, so updates never diverge. The cache becomes part of the write path.

  • Write-behind: the application writes to the cache and the cache asynchronously persists to the database.

  • GridGain CacheStore: binds the cache to the database through a factory so read-through and write-through become first-class configuration.

Each of those changes the consistency contract and the failure model. Cache-aside with a bounded TTL is the simplest pattern and the right default. The later patterns are covered in the Beyond Key-Value learning path when the tutorials need them.

Summary

You connected a cache to a source-of-truth database and measured what the cache absorbed. Four files in cache-client/src/main/java/com/example/cacheaside/ carried the work:

  • Customer.java implements Serializable with thirteen fields that match the Chinook Customer schema. The cache round-trips the POJO by value.

  • CustomerRepository.java implements cache-aside with single-flight coalescing. The ConcurrentHashMap<Integer, CompletableFuture<Customer>> guarantees exactly one MariaDB query per unique key per miss event, even under eight concurrent readers.

  • CacheClient.java wires the configured customers cache to the repository and runs the cold-then-warm sequence that proves the pattern end-to-end.

  • The cache-client/pom.xml added the MariaDB JDBC driver next to the GridGain dependency from the earlier tutorials.

The measured offload from the combined simulator-plus-listen-mode run was the headline: 2,497,904 cache hits, 14 threads that waited on another thread's in-flight load, 118 database queries, a 96.0% read reduction on MariaDB. The simulator's workload mix was unchanged, but MariaDB served 11% more queries in the same 60 seconds with faster p99 on every primary-key path. The 60-second ModifiedExpiryPolicy on the cache bounded the staleness window to one TTL, which is the price cache-aside pays for keeping the cache and the database ignorant of each other.

Four controls produced that outcome:

  • The cache configuration from Cache Sizing and Expiry bounded memory and set the staleness window.

  • The single-flight coalescing in findById held dbLoads to one per unique key per TTL cycle.

  • The workload simulator produced a reproducible baseline to compare against.

  • The measured dbLoads is the number that convinces: it is the exact count of queries the listen harness sent to MariaDB.

The cache served two million reads from memory, and the database never saw them.

Next Step

The next tutorial keeps the same cache and adds transactions. Read-modify-write patterns on two or more cache entries (transfer a charge between two customer accounts, for instance) need atomicity guarantees that put and get do not provide. The next tutorial uses ignite.transactions().txStart() with explicit concurrency and isolation levels to close out the Foundations path.

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

Last updated

Was this helpful?