Store Aggregates, Not Event Lists, in Flink State#
Most Flink state problems do not start with a bad design decision. They start with the first version that works. We key the stream, put every event into a list, and on each new event we loop over the list and decide. The output is correct, the demo passes, and nobody looks at state again until checkpoints grow and latency drifts up.
On RocksDB, every access to a growing list reads and rewrites all of it. Every checkpoint copies bytes that no rule ever reads again. The job gets a reputation for being heavy, but the cause is the state design, not Flink.
I showed this in a 60-minute session for the engineering community of a bank. For the session I built a demo where every regulatory rule exists twice, on the same input: the naive job keeps the history, the optimized job keeps the answer. Both raise exactly the same alerts. The optimized job holds 12.7 times less keyed state (2.27 MB down to 179 KB) and needs a fraction of the CPU.
In this article, we will walk through six state patterns from that demo, each with a short Java excerpt of the naive and the optimized version. Then we will look at the measured results and at a way to inspect the state of your own job.
๐ฏ What We Will Cover#
- The demo: two jobs, same input, same alerts, two state designs
- Pattern 1: day buckets in
MapStateinstead of a payment list - Pattern 2: one small POJO with running statistics (Welford)
- Pattern 3: broadcast rules parsed once, not on every event
- Pattern 4: Flink CEP with
within()instead of a hand-written state machine - Pattern 5: one event-time timer per key, moved forward
- Pattern 6: deduplication in
MapStatewith state TTL - Results: bytes per keyed state, busy time, checkpoints and latency
- Inspect your own state with the State Processor API
Prerequisites:
- Apache Flink 1.19.3, DataStream API, Java 11. All patterns are open source Flink and work on Flink 1.17 to 1.20.
- RocksDB state backend (
state.backend.type: rocksdb) flink-cepfor pattern 4 andflink-state-processor-apifor the inspection step- Basic knowledge of keyed state (
ValueState,ListState,MapState) - The demo ran on Ververica Platform 2.14.3 on Amazon EKS. The demo code is available on request (contact details at the end of this article).
๐ The Demo: The Same Rules, Built Twice#
The demo is a small regulatory monitoring system with synthetic data:
- A generator writes bank events (payments, orders, trades, exposure changes, incidents, report status changes) to Kafka as Avro with Schema Registry.
- Rules are rows in a compacted Kafka topic. They reach the jobs as broadcast state, so a changed row changes the running jobs without a restart.
- A monitor job evaluates the rules and raises alerts. A clock job runs the legal deadline clocks (reminder, at risk, breached).
- Each job runs twice on the same input: a naive profile and an optimized profile.
- The rules cover nine regulatory needs from seven EU laws: AMLR, Instant Payments, MAR, CRR, MiFIR, EMIR and DORA.

Here is the full map of what each profile keeps. The rest of the article goes through the rows one by one.
| Use case (law) | Naive keeps | Optimized keeps |
|---|---|---|
| Structuring (AMLR) | every payment, full event | count and sum per day, in MapState |
| Behaviour drift, ML score (AMLR) | every payment, scanned again | count, mean, variance, in one POJO |
| Sanctions (Instant Payments) | raw names, rules as JSON | name hash, rules parsed once, in broadcast state |
| Spoofing (MAR) | every order and trade | three small arrays, pruned on access |
| Large exposure (CRR) | every exposure change | one number and two flags, in ValueState |
| Rejected report (MiFIR, EMIR) | all events, a timer per rejection | a Flink CEP partial match |
| Deadlines (T+1, DORA) | 3 timers per stage, kept | 1 event-time timer per subject, moved |
| Replays (every rule) | every id ever, scanned | two id caches with state TTL |
Two deployments, one JAR#
Both profiles run the same JAR. On Ververica Platform, each profile is its own deployment, and the only differences are a --profile argument and three Flink settings in the deployment spec. This is the optimized monitor deployment, trimmed to the parts that matter here:
metadata:
name: rp-monitor-opt
spec:
upgradeStrategy:
kind: STATEFUL
restoreStrategy:
kind: LATEST_STATE
allowNonRestoredState: false
template:
spec:
artifact:
kind: JAR
flinkVersion: "1.19"
mainArgs: --profile opt ... # jarUri, entryClass and other arguments left out
parallelism: 1
resources:
jobmanager: { cpu: 0.2, memory: 1G }
taskmanager: { cpu: 0.2, memory: 2G }
flinkConfiguration:
state.backend.type: rocksdb
execution.checkpointing.interval: 60s
state.backend.incremental: "true"
pipeline.generic-types: "false" # a Kryo fallback fails the job at start
The naive deployment uses execution.checkpointing.interval: 10s, state.backend.incremental: "false" and pipeline.generic-types: "true". The job code sets the same Kryo rule in Java:
if (args.profile() == Profile.OPT) {
// A type that falls back to Kryo then fails the job when its graph is built, instead of running slowly.
env.getConfig().disableGenericTypes();
}
Key Points:
upgradeStrategy: STATEFULwithrestoreStrategy: LATEST_STATEmeans a cancelled deployment starts again from its latest state. In the demo, a “park” step cancels all jobs, and the next start picks up the state with no manual savepoint handling.- Each Flink pod is capped at 0.2 CPU on purpose, so the difference between the profiles shows at demo event rates.
- The profiles use different checkpoint settings, so the checkpoint times later in this article include that difference.
๐ Pattern 1: Day Buckets in MapState (Structuring)#
Structuring means a customer splits one large transfer into several payments that stay just under a reporting threshold. The rule asks: how many payments just under 10,000 EUR did this customer make in the last 30 days, and what is their total?
The naive version#
The naive job keeps every payment of a customer, as a full event, in one list. On each payment it reads the list, scans all of it, and writes it back:
// Naive: every payment of a customer, as a full wide event, in one list
private transient ValueState<ArrayList<StoredEvent>> payments;
void onEvent(BankEvent payment, ReadOnlyContext ctx, Collector<Alert> out) throws Exception {
ArrayList<StoredEvent> history = payments.value(); // reads the whole list
if (history == null) {
history = new ArrayList<>();
}
for (RuleRow rule : rules(rows(ctx), "WINDOW_SUM")) {
if (inBand(rule, payment.getAmountMinor())) {
windowSum(rule, payment, window(history, rule, payment), out);
}
}
history.add(new StoredEvent(payment));
payments.update(history); // writes the whole list back
}
private static long[] window(List<StoredEvent> history, RuleRow rule, BankEvent payment) {
long cutoff = Time.dayIndex(payment.getEventTime()) - rule.longParam("windowDays");
long[] window = {1, payment.getAmountMinor()};
for (StoredEvent earlier : history) { // every payment ever seen
if (Time.dayIndex(earlier.eventTime) > cutoff && inBand(rule, earlier.amountMinor)) {
window[0]++;
window[1] += earlier.amountMinor;
}
}
return window;
}
The cost of each event grows with the length of the history, not with the question. And the list never gets smaller.
The optimized version#
The question needs only a count and a sum per day. The optimized job keeps a MapState with the key (rule id, day) and the value {count, sum}, and only for payments that fall into the band:
// Optimized: (rule id, day index) -> {count, sum}, only for in-band payments
private transient MapState<Tuple2<String, Long>, long[]> buckets;
private long[] addToWindow(RuleRow rule, BankEvent payment) throws Exception {
long today = Time.dayIndex(payment.getEventTime());
long cutoff = today - rule.longParam("windowDays");
Tuple2<String, Long> todayKey = Tuple2.of(rule.getId(), today);
long[] bucket = buckets.get(todayKey); // one entry, not the history
if (bucket == null) {
bucket = new long[2];
}
bucket[0]++;
bucket[1] += payment.getAmountMinor();
buckets.put(todayKey, bucket);
long[] window = new long[2];
Iterator<Map.Entry<Tuple2<String, Long>, long[]>> it = buckets.iterator();
while (it.hasNext()) {
Map.Entry<Tuple2<String, Long>, long[]> b = it.next();
if (!b.getKey().f0.equals(rule.getId())) {
continue;
}
if (b.getKey().f1 <= cutoff) {
it.remove(); // the day left the window
} else {
window[0] += b.getValue()[0];
window[1] += b.getValue()[1];
}
}
return window;
}
The state descriptor uses only Flink types, so it runs with Kryo switched off:
new MapStateDescriptor<>("window-buckets",
Types.TUPLE(Types.STRING, Types.LONG), PrimitiveArrayTypeInfo.LONG_PRIMITIVE_ARRAY_TYPE_INFO);
Key Points:
- State grows with the number of days in the window, not with the number of payments.
- Old buckets are removed on access, so the state cleans itself while the customer is active.
- A payment outside the band creates no bucket at all.
๐งฎ Pattern 2: One POJO with Running Statistics (Behaviour Drift and ML Score)#
The behaviour rule asks: is this amount far from what this customer usually pays? The ML score asks a similar question with a few more features. Both need a count, a mean and a variance.
The naive version#
The naive job rebuilds the statistics from the full payment list on every payment:
// Naive: one full scan of the history for the baseline and the ML features
Welford stats = new Welford();
AnomalyModel.Recent recent = new AnomalyModel.Recent();
for (StoredEvent earlier : history) {
stats.add(earlier.amountMinor);
recent.add(earlier.country, earlier.amountMinor);
}
baseline(rows, payment, stats, out);
mlScore(rows, payment, stats, recent, ctx, out);
The optimized version#
Welford’s online algorithm updates the mean and the variance with one new value at a time. It needs three numbers, not the history:
public class Welford {
public long count;
public double mean;
public double m2;
void add(long amountMinor) {
count++;
double delta = amountMinor - mean;
mean += delta / count;
m2 += delta * (amountMinor - mean);
}
/** Sample standard deviation, 0 below two samples. */
double stddev() {
return count < 2 ? 0 : Math.sqrt(m2 / (count - 1));
}
}
The optimized job keeps one small object per customer in a ValueState. It is a Flink POJO (public fields, a no-argument constructor), so Flink serializes it without Kryo:
/** What the optimized profile keeps per customer besides the window buckets. */
public static class Customer {
public long nameHash; // hash of the latest customer name
public long lastPaymentTime;
public Welford stats = new Welford(); // count, mean, m2
public AnomalyModel.Recent recent = new AnomalyModel.Recent(); // the ML features
}
ValueStateDescriptor<Customer> d = new ValueStateDescriptor<>("customer", Types.POJO(Customer.class));
Both profiles add the same amounts in the same order, so both get bit-identical statistics and raise the same alerts.
Tip:
For one customer key, the State X-ray (see the last section) showed 309 full payments, 176 KB in the naive job and one Customer object of 81 bytes in the optimized job. Create heavy objects such as an ONNX model once in open(), never per event.
๐ก Pattern 3: Broadcast Rules, Parsed Once (Sanctions)#
Rules arrive as JSON rows from a compacted Kafka topic. The naive job stores the raw JSON in broadcast state and parses it again on every event. The optimized job parses a row once, when it arrives, and stores a POJO:
static final MapStateDescriptor<String, String> RAW_RULES =
new MapStateDescriptor<>("rules", Types.STRING, Types.STRING);
static final MapStateDescriptor<String, RuleRow> PARSED_RULES =
new MapStateDescriptor<>("rules", Types.STRING, Types.POJO(RuleRow.class));
@Override
public void processBroadcastElement(String json, Context ctx, Collector<Alert> out) throws Exception {
Optional<RuleRow> parsed = RuleParser.parse(json);
if (parsed.isEmpty()) {
return;
}
RuleRow row = parsed.get();
if (profile == Profile.NAIVE) {
ctx.getBroadcastState(RAW_RULES).put(row.getId(), json); // parsed again for every event
} else {
ctx.getBroadcastState(PARSED_RULES).put(row.getId(), row); // parsed once, kept as a POJO
}
onRow(row, ctx, out);
}
The sanctions rule also needs the other direction: when a new name is added to the list, which of my customers match it? The optimized job keeps a 64-bit hash of the customer name, and visits all customers of this parallel instance with applyToKeyedState:
void rescreen(Context ctx, RuleRow entry, List<RuleRow> listRules, Collector<Alert> out) throws Exception {
long wanted = Names.hash64(entry.getName());
ctx.applyToKeyedState(customerDescriptor, (customerId, state) -> {
Customer known = state.value();
if (known != null && known.nameHash == wanted) { // two longs, not two strings
rescreened(ctx, listRules, customerId, entry, known.lastPaymentTime, out);
}
});
}
The naive job runs the same loop over the raw names and normalizes each name again on every comparison.
Important:
applyToKeyedState visits every key of the operator instance. Use it for rare events, such as a sanctions list change. Never call it for each normal event.
๐ Pattern 4: Flink CEP with within() (Rejected Report)#
A regulator can reject (NACK) a trade report. The rule asks two questions: was the fixed report sent in time? and was it rejected again right after the fix?
The naive version#
The naive job keeps every report event of the trade in one list, registers one timer per NACK that is never deleted, and scans the list twice when the timer fires:
// Naive: one event-time timer per NACK, never deleted
if (e.getEventType() == EventType.REPORT_NACKED) {
ctx.timerService().registerEventTimeTimer(e.getEventTime() + resubmitMs);
}
history.add(new StoredEvent(e));
events.update(history);
@Override
public void onTimer(long time, OnTimerContext ctx, Collector<LifecycleMatch> out) throws Exception {
ArrayList<StoredEvent> history = events.value();
for (StoredEvent nack : history) { // scan 1
if (nack.eventType != EventType.REPORT_NACKED || nack.eventTime + resubmitMs != time) {
continue;
}
boolean corrected = false;
for (StoredEvent later : history) { // scan 2, inside scan 1
corrected |= later.eventType == EventType.REPORT_RESUBMITTED
&& later.eventTime > nack.eventTime && later.eventTime <= time;
}
if (!corrected) {
out.collect(LifecycleMatch.of(LifecycleMatch.NOT_CORRECTED, nack.tradeId, nack.eventId, time, null,
nack.attributes.get("reason"), nack.eventId));
}
}
}
The optimized version#
The same rule is a sequence with a time limit, which is exactly what Flink CEP does. Each NACK starts a partial match. A later RESUBMITTED inside the window completes it. If the window ends first, the partial match times out, and the timeout is the finding:
static Pattern<BankEvent, BankEvent> notCorrected(long resubmitMs) {
return Pattern.<BankEvent>begin("nack", AfterMatchSkipStrategy.noSkip())
.where(is(EventType.REPORT_NACKED))
.followedBy("resubmit").where(new IterativeCondition<BankEvent>() {
@Override
public boolean filter(BankEvent e, Context<BankEvent> ctx) throws Exception {
long nackTime = ctx.getEventsForPattern("nack").iterator().next().getEventTime();
return e.getEventType() == EventType.REPORT_RESUBMITTED && e.getEventTime() > nackTime;
}
})
.within(Duration.ofMillis(resubmitMs + 1));
}
The timed-out matches go to a side output:
static final class NotCorrected extends PatternProcessFunction<BankEvent, LifecycleMatch>
implements TimedOutPartialMatchHandler<BankEvent> {
@Override
public void processMatch(Map<String, List<BankEvent>> match, Context ctx, Collector<LifecycleMatch> out) {
// corrected in time: nothing to report
}
@Override
public void processTimedOutMatch(Map<String, List<BankEvent>> match, Context ctx) {
BankEvent nack = match.get("nack").get(0);
ctx.output(NOT_CORRECTED, LifecycleMatch.of(LifecycleMatch.NOT_CORRECTED, nack.getTradeId(),
nack.getEventId(), nack.getEventTime() + resubmitMs, null, nack.getAttributes().get("reason"),
nack.getEventId()));
}
}
SingleOutputStreamOperator<LifecycleMatch> corrected =
CEP.pattern(fresh.keyBy(Lifecycle::key), notCorrected(resubmitMs))
.process(new NotCorrected(resubmitMs), MATCH)
.uid("lifecycle-not-corrected").name("lifecycle-not-corrected");
DataStream<LifecycleMatch> findings = corrected.getSideOutput(NOT_CORRECTED);
CEP keeps a partial match only until within() ends it. In the measured run, the report lifecycle state went from 6,128 bytes to 647 bytes.
Trap:
within() ends a partial match at the time of its first event plus the window, and that end is exclusive. If your rule says “a fix at exactly the deadline still counts”, add one millisecond to the window, as the code above does.
Info:
In this demo, the CEP patterns are compiled into the job. Changing CEP patterns at run time, without a restart, is not part of open source Flink 1.20. Ververica’s engine offers it as Dynamic Flink CEP.
โฐ Pattern 5: One Event-Time Timer per Key, Moved Forward (Deadlines)#
The clock job tracks legal deadlines such as trade reporting by T+1 and the DORA incident reports (4 hours, 72 hours, 1 month). Each deadline has milestones: reminder, at risk, breached.
The naive clock keeps the full start events forever and registers three timers per stage that are never deleted:
// Naive: three timers per stage, never deleted
for (Stage stage : created) {
timers.registerEventTimeTimer(stage.timeOf(ObligationStatus.REMINDER));
timers.registerEventTimeTimer(stage.timeOf(ObligationStatus.AT_RISK));
timers.registerEventTimeTimer(stage.deadline);
}
The optimized clock keeps a small POJO with start, deadline and status per stage, and exactly one timer per subject: the next milestone of any open stage, rounded up to the next minute. When the next milestone changes, the old timer is deleted and a new one is registered:
// Optimized: keeps exactly one timer, the next milestone or the clean-up of an ended stage
private static void reschedule(Subject s, TimerService timers) {
long next = Long.MAX_VALUE;
for (Stage stage : s.stages) {
next = Math.min(next, stage.isOpen() ? stage.timeOf(stage.nextMilestone()) : stage.statusTime + Time.DAY_MS);
}
long wanted = Math.floorDiv(next + MINUTE_MS - 1, MINUTE_MS) * MINUTE_MS; // round up to the minute
if (s.timer != null && s.timer == wanted) {
return;
}
if (s.timer != null) {
timers.deleteEventTimeTimer(s.timer);
}
timers.registerEventTimeTimer(wanted);
s.timer = wanted;
}
When the timer fires, ended stages older than one day are dropped. When nothing is left, the whole state of the key is cleared with subject.clear(). In the measured run, the clock checkpoint went from 387 KB to 57 KB.
Tip:
Use event time for deadline timers. A stopped job or a replay then does not fire a flood of late alerts based on the wall clock. Rounding timer timestamps is called timer coalescing: Flink keeps only one timer per key and timestamp.
๐ Pattern 6: Deduplication with MapState and TTL (Replays)#
Upstream systems replay events. Every rule must ignore an event id it has already seen for the key. The naive version keeps every id ever seen in one list and scans it:
// Naive: every id ever seen for the key, in one list, scanned and never pruned
boolean seenBefore(String id, long eventTime, boolean replay) throws Exception {
ArrayList<String> seen = ids.value();
if (seen == null) {
seen = new ArrayList<>();
}
for (String s : seen) {
if (s.equals(id)) {
return true;
}
}
seen.add(id);
ids.update(seen);
return false;
}
The optimized version uses two MapState caches that forget: a live cache (30 minutes by default) and a short replay cache (5 minutes by default), each with state TTL. A replay storm fills only the short-lived replay cache:
private static MapStateDescriptor<String, Long> cache(String name, long minutes) {
MapStateDescriptor<String, Long> d = new MapStateDescriptor<>(name, Types.STRING, Types.LONG);
d.enableTimeToLive(StateTtlConfig.newBuilder(Duration.ofMinutes(minutes)).build());
return d;
}
boolean seenBefore(String id, long eventTime, boolean replay) throws Exception {
if (live.contains(id) || replayed.contains(id)) { // point lookups, no scan
return true;
}
(replay ? replayed : live).put(id, eventTime);
return false;
}
The optimized rule states also get a long TTL as a safety net for keys that stop getting events:
private static final StateTtlConfig IDLE_KEYS = StateTtlConfig.newBuilder(Duration.ofDays(30)).build();
descriptor.enableTimeToLive(IDLE_KEYS);
Trap:
State TTL in Flink 1.19 runs on processing time (the wall clock). A replay that is older than the TTL counts as a new event. Pick the TTL from the longest replay you expect, and prune on access as the main cleanup.
๐ Measured Results#
All numbers come from one acceptance run and one State X-ray, with the same input for both profiles. Both profiles produced the same output: 7 alerts and 1,142 obligations.
Bytes per keyed state#
These are the serialized bytes per keyed state of the monitor job, read from a savepoint with the State Processor API:
| Keyed state | Naive | Optimized |
|---|---|---|
| customer | 1,459,049 B | 109,415 B |
| trader + instrument | 555,287 B | 47,543 B |
| client group | 244,958 B | 20,919 B |
| report lifecycle | 6,128 B | 647 B |
| Total | 2.27 MB | 179 KB (12.7x smaller) |

The bill#
These numbers come from the Flink metrics of the four deployments:
| Measure | Naive | Optimized |
|---|---|---|
| State of the monitor job, normal day | 4.9 MB | 0.5 MB |
| Busy time, normal day (10 events per second) | 165 ms per second | 20 ms per second |
| Checkpoint time, normal day | 2.8 s | 1.4 s |
| Alert latency p95, normal day | 306 ms | 210 ms |
| Busy time at peak (burst x10, then 200 events per second) | 1,000 ms per second (100%, backpressure) โ | 38 ms per second โ |
| Checkpoint time at peak | 32.4 s | 1.8 s |
| Checkpoint size at peak | 14.7 MB | 307 KB |
Important:
Read the shape, not the absolute numbers:
- This is one run on a lab cluster with small state, and each Flink pod is capped at 0.2 CPU on purpose.
- The checkpoint settings differ between the profiles (naive: every 10 s, full snapshots, Kryo allowed; optimized: every 60 s, incremental RocksDB snapshots, Kryo off). The checkpoint times include that difference.
- Busy time is the CPU a job needs. Less busy time means fewer cores for the same traffic. That last step is an inference, not a measurement.
An earlier, smaller lab#
Before the demo, I measured the same idea in a smaller lab: one rule in four state layouts, on Flink 1.19.3 with RocksDB on a laptop, with 1,000 accounts. The p50 latency of one record:
| State layout | p50 latency per record |
|---|---|
ValueState of a list | 38 ยตs |
ListState | 24 ยตs |
MapState | about 10 ยตs |
MapState with only the needed fields | 7 ยตs |
The order is the same as in the demo: the less a record has to read and write, the faster it is.
๐ How to Inspect Your Own State#
You do not need a new tool to find these problems. Take a savepoint, read it with the State Processor API, and list the largest keys per state. This is what the State X-ray job in the demo does.
Step 1: Take a savepoint#
Use the Flink REST API of the JobManager. The job keeps running:
# Trigger a savepoint without stopping the job
curl -s -X POST http://localhost:8081/jobs/<job-id>/savepoints \
-H 'Content-Type: application/json' \
-d '{"target-directory": "s3://<your-bucket>/savepoints", "cancel-job": false}'
# The answer contains a request-id. Poll it until the status is COMPLETED
curl -s http://localhost:8081/jobs/<job-id>/savepoints/<request-id>
The operation.location field of the completed answer is the savepoint path.
Step 2: Add the dependency#
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-state-processor-api</artifactId>
<version>1.19.3</version>
</dependency>
Step 3: Read the keyed state of one operator#
The reader finds an operator by its uid. This is one more reason to set a uid on every stateful operator. The X-ray runs in batch mode and uses the job’s own state descriptors:
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
env.setRuntimeMode(RuntimeExecutionMode.BATCH);
env.setParallelism(1);
SavepointReader reader = SavepointReader.read(env, savepoint, new HashMapStateBackend());
DataStream<KeyStats> stats = reader.readKeyedState(
OperatorIdentifier.forUid("customer-rules"), // the uid of the operator
new KeyReader("customer-rules", descriptors),
Types.STRING, TypeInformation.of(KeyStats.class));
Step 4: Measure each key with the state’s own serializer#
For every key, the reader serializes each state value with the serializer Flink uses for it, and counts the bytes and the registered timers:
final class KeyReader extends KeyedStateReaderFunction<String, KeyStats> {
@Override
public void open(Configuration parameters) {
buffer = new DataOutputSerializer(4096);
for (StateDescriptor<?, ?> d : descriptors) {
switch (d.getType()) {
case VALUE: {
ValueStateDescriptor vd = (ValueStateDescriptor) d;
ValueState state = getRuntimeContext().getState(vd);
TypeSerializer s = vd.getSerializer();
measures.add(() -> {
Object v = state.value();
return v == null ? null : new long[] {size(s, v), entries(v)};
});
break;
}
// LIST and MAP work the same way, entry by entry
}
}
}
@Override
public void readKey(String key, Context ctx, Collector<KeyStats> out) throws Exception {
KeyStats stats = KeyStats.of(uid, key, measures.size());
for (int i = 0; i < measures.size(); i++) {
long[] m = measures.get(i).measure();
if (m != null) {
stats.bytes[i] = m[0];
stats.entries[i] = m[1];
}
}
stats.timers = ctx.registeredEventTimeTimers().size();
out.collect(stats);
}
private long size(TypeSerializer s, Object value) throws IOException {
buffer.clear();
s.serialize(value, buffer); // the bytes Flink writes for this value
return buffer.length();
}
}
Sort the result by bytes and look at the top ten keys of each state. A key with hundreds of entries in a list, or a pile of timers, shows you where to start.
Key Points:
- Ask of every stateful operator: what does each event read, and what does it write?
- Do you keep every event to answer one question?
- Does your deduplication state ever get smaller?
- Compare before and after on state size, checkpoint size and duration, busy time, backpressure and p95 latency.
โ Rules of Thumb for Keyed State#
Production Best Practices:
Let the question pick the primitive:
- “Seen this id?” or “what is in bucket X?”:
MapState. It reads and writes one entry, not all. - “What is the total or the average?”:
ValueStateof a few numbers in one POJO. - “All recent items, read together”: a short list in one value, pruned on every access.
- “Add often, read rarely”:
ListState.add()appends without reading the list. - “This sequence within a time limit”: Flink CEP, not a hand-written state machine.
- “Something is due later”: one event-time timer per key, moved forward.
Avoid (the naive job does all six):
- A list in a
ValueStatethat only grows. - Full wide events in state.
- Kryo fallback for state types. Use
disableGenericTypes()so it fails at start, not in production. - Rule JSON parsed for every event. Parse once in
processBroadcastElement. - Timers that are never deleted.
- No way out for idle keys. Prune on access, and use state TTL as a safety net.
Java habits that run on every event: one static ObjectMapper (thread-safe objects only), heavy objects created in open(), a uid on every operator, and event time for timers.
๐ฏ Summary#
We built the same regulatory rules twice on the same bank events and measured the difference:
- โ Same output: 7 alerts and 1,142 obligations in both profiles
- โ State: 2.27 MB down to 179 KB of keyed state (12.7 times smaller)
- โ CPU: 165 down to 20 ms of busy time per second on a normal day
- โ Peak load: the naive job hit 100% busy and backpressure, the optimized job stayed at 38 ms per second
- โ Checkpoints at peak: 32.4 s down to 1.8 s, and 14.7 MB down to 307 KB
None of this needed a new Flink feature. MapState, a POJO in ValueState, broadcast state, CEP, event-time timers and state TTL are all open source Flink. The change is one question per operator: what does this operator really need to know? Store that, and nothing else.
๐ค How Ververica Can Help#
Ververica: Delivery Assurance for mission-critical real-time data. Built by the original creators of Apache Flinkยฎ. In this story, that shows up in a few concrete ways:
- One JAR, many profiles: on Ververica Platform, each profile was its own deployment with its own Flink configuration, and
LATEST_STATErestores made stops and restarts a non-event. The platform runs self-managed, in your own cloud (BYOC) or as a managed service. - Patterns beyond open source Flink 1.20: CEP patterns that change at run time are available as Dynamic Flink CEP on Ververica’s engine.
- A second pair of eyes on your state: Ververica Professional Services offers Flink job code reviews, health checks and performance tuning by the engineers who built Flink.
- Training for your team: the Ververica Academy teaches stream processing with Flink.
If you want the demo code, a walkthrough of the State X-ray, or a review of the state in your own Flink jobs, reach out to me on LinkedIn or through Ververica.
๐ Related Articles#
- One Spare TaskManager Cut Flink Node Loss Catch-Up From 439 s to 29 s
- Three Fixes That Got a Shared Streaming Lab Ready for 40 Parallel Users
All results in this article come from one run of the demo on Ververica Platform 2.14.3 with Flink 1.19.3, Java 11 and RocksDB on Amazon EKS, with synthetic data. Update 2026-12-06: this post was rewritten with code excerpts and the full results. The first version gave the state saving as “about 13%”; the measured result is 12.7 times smaller.







