Stateful Stream Processing on Amazon Managed Service for Apache Flink
State is what turns a stream processor from a filter into a long-running application. Flink state remembers the current session, latest device value, rolling count, deduplication window, or incomplete transaction for each key. Amazon Managed Service for Apache Flink operates the Flink control and worker environment and provides durable checkpoints, scaling, logging, and deployment integration.
This post is archival: the post date is 2018, but the AWS service was originally launched and named Kinesis Data Analytics for Apache Flink. It is now Amazon Managed Service for Apache Flink. The application concepts are the same, while console fields, APIs, runtime versions, and connector packaging have evolved. Verify the current service limits and supported Flink versions when deploying.
Managed control plane, application responsibility
The managed service reduces the work of provisioning clusters, but it does not infer a correct state model. The application team still owns:
- the event-time and watermark policy;
- key selection and expected key cardinality;
- state type, time-to-live (TTL), and serialization;
- connector and application compatibility;
- restart, savepoint, rescaling, and rollback behavior;
- service-level objectives and alerts.
Use least-privilege IAM for the application role. It needs access to the source and sink streams or topics, S3 artifacts, state destinations where applicable, and logging. A broad * policy makes a stateful application convenient to deploy and difficult to audit.
Keyed state and operator state
Flink keyed state is partitioned with keyBy. ValueState stores one value per key, ListState stores a collection, and MapState supports a map-like index for each key. Operator state is attached to an operator subtask rather than an individual key; it is common for source connector offsets and custom shard-aware buffers.
For example, maintain the latest observed temperature and event count per device:
public final class DeviceState
extends KeyedProcessFunction<String, Reading, DeviceAlert> {
private transient ValueState<DeviceSummary> summaryState;
@Override
public void open(Configuration config) {
StateTtlConfig ttl = StateTtlConfig
.newBuilder(Time.days(7))
.setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
.setStateVisibility(
StateTtlConfig.StateVisibility.NeverReturnExpired)
.cleanupInRocksdbCompactFilter(1_000)
.build();
ValueStateDescriptor<DeviceSummary> descriptor =
new ValueStateDescriptor<>(
"device-summary-v1", DeviceSummary.class);
descriptor.enableTimeToLive(ttl);
summaryState = getRuntimeContext().getState(descriptor);
}
@Override
public void processElement(
Reading input,
Context context,
Collector<DeviceAlert> output) throws Exception {
DeviceSummary previous = summaryState.value();
DeviceSummary current = previous == null
? DeviceSummary.first(input)
: previous.with(input);
summaryState.update(current);
if (input.celsius() > 90.0 && current.count() >= 3) {
output.collect(DeviceAlert.from(input, current));
}
}
}
Register the timer or cleanup TTL according to the business deletion rule. Flink TTL controls internal state lifetime; it does not automatically delete output facts from a database or lake.
Use stable operator UIDs so a new JAR can locate state:
readings
.keyBy(Reading::deviceId)
.process(new DeviceState())
.uid("device-state-v1")
.name("device state");
Application configuration
Managed service configuration maps runtime properties into Flink settings. A representative application group can contain:
pipeline.name: device-monitor-v3
execution.checkpointing.interval: 60000
execution.checkpointing.mode: EXACTLY_ONCE
execution.checkpointing.min-pause: 30000
execution.checkpointing.timeout: 300000
execution.checkpointing.unaligned.enabled: true
state.backend: rocksdb
state.checkpoints.num-retained: 3
parallelism.default: 8
In current managed deployments, configure properties through the service API or console schema for the supported runtime, not by assuming an on-premises flink-conf.yaml is mounted in the same way. Keep application-specific values in a DataStream property group and read them using ParameterTool.
State backend trade-offs
| Backend | Strength | Trade-off | Best fit |
|---|---|---|---|
| Heap / hashmap | Fast object access, simple behavior | State constrained by JVM memory; garbage collection pressure | Small, bounded state |
| Embedded RocksDB | Larger state can spill to local disk; incremental checkpoints | Serialization, compaction, filesystem IO, larger native footprint | Large state or high key cardinality |
RocksDB is not a universal performance fix. A hot key serializes into one state partition, so extra tasks do not help. Avoid values that grow without bounds, and split a logically shared counter into sharded keys where output semantics allow it.
State size should be estimated from data rather than memory intuition:
state bytes ~= active keys
x (serialized key + serialized value + state metadata overhead)
x safety factor
Add churn. If 20 million users are active for seven days and each record stores 300 bytes including key overhead, the checkpoint can exceed 6 GB before allowing RocksDB and serializer overhead. Load the expected active-key distribution, not a uniform synthetic key set.
Checkpoint and savepoint lifecycle
Automatic checkpoints support recovery from infrastructure failure. The managed service stores the latest recoverable application state according to its runtime and application snapshot settings. Savepoints are explicit snapshots for deploy rollback, state migration, and rescaling.
An operational upgrade sequence is:
- Confirm the latest checkpoint is successful.
- Stop updates and trigger a savepoint with the service control API or console.
- Record Flink version, JAR hash, source offsets, and operator UIDs.
- Deploy the new application from the savepoint.
- Observe two checkpoint successes and end-to-end output.
- Keep the previous savepoint until the new version meets the rollback window.
Snapshotting alone does not make arbitrary schema changes compatible. A Java class layout change may fail to deserialize. Give every evolving state object a version field, use a stable schema, and test restore from the oldest supported savepoint format.
Rescaling stateful jobs
When restoring a keyed job at a new parallelism, Flink redistributes key groups. The network and checkpoint cost is highest around the first runs after a stateful scale change. Increase parallelism gradually and watch:
- managed processing units or capacity and CPU;
- consumer lag and bytes consumed per task;
- state read/write latency and RocksDB compaction time;
- task idle time, busy time, and backpressure;
- checkpoint size, duration, and upload throughput;
- number of active keys and key-group skew.
More parallelism also adds task fan-out and can produce more small files in an S3 or table sink. A database sink may become connection-bound before Flink becomes compute-bound.
Maintain maximum parallelism deliberately. It defines the upper key-group partitioning used by saved state:
env.setParallelism(8);
env.setMaxParallelism(128);
Changing maximum parallelism across restore boundaries is not an ordinary rescale; plan and test it as a migration.
Observability
Metrics must connect infrastructure to data semantics:
| Signal | Why it matters | Action threshold example |
|---|---|---|
| Consumer lag | Recovery and source backlog | Above one minute for 10 minutes |
| Checkpoint age | Recoverable position is stale | Above 3 intervals |
| Checkpoint duration | IO or serialization pressure | Above 30% of interval |
| State size | Retention or cardinality leak | Above forecast by 20% |
| Processed late records | Watermark or upstream delay | Above agreed SLO |
| DLQ rate | Schema or validation defect | Any sustained increase |
| Job restart count | Dependency or application failure | More than 2 in 15 minutes |
Export application logs with job ID and deployment version. Avoid logging every event. A high-volume pipeline can spend more on log ingestion than stream compute while also increasing operator latency.
Upgrade and recovery behaviors
A managed failure restart restores from the latest valid checkpoint. It does not make a bad event valid: poison data replays and can fail again. The main recovery strategies are:
- validate and route bad records to a DLQ;
- repair the decoder and restart from the checkpoint;
- deliberately restore the last savepoint when a deployment introduced a state bug;
- restart from an older source position only when data-policy owners approve repeated downstream effects.
For a sink that cannot atomically commit, add a stable event ID and a consumer-side idempotency key. Flinkās state may be correct while the external system is not.
Run a failure game every release:
- process known keys and expected outputs;
- force task failure during a checkpoint;
- assert restored counts and timers;
- trigger a stateful upgrade from a savepoint;
- scale the application down and back up;
- verify no state key is lost and no output batch is duplicated.
Managed-service checklist
Before production:
- match connector libraries and Java/Flink versions to the selected runtime;
- pin operator UIDs and state serializer schemas;
- estimate state in bytes and test the p99 key distribution;
- define checkpoint and savepoint retention;
- encrypt artifacts and restrict access to the application role;
- validate recovery, sink semantics, and rollback in staging;
- set lag, checkpoint, restart, DLQ, and data-quality alarms;
- document source offsets and the last known-good application version.
Managed does not mean stateless. It means AWS handles a larger part of the runtime while the application still has to make state, compatibility, and recovery correctness explicit.