Real-time data aggregation

Updated at:

Real-time aggregation involves three recurring trade-offs: how quickly results appear (latency), how accurate those results are when data arrives out of order (completeness), and how much infrastructure complexity you take on to achieve both. This topic compares three solutions that represent a progression along these axes. Each solution fits different business requirements, data volumes, and team capabilities.

Challenges

Real-time aggregation pipelines face three recurring problems at scale.

Late data. In distributed stream processing, data regularly arrives out of order — network delays, upstream system jitter, and processing backpressure all contribute. Without a mechanism to handle late arrivals, late records can overwrite previously correct results, introducing statistical bias into monitoring metrics and business dashboards.

State management at scale. High-cardinality aggregations cause the engine's in-memory state to grow rapidly. Large state volumes slow down checkpointing, extend recovery time after failures, and increase the risk of out-of-memory errors.

Resource versus accuracy trade-offs. Keeping everything in memory is fast but expensive. Offloading state to external storage reduces memory pressure but adds I/O latency. Every aggregation architecture must find a workable position in this space.

Solution comparison

The three solutions map to a latency-accuracy-complexity triangle: lower latency means accepting less accuracy; higher accuracy means either more operational complexity or more infrastructure. Use the table below to identify which trade-offs your use case can absorb.

Solution Core strengths Typical use cases Dev complexity O&M complexity Data accuracy Downstream write pressure Resource efficiency
Stateful aggregation Simple to implement. Standard stream processing SQL. High data freshness. Real-time alerting, high-frequency trading monitoring, scenarios with fixed dimensions and very low late-data ratios. Low Medium to high (state management) Low (late data) High Medium
Stateless incremental aggregation Handles late data correctly. Eliminates engine-side state management complexity. Financial monitoring metrics, user behavior analysis, historical data correction — any scenario requiring high accuracy when late data is common. Medium Low Very high Medium to high (requires reading historical state) Medium
Data lake intermediate layer aggregation Handles tens of millions of records daily. Significantly reduces downstream write pressure. Supports multiple versions. Large-scale pipelines with diverse sources, multiple consumers, or a need to decouple online storage from analytical storage. High Medium to high (component maintenance) Very high Low (batch writes) Optimal

Stateful aggregation

This solution uses the stream processing engine's built-in state management to maintain aggregation results in memory.

image

The following SQL aggregates a real-time log stream (view_source), calculates page views (pv) and clicks (click) grouped by timestamp (ts) and cluster, and writes results to a sink table (sink_table).

INSERT INTO sink_table
SELECT
  ts, cluster,
  SUM(pv) as pv,
  SUM(click) as click
FROM view_source
GROUP BY ts, cluster;

As data flows through the aggregation operator, the engine looks up the current state for each grouping key, updates it with the new record, and emits the updated result downstream. Most aggregation logic is expressible in standard SQL.

Analysis

The main strengths of stateful aggregation are its low implementation barrier and high data freshness. This makes it well suited to real-time alerting and monitoring dashboards where freshness matters more than perfect accuracy.

The limitations become significant at scale:

  • Late data overwrites correct results. If the state for a key expires due to state Time-To-Live (TTL), a late-arriving record for that key starts a new accumulation from scratch. For example, if the state for a key with pv=999 is cleared at 09:30 because its TTL expires, and a late record with pv=1 arrives afterward, the result is incorrectly recorded as pv=1.

  • State bloat under high cardinality. Hot keys in high-concurrency, high-cardinality scenarios cause the state to grow rapidly, consuming memory and slowing checkpoint operations — which directly affects recovery time and system availability.

  • Recovery time scales with state size. After a failure, the engine must reload the full state from the latest checkpoint. The larger the state, the longer the job is unavailable.

Stateless incremental aggregation

This solution moves state management out of the stream processing engine entirely, delegating it to the storage layer. The engine performs only stateless incremental calculations on each batch of records.

image

The following example shows a user-defined aggregate function (UDAF) that performs incremental calculations only on data in the current batch or window, without retaining state across batches.

public class LongSumAggUDAF extends AggregateFunction<Long, LongAccumulator> {
    @Override
    public LongAccumulator createAccumulator() {
        return new LongAccumulator();
    }

    public void accumulate(LongAccumulator acc, Long value) {
        acc.add(value); // Accumulates data only in the current micro-batch
    }

    @Override
    public Long getValue(LongAccumulator acc) {
        return acc.getValue();
    }
}

LongSumAggUDAF accumulates only the records in the current batch and outputs the incremental sum. It does not maintain any historical state.

How it works

The connector implements the full aggregation using a read-compute-write pattern:

  1. Before writing, the connector reads the current stored value for the primary key.

  2. It adds the UDAF's incremental result to the historical value.

  3. It writes the updated total back to storage.

This pattern produces correct results even after a job restart or when late data arrives — the historical value in storage is always the source of truth.

Analysis

The primary advantage is that this solution completely solves the problem of late data. Because the UDAF has no state to expire, late-arriving records are always accumulated into the correct historical total in storage. Engine-side memory usage and checkpoint size are also significantly reduced.

The trade-off is read amplification: every write operation requires a prior read from storage. This increases read QPS on the storage system and adds some latency per record.

Data lake intermediate layer aggregation

This solution introduces a data lake — Apache Paimon, for example — as an aggregation layer between the stream processing engine and downstream storage. The full architecture is:

Raw data → Stream processing engine (stateless aggregation) → Aggregation data lake → Downstream storage

image

The following SQL creates a Paimon aggregation table. When records share the same primary key (ts, cluster), the data lake automatically merges them using the specified aggregate functions.

-- Create a Paimon aggregation table
CREATE TABLE paimon_agg (
    ts TIMESTAMP(3),
    cluster STRING,
    pv BIGINT,
    click BIGINT,
    PRIMARY KEY (ts, cluster) NOT ENFORCED
) WITH (
    'merge-engine' = 'aggregation',
    'fields.pv.aggregate-function' = 'sum',
    'fields.click.aggregate-function' = 'sum'
);

How it works

Each component in the three-layer architecture has a distinct responsibility:

  1. Stream processing task. Writes the incremental output from stateless aggregation to the Paimon table. The task contains no complex read-compute-write logic.

  2. Data lake (Paimon). Performs incremental aggregation and version management at the storage level using the configured merge engine.

  3. Data lake data merge mechanism. Periodically syncs the final aggregated results to downstream core storage systems in batches, rather than writing each record in real time.

The key to this solution is the data merge mechanism of the data lake, which handles aggregation automatically at the table level.

Analysis

Reduces downstream write pressure. Batch sync to downstream storage replaces per-record writes, significantly lowering real-time write QPS on core storage systems.

Simplifies stream processing logic. The stream processing task focuses only on ingestion and initial incremental processing — no storage reads, no complex merge logic.

Supports multiple consumers and historical queries. Because the data lake maintains version history, downstream systems can query historical snapshots and support diverse consumption patterns without touching the core storage system.

Decouples architectural components. The data lake acts as a universal aggregation layer, making it straightforward to add or change downstream storage systems independently.

Choose a solution

Development complexity and operational complexity tend to move in opposite directions: simpler solutions require more operational attention; more complex architectures reduce ongoing maintenance burden once set up. The right choice depends on your data volume, accuracy requirements, and team's capability to operate additional infrastructure.

Situation Recommended solution
Low late-data ratio, fixed dimensions, freshness is the priority Stateful aggregation
High accuracy required, late data is common, team prefers low O&M Stateless incremental aggregation
Tens of millions of records daily, multiple consumers, need to decouple storage Data lake intermediate layer aggregation

Start with stateful aggregation if your use case fits — it is the simplest to implement and operate. If state TTL expiration causes accuracy problems, move to stateless incremental aggregation. Introduce the data lake layer when data volume and architectural complexity justify it.