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

Real-Time Event Processing: The Streaming Problem

Subscribe to a cache as an event source.

Introduction

Every tutorial in this path so far runs on requests from your code. You query the cache with SQL, run ACID transactions across keys, dispatch compute to where the data lives, make storage durable, and reach for cluster-wide coordination primitives. Each operation starts when the application calls in.

This tutorial inverts that direction. The application registers interest once, and the cluster pushes matching events as they happen.

A traditional caching layer offers two patterns and neither fits. Pub/sub is fire-and-forget and value-blind. The cache fans out a topic message and moves on, with no record of what changed. Keyspace notifications report that a key changed but carry no value, and the set of watched events is fixed by configuration. Neither pattern lets the application say "send me every update where a SKU's quantity drops below ten." Production teams either accept those limits or build a CDC pipeline against an external write-ahead log.

ContinuousQuery<K, V> is a subscription against a cache. You register two halves once. A remote filter factory ships a predicate to every server. The predicate runs against each cache event and decides whether the event reaches the client. A local listener runs on the client and fires on every event the filter accepts. An optional initial scan lets the listener see existing matching entries before live changes start. The cluster pushes filtered events to the application with no polling, no external log, and no custom CDC pipeline. This tutorial closes the Beyond Key-Value path.

Prerequisites

  • A running single-node cluster using cache-cluster/docker-compose.yml from Start a Local Cache Development Cluster. One node is enough. Continuous-query semantics are independent of topology, so an extra server adds no teaching value at this stage.

  • The Stock cache value class on the server's classpath. The continuous query's filter and the initial ScanQuery deserialize cache values inside the server. Peer class loading covers closures (the filter factory, the filter itself), but binary deserialization of cache value classes uses a separate path. The fix is to mount the project jar in the server's libs/user-libs/ directory once. Step 1 covers the one-time mount.

  • Java 17 or later for the client runtime. The Maven project compiles to Java 17 bytecode, the same version the GridGain 8 server JVM runs.

  • Maven 3.6 or later.

  • Two terminal windows. One runs the listener, the other runs the writer that drives the events.

This tutorial creates a fresh continuous-events/ Maven project alongside any other project directories from earlier tutorials in this path. The single-node cache-cluster/ from Start a Local Cache Cluster stays where it is. Step 1 adds a user-libs/ mount to it.

Returning to this tutorial? Restart the single-node cluster.

If the single-node cluster is no longer running, start it before continuing.

docker compose -f cache-cluster/docker-compose.yml up -d
docker ps --filter name=gridgain8-node --format "table {{.Names}}\t{{.Status}}"

One server container in the Up state. The cluster is in-memory, so any prior data was discarded with the previous session. You reseed the Stock cache below.

What You Will Learn

  • How ContinuousQuery turns a cache into an event source the application subscribes to

  • How setRemoteFilterFactory ships a predicate to the server so non-matching updates never cross the network

  • Why the initial query is a ScanQuery (not SqlFieldsQuery) and how the type system enforces it

  • How the QueryCursor doubles as the subscription handle and why closing it unregisters the listener

  • What CacheEntryEvent carries for CREATED, UPDATED, and REMOVED events

What You Will Build

A small Maven project with three runnable scenarios and a model class. SeedStock creates a Stock cache (Integer SKU -> StockLevel) and loads twenty entries with mixed quantities. LowStockListener registers a continuous query whose filter fires whenever an update lands below the threshold. StockWriter runs in a second terminal and decrements quantities every half-second. A writer update whose new value falls under ten appears in the listener's terminal in real time. Updates whose new value stays above the threshold are dropped at the server and never reach the listener.

Define the Stock Cache and Seed Data

Create the continuous-events/ Maven project. The pom uses the same Java 17 bytecode target as the rest of the path so the host client and the cluster server agree on class file format.

continuous-events/pom.xml

GridGain 8 artifacts are not on Maven Central. The <repositories> block points Maven at the GridGain external Nexus.

The ignite-indexing dependency is required because the Stock cache registers indexed types so any client can run SQL queries against it. The continuous query itself does not use SQL, but the cache's QueryEntity makes the cache productive for adjacent operational queries.

Add the StockLevel POJO. It has two fields, both annotated for SQL access:

Add SeedStock. The class creates the cache, loads twenty entries with mixed quantities, and prints both the total count and the count below threshold so the listener's initial state is predictable.

The clientConfig helper is static and package-private so the listener and the writer can reuse it. All three classes share one connection profile.

Build the jar once. The Step 1 artifact contains StockLevel and is mounted on every server. Step 2 introduces the filter factory and ships it to the servers through peer class loading, so this initial jar is intentionally small. If you edit anything in continuous-events/src/ between steps, repackage with mvn -f continuous-events/pom.xml package -DskipTests before re-running:

Mount the jar in the cluster's libs/user-libs/ directory, then restart the cluster so the server picks it up:

Add the volume mount to cache-cluster/docker-compose.yml. Under volumes::

Restart the cluster:

The mount is a one-time setup. When you rebuild the jar after editing classes, the new build lands at the same path, and the next cluster restart picks it up. Peer class loading covers the filter and filter factory closures, but the cache value class (StockLevel) needs to be on the server's classpath because the server deserializes the binary form to evaluate the predicate.

Run SeedStock:

The seed is deterministic (new Random(42)), so re-running the command produces the same twenty entries. SKUs 2, 5, and 11 are below the threshold. Change the seed and the listener reports whatever falls below ten when it registers.

Register the Continuous Query

The ContinuousQuery API has three slots you fill: a local listener, a remote filter factory, and an initial query. The local listener is a callback that runs on this JVM. The remote filter factory ships to every server node and produces the predicate that decides which events leave the server. The initial query is a one-time scan that runs before the subscription starts so the listener can see existing entries that match.

The remote filter factory is a separate class for two reasons. The factory needs to be Serializable (the cluster sends it across the wire), and a named class deserializes cleanly under peer class loading on every JDK. Lambdas can synthesize as JDK hidden classes on Java 17 and above, which the marshaller cannot ship. A named class is the production pattern.

The factory takes the threshold in its constructor. The create() method runs on each server and returns the predicate. The lambda inside create() runs on the server and never serializes. Only the factory itself crosses the wire.

The architecture for the registered subscription:

The filter runs once per cache event on the server. Events that pass the predicate cross the network to the client, and the rest stop at the server before they reach the wire.

Add LowStockListener. The class registers the continuous query and blocks for sixty seconds so the writer scenario in Step 3 has time to fire updates that cross the threshold.

The initial query is a ScanQuery, not a SqlFieldsQuery. You know SqlFieldsQuery from earlier in this path, and the natural reach is to write setInitialQuery(new SqlFieldsQuery("...")). The compiler rejects it. ContinuousQuery.setInitialQuery is declared Query<Cache.Entry<K, V>>. SqlFieldsQuery extends Query<List<?>>, which returns field rows rather than entries, so the type checker turns it away. ScanQuery<K, V> extends Query<Cache.Entry<K, V>> and is the runnable form. The predicate signature is IgniteBiPredicate<K, V>, so the same threshold check shows up twice (filter, scan): once shipped to the server, and once issued as a one-time query at registration.

Run LowStockListener in your first terminal:

The three SKUs below ten match the count SeedStock printed. The listener now waits for live events. Leave this terminal running and switch to the second terminal for Step 3.

Drive Updates From a Second Terminal

StockWriter connects as a separate thick client and decrements quantities every half-second for sixty seconds. Each writer update is a cache.put against an existing SKU. The server applies the continuous-query filter to each event. An update whose new value falls under ten flows through to the listener. An update whose new value stays at or above ten is dropped at the server. The filter is level-based, not edge-based, so a SKU that updates from 8 to 7 also fires the listener. An explicit oldValue >= threshold guard would give edge semantics.

StockWriter reads a quantity, computes the next value, and writes it back. There is no transaction between the read and the write. The pattern is safe in this scenario because StockWriter is the only writer. If two writers raced on the same SKU between this tutorial's cache.get and cache.put, one decrement would be lost. Production code with multiple writers wraps the read/write pair in a transaction or uses cache.invoke(...) with an EntryProcessor. See Use Transactions with the Cache API for both patterns.

In your second terminal:

Now look at terminal 1, the listener:

Compare the two terminals. The writer issued 116 updates over its sixty-second run. The listener received 27 events. Every event in the listener's terminal corresponds to a writer line. The writer lines that did not cross the threshold (SKU 10 at quantity 43, SKU 19 at 33, SKU 4 at 48, and so on) appear nowhere in the listener's output. Those events ran the filter on the server, the predicate returned false, and the cluster dropped them before they crossed the network.

Look at the boundary cases. The third writer line is put SKU 17 qty 11 -> 10. The next line is put SKU 13 qty 11 -> 10. Neither appears in the listener. Ten is not below ten. The listener picks up [21:43:53.941] UPDATED SKU 13 -> qty 9 (was 10) later, when the writer decrements SKU 13 from ten to nine. That decrement crosses the threshold and fires the event.

The wall-clock alignment is the proof. The writer's [21:43:49.792] put SKU 11 qty 7 -> 6 and the listener's [21:43:49.792] UPDATED SKU 11 -> qty 6 (was 7) share a timestamp to the millisecond. The cache is pushing the event in real time. There is no polling loop in either process.

Lifecycle and Cleanup

The cursor returned by cache.query(continuousQuery) is the subscription handle. Iterating it yields the initial query results. Closing it unregisters the listener on every server node.

After sixty seconds the listener exits the try-with-resources block:

The timeline:

After the cursor closes, the listener stops firing on new events. If the writer continues running (the writer in Step 3 was sized to finish at the same time so this does not come up), any further crossings produce no listener output.

Two patterns to know. First, leaking the cursor (storing it in a field and never closing it) leaves the listener registered indefinitely. The cluster keeps the subscription alive and continues sending events the application is no longer reading. Closing in a finally block or via try-with-resources prevents this.

Second, the sixty-second sleep is a tutorial convenience. Production code substitutes the application's main loop, an HTTP server's request handler, or a background thread that waits for shutdown signals. The continuous query stays active as long as the cursor stays open. The sleep is doing nothing more than keeping main alive.

CacheEntryEvent carries different fields for each event type. CREATED has a value, and getOldValue() returns null. UPDATED carries both a new value and the prior value. REMOVED returns the removed value from getValue() (and also from getOldValue() when the cache configuration enables old-value retrieval), per the JSR 107 spec. The listener's print statement handles this with e.getOldValue() == null ? "new" : .... A CREATED event prints "(was new)". An UPDATED event prints the prior quantity, like "(was 7)".

Summary

ContinuousQuery turns a cache into an event source. You registered two halves once. The remote filter factory shipped a predicate to the server, where the predicate ran on every cache event and decided whether the event was sent. The local listener received the events the filter accepted and printed them on the client. The cluster pushed events to the application as they happened.

Two frameworks land. First, continuous queries are subscriptions, not polls. The application registers interest once and processes events as they arrive. The polling loop you would otherwise build, with its timing knobs and back-pressure tuning, becomes unnecessary. Second, the predicate runs on the server next to the data, and only matching events cross the network. This is the same map/reduce shape colocated compute used earlier in this path, applied to events: push the predicate to the data, pull only the matches.

The deeper reframing matches the shape of every other tutorial in this path. The cache-aside scenario had a database that accepted writes and a cache that offloaded reads. With continuous queries, the application subscribes to the cache itself and reacts to writes as a first-class operation. Audit logs, alerting systems, downstream caches, and inventory dashboards now have a natural home against the cache.

The Beyond Key-Value path closes here. You have now seen every place the cache is more than a cache: SQL on cache, atomic writes across keys, in-place compute, durable storage, coordination primitives, and event delivery. The reader who started the path looking for the cache's limits has now found them. The limits are configuration and licensing, not capability.

Three adjacent topics for follow-up content. ContinuousQueryWithTransformer runs a transformation on the server before the event crosses the wire, so the listener receives a projection (one field, a derived value) instead of the full cache value. The JCache CacheEntryListener API registers directly on cache.registerCacheEntryListener with similar semantics. The GridGain-specific ContinuousQuery is the production form because it includes the remote filter factory, but JCache is portable across cache providers. Backup event queues add at-least-once delivery for failover safety. The single-node setup in this tutorial does not exercise them, but production deployments rely on them when a primary node fails.

For the next path, choose between Design for Data Locality for the design-driven treatment of affinity, or the Operations path for production deployment, monitoring, and security. Both build on the cache vocabulary you have completed.

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

Last updated

Was this helpful?