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

Stream Data With the Data Streamer API

Build a high-throughput pipeline that streams hundreds of thousands of records with the DataStreamer API, including backpressure handling and multi-table referential integrity.

Introduction

Every write operation in the previous tutorials used individual upsert() calls or SQL INSERT statements. Each call is a network round-trip: the client sends one record, waits for the server to acknowledge it, then sends the next. At 59 customers and 2,240 invoice lines, this approach works fine. At 10,000 customers or 500,000 invoice lines, it becomes a bottleneck.

The DataStreamer API replaces that one-at-a-time pattern with a streaming pipeline. Records flow from your application through an internal buffer, get batched into pages, and ship to the cluster in parallel across partitions. The cluster processes pages concurrently while your application continues producing records. The result is throughput measured in tens of thousands of records per second instead of hundreds.

This tutorial builds a commerce data generator that streams Customer, Invoice, and InvoiceLine records into the Music Store tables. The DataStreamer pattern applies to any scenario where individual writes are too slow: bulk data migration, cache warming after restarts, ETL from legacy systems, event ingestion from Kafka, test fixture generation for CI pipelines, and audit trail storage.

Prerequisites

Returning to these tutorials? Verify your environment.

Check that the cluster is running and the Music Store data is loaded:

docker exec gridgain9-node1 /opt/gridgain9cli/bin/gridgain9 sql \
  "SELECT COUNT(*) AS tracks FROM Track;"

Expected result: 3503. If the query succeeds, your environment is ready.

If the containers are stopped, restart them from the directory containing your docker-compose.yml:

docker compose up -d

Data persists across restarts. Wait 15-30 seconds for the nodes to rejoin, then re-run the check above.

If the cluster was destroyed (docker compose down), start the containers and re-initialize:

docker compose up -d

Wait 10 seconds for the nodes to start, then load the license and initialize the cluster:

LICENSE=$(jq -Rs . gridgain-license.json)
curl -X POST http://localhost:10300/management/v1/cluster/init \
  -H "Content-Type: application/json" \
  -d '{"metaStorageNodes":["node1","node2","node3"],"cmgNodes":[],"clusterName":"my-cluster","license":'"$LICENSE"'}'

Download the schema and data files:

Copy the files into the container and load them:

docker cp music-store-schema.sql gridgain9-node1:/tmp/
docker cp music-store-data.sql gridgain9-node1:/tmp/
docker exec gridgain9-node1 /opt/gridgain9cli/bin/gridgain9 sql --file /tmp/music-store-schema.sql
docker exec gridgain9-node1 /opt/gridgain9cli/bin/gridgain9 sql --file /tmp/music-store-data.sql

The schema loader prints "Updated 0 rows" for each DDL statement. The data loader prints row counts per batch. Both commands emit jline reflection warnings that are cosmetic and safe to ignore.

Re-run the check above to verify 3503 tracks are loaded.

What You Will Learn

You will build a commerce data generator that streams over 1,000,000 records across three related tables into the Music Store cluster. Along the way you will learn:

  • How the DataStreamer API delivers orders-of-magnitude faster writes than individual upserts

  • How to configure batch size, parallelism, and flush intervals for throughput

  • How to stream parent-child tables in the correct order to maintain referential integrity

  • How backpressure works in SubmissionPublisher and when to replace it with a custom Flow.Publisher

Set Up the Project

Create a new directory called data-streaming-demo alongside your earlier tutorial projects. Add the following pom.xml:

Create the source directory:

Verify the project compiles:

The first build downloads the ignite-client dependency. Subsequent builds use the cached artifact:

Load Customers With Individual Upserts

Before introducing the DataStreamer, establish a baseline. Load 1,000 synthetic customers using the upsert() call from the RecordView tutorial and measure the throughput.

Create src/main/java/com/example/streaming/UpsertVsStream.java:

Run the comparison:

Expected output:

Throughput depends on your machine's CPU, Docker resource allocation, and network stack. The absolute numbers matter less than the ratio: DataStreamer should be at least an order of magnitude faster than the upsert loop. On a 3-node Docker cluster, typical upsert throughput is 400-1,400 rows/sec. DataStreamer throughput is 15,000-100,000 rows/sec for the same data.

The upsert loop sends one record per network round-trip. At 1,000 records, the round-trip latency dominates. The cluster spends most of its time waiting for the next record. DataStreamer eliminates that wait by batching records into pages. It sends those pages in parallel across partitions, so the cluster processes pages concurrently while your application keeps producing records.

Hover over streamData in your IDE. The signature shows Flow.Publisher<DataStreamerItem<T>> as the first parameter. SubmissionPublisher implements Flow.Publisher, and DataStreamerItem.of() wraps each Tuple. The type chain connects: your Tuple goes into a DataStreamerItem, which goes into a SubmissionPublisher, which feeds streamData.

Configure DataStreamer Options

The default DataStreamerOptions work well for moderate volumes. For higher throughput, four settings control how records flow from your application to the cluster:

Option
Default
Effect

pageSize

1,000

Records batched into one network request. Larger pages mean fewer round-trips but more client memory.

perPartitionParallelOperations

1

Concurrent in-flight requests per partition. Higher values increase throughput but add cluster load.

autoFlushInterval

5,000 ms

How often to flush a partial page. Prevents records from waiting in the buffer when the producer is slower than the page size.

retryLimit

16

Automatic retries for failed pages before the stream aborts. Handles transient network issues and primary replica changes.

Create src/main/java/com/example/streaming/TunedStreaming.java:

Run the tuned streaming test:

Expected output:

At 10,000 records, both default and tuned options finish in under a second. The tuning knobs make a bigger difference when streaming hundreds of thousands of records, running multiple streams concurrently, or streaming to a cluster under load. The values used here (pageSize=500, parallelOps=4, autoFlush=1000ms) are a good starting point for most workloads.

DataStreamer provides at-least-once delivery. If a page fails and the retry succeeds, but the original page also committed, duplicate records are possible. Because Customer uses CustomerId as the primary key, a duplicate upsert overwrites the same row. Applications that stream into append-only tables (event logs, audit trails) should include a unique key for deduplication.

Stream Invoices With Parent-Child Order

The Music Store data has a logical parent-child order: Customer -> Invoice -> InvoiceLine. GridGain 9.1 SQL has no FOREIGN KEY constraints, so nothing enforces the relationship, and your application must load parents before children. If you stream Invoice records that reference a CustomerId before that customer exists, the records still land, but your verification queries and application logic will encounter orphaned rows.

DataStreamer follows the same constraint: stream parents first, then children.

Create src/main/java/com/example/streaming/InvoiceStreaming.java. This class generates Invoice records for 10,000 customers using a Zipf distribution that mimics real e-commerce patterns: most customers place a few orders, but a small percentage account for a large share of the volume.

Run the multi-table streaming test:

Expected output:

The Zipf distribution produces a realistic spread: power buyers at the top with 50 invoices, casual buyers at the bottom with 1. Your specific customer names will differ (many customers tie at 50 invoices, and the tiebreaker depends on partition assignment), but the invoice count of 50 and the total of ~102,000 invoices are consistent across runs.

The JOIN query shows that every Invoice references a valid Customer. If you reversed the streaming order (invoices before customers), the JOIN would still work (GridGain has no foreign key constraints), but the data would be logically inconsistent until the parent table loaded.

Build the Full Three-Table Pipeline

The final table in the chain is InvoiceLine. Each InvoiceLine references an InvoiceId (from the invoices you just streamed) and a TrackId (from the Chinook catalog already in the cluster). Unlike the Customer-Invoice step, InvoiceLine joins newly streamed data to existing catalog data. The generator loads the Track catalog first so it can select valid TrackIds when generating line items.

Create src/main/java/com/example/streaming/CommerceDataGenerator.java:

Run the full pipeline:

Expected output:

Over one million rows across three related tables, streamed in under 15 seconds. The individual upsert() approach would take over 12 minutes for the same data at ~1,400 rows/sec. The four-table JOIN confirms referential integrity: every InvoiceLine references a valid Invoice, every Invoice references a valid Customer, and every InvoiceLine references a valid Track from the original catalog.

The JOIN results show randomly selected tracks from the Chinook catalog. The specific track names depend on partition assignment, which varies between cluster restarts. The row counts (15,000 customers, 156,222 invoices, 858,280 invoice lines) are identical on every run because the generator uses a fixed random seed.

Observe Backpressure With SubmissionPublisher

SubmissionPublisher is Java's built-in Flow.Publisher implementation. It maintains an internal buffer (256 items by default) and delivers items to the subscriber asynchronously. When the buffer fills because the producer is faster than the consumer, submit() blocks the calling thread until space opens.

The submit() method returns a long value called the lag: the estimated number of items buffered but not yet consumed by the subscriber. A lag of 0 means the subscriber is keeping up. A growing lag means the producer is outpacing the consumer. When the lag reaches the buffer capacity, the next submit() call blocks.

Create src/main/java/com/example/streaming/BackpressureDemo.java:

submit() returns the estimated lag (items buffered but not yet consumed) for observability. The code captures it here so you can watch the buffer fill and drain. You don't need to check the lag and decide when to block. When the buffer is full, submit() blocks the calling thread automatically until the DataStreamer consumes items and frees space. Backpressure works the same whether you capture the return value or ignore it.

Run the backpressure test:

Expected output:

The lag peaks above the buffer capacity during the run, which means the buffer filled and submit() blocked the producer thread until the DataStreamer freed space. SubmissionPublisher can report a lag slightly above its capacity when a call has blocked, so the peak (274 here, 288 in other runs) is a sign of backpressure at work, not an error. The lag at the sampled records is small because the subscriber catches up between bursts. Your numbers will differ from run to run.

For batch jobs, migrations, and data generators, SubmissionPublisher is the right choice. It handles backpressure transparently: if the cluster slows down, the producer thread pauses automatically.

The calling thread resumes when buffer space opens. This blocking behavior is acceptable when the producer has nothing else to do while waiting.

For event-driven systems, the blocking model is a problem. A Kafka consumer that blocks on submit() stops polling, which triggers consumer group rebalancing. An IoT gateway that blocks on submit() drops incoming sensor readings. A real-time feed that blocks on submit() falls behind and may never recover. These producers cannot pause.

The non-blocking alternative is a custom Flow.Publisher that produces items only when the DataStreamer requests them.

Stream With a Custom Flow.Publisher

SubmissionPublisher buffers items and delivers them asynchronously, but it blocks when the buffer fills. A custom Flow.Publisher implements demand-based delivery instead: it produces items only when the DataStreamer's internal subscriber calls request(n). The custom publisher never buffers, never blocks, and adds real-time progress tracking for long-running data loads.

The reactive streams contract is a collaboration between two parties:

  1. The subscriber (DataStreamer's internal StreamerSubscriber) calls request(n) to signal how many items it can accept. The value of n depends on the pageSize and perPartitionParallelOperations settings.

  2. The publisher delivers up to n items via onNext(), then waits for the next request(n) call. When all items are delivered, it calls onComplete().

Neither side overwhelms the other. The producer never buffers, never blocks, and never overflows. Kafka consumer frameworks, R2DBC drivers, and Project Reactor use the same contract.

After building the ProgressSubscription below, use Find Usages on the request() method. The call comes from GridGain's internal StreamerSubscriber, not from your code. The DataStreamer controls the pace; your publisher responds to demand.

Create src/main/java/com/example/streaming/StreamingWithProgress.java:

Run the full pipeline with progress tracking:

Expected output:

During the InvoiceLine stream (858,280 rows), the progress bar advances in real time as the DataStreamer pulls records from the publisher. The Invoice stream (156,222 rows) also shows meaningful progress. Customer completes too quickly for the progress bar to advance, which is expected at 15,000 rows.

The ProgressPublisher pattern gives you operational visibility into long-running data loads. In production, you would replace the console progress bar with metrics (Micrometer, Prometheus) or structured logging, but the underlying Flow.Publisher contract is the same.

Summary

You built a commerce data generator that streams over 1,000,000 records across three related tables into the Music Store cluster. The DataStreamer API replaced individual upsert() calls with a streaming pipeline that delivers 40-70x higher throughput on the same hardware.

The patterns from this tutorial apply wherever individual writes are too slow:

Scenario
Pattern from this tutorial

Bulk data migration

Full pipeline: generate or read records, stream in parent-child order, verify with JOINs

Cache warming

Stream hot data from a backing store into GridGain at startup using tuned DataStreamerOptions

ETL from legacy systems

Load source data, transform to Tuples, stream via SubmissionPublisher

Event ingestion (Kafka, IoT)

Custom Flow.Publisher with demand-based delivery to avoid blocking the consumer thread

CI test fixtures

Fixed-seed generator for reproducible datasets at any scale

SubmissionPublisher buffers and blocks, which works for batch jobs where the producer has nothing else to do while waiting. Event-driven systems need demand-based delivery instead: a custom Flow.Publisher that never blocks the producer thread. Both strategies use the same streamData() method and DataStreamerOptions.

The commerce-data-generator.jar used in the schema design tutorial applies the same pattern at 50,000 customers, producing over 2.5 million rows.

What's next. To process data where it lives instead of moving it to the client, see About Distributed Computing.

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

Last updated

Was this helpful?