Apache Kafka is a durable, partitioned log; Apache Flink is a stateful stream processor. Amazon MSK supplies the managed Kafka infrastructure while Flink turns records into timely views, metrics, and downstream events. This separation is useful: the source remains replayable, and the application owns transformations and state.
The example below accepts checkout events from MSK, rejects malformed records, filters test traffic, and computes a five-minute spend total per region. It sends valid aggregate updates to another topic and malformed events to a dead-letter queue (DLQ).
Topology and contracts
Keep the source and sink contracts explicit before writing an operator:
MSK topic: checkout-events
key: checkout_id
value: JSON event
{
"checkoutId": "co-1042",
"accountId": "a-82",
"region": "us-east-1",
"amountCents": 12495,
"test": false,
"eventTime": "2018-01-18T14:31:22Z"
}
Use schema versioning and a stable event identifier. Kafka partitioning by accountId can preserve per-customer ordering, but the aggregation in this design keys by region, so Flink may need a network shuffle after deserialization. More partitions increase source and key parallelism, but they also increase metadata, connection, and checkpoint overhead.
A compact topology is:
KafkaSource
-> deserialize and validate
-> filter test events
-> keyBy(region)
-> event-time window(5 minutes)
-> aggregate
-> KafkaSink
deserialize failure -> DLQ
Event time versus processing time
Event time is the timestamp assigned by the producing system. It gives reproducible window membership, even when a record arrives late. Processing time is the wall clock at the Flink task; it is simple and low-latency, but restart timing and bursts can change results.
For financial or customer activity aggregates, prefer event time. Assign watermarks from bounded out-of-orderness when the expected lateness is known:
WatermarkStrategy.<Checkout>forBoundedOutOfOrderness(
Duration.ofSeconds(30))
.withTimestampAssigner(
(event, ignored) -> event.getEventTimeEpochMs())
.withIdleness(Duration.ofMinutes(5));
The 30-second bound trades freshness for lateness tolerance. If producers are regularly two minutes behind, a 30-second watermark can close windows too early. A small allowed-lateness interval can update windows after the first result, but only if the sink supports an update or retract representation. Otherwise, route late data to a separate correction stream.
Record watermark lag per source partition. An idle partition must not hold the global watermark forever; mark it idle, but verify that intermittent partitions eventually resume.
Flink DataStream implementation
The following Flink Java example uses tags to keep malformed records in a side output. Version-specific connector artifacts should match the Flink runtime exactly.
public final class CheckoutAggregation {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(60_000L);
env.getCheckpointConfig().setMinPauseBetweenCheckpoints(30_000L);
env.getCheckpointConfig()
.setCheckpointTimeout(120_000L);
KafkaSource<String> source = KafkaSource.<String>builder()
.setBootstrapServers(System.getenv("MSK_BOOTSTRAP_SERVERS"))
.setTopics("checkout-events")
.setGroupId("checkout-aggregate-v1")
.setStartingOffsets(OffsetsInitializer.committedOffsets(
OffsetResetStrategy.EARLIEST))
.setValueOnlyDeserializer(new SimpleStringSchema())
.build();
OutputTag<DeadLetter> badRecords =
new OutputTag<DeadLetter>("bad-records") {};
DataStream<Checkout> valid = env
.fromSource(
source,
WatermarkStrategy.noWatermarks(),
"checkout-source")
.process(new DecodeCheckout(badRecords))
.assignTimestampsAndWatermarks(
WatermarkStrategy.<Checkout>forBoundedOutOfOrderness(
Duration.ofSeconds(30))
.withTimestampAssigner(
(e, ignored) -> e.eventTimeEpochMs())
.withIdleness(Duration.ofMinutes(5)));
DataStream<String> totals = valid
.filter(e -> !e.test())
.keyBy(Checkout::region)
.window(TumblingEventTimeWindows.of(Time.minutes(5)))
.aggregate(new AmountAggregate(), new FormatResult());
totals.sinkTo(KafkaSink.<String>builder()
.setBootstrapServers(System.getenv("MSK_BOOTSTRAP_SERVERS"))
.setRecordSerializer(
KafkaRecordSerializationSchema.builder()
.setTopic("checkout-totals-v1")
.setValueSerializationSchema(new SimpleStringSchema())
.build())
.setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
.setTransactionalIdPrefix("checkout-totals")
.build());
env.execute("checkout-five-minute-totals");
}
}
DecodeCheckout should validate the schema version, required fields, timestamp range, and positive amount. Keep the exception and original payload plus source topic, partition, offset, and failure reason in the DLQ record. Do not silently drop poison messages: that makes data loss difficult to diagnose.
Mapping, filtering, and aggregation
Each transformation has a cost:
- mapping or validation is usually stateless and scales linearly;
- filtering reduces downstream load, but can create hot-skew if many events remain in one key;
- keying controls ownership of state and can produce a shuffle;
- windows retain events or aggregate state until the watermark closes them.
Prefer an incremental aggregate function over retaining every checkout:
final class AmountAggregate
implements AggregateFunction<Checkout, Long, Long> {
public Long createAccumulator() { return 0L; }
public Long add(Checkout event, Long total) {
return Math.addExact(total, event.amountCents());
}
public Long getResult(Long total) { return total; }
public Long merge(Long left, Long right) {
return Math.addExact(left, right);
}
}
Serialization must be deterministic and compatible across savepoint resumes. Do not change field meaning or accumulator type during an ordinary restart.
Scaling and backpressure
Scale source parallelism to the number of Kafka partitions, and set downstream parallelism from measured CPU, serialization, state, and network demand. Parallelism above the source partition count only creates idle readers. Parallelism below it assigns multiple partitions to each task.
Treat sustained backpressure as a feedback signal, not a reason to add resources blindly. Observe:
- Kafka consumer lag by partition;
- records and bytes per second;
- busy, backpressured, and idle time per task;
- source watermark lag and end-to-end latency;
- checkpoint duration, alignment duration, and state bytes;
- records sent to the DLQ.
A starting service objective can be: keep 99th-percentile event latency below 15 seconds, consumer lag below one minute of traffic at normal load, and checkpoint duration below one-third of the checkpoint interval. Load-test at two times expected peak and introduce one slow sink before choosing capacity.
Backpressure naturally propagates to the source and reduces consumption. This preserves bounded memory but increases lag. If lag exceeds the retention window, records can become unrecoverable. Use Kafka retention based on the maximum credible outage and include the checkpoint and replay interval.
Failure, replay, and DLQ behavior
A checkpoint coordinates MSK offsets, Flink state, and the two-phase Kafka sink transaction. On failure, Flink restores the last completed checkpoint. The consumer seeks to the checkpointed offsets, and sink records from an unfinished transaction are not visible. This is why the Kafka consumer of the output topic must use read_committed.
Replay is not a free duplicate loop. If a sink is not transactional, a restored job can emit a previously visible record again. Idempotent event IDs and consumer deduplication remain necessary even when Flink calls the sink exactly once.
DLQ delivery should be asynchronous, bounded, and monitored. A synchronous side call in the main operator can turn a schema error into pipeline-wide backpressure. If the DLQ itself is unavailable, either fail the job to preserve replayable source offsets or persist enough failure state for a later retry. Choosing to drop is a deliberate data policy, not a default.
Recovery runbook:
- Stop producer or schema rollout if the DLQ rate spikes.
- Check the latest completed checkpoint and task-manager restarts.
- Fix the schema or deploy a compatible decoder.
- Restore from the current savepoint when changing application state.
- Replay the DLQ with the original
eventIdand record counts. - Reconcile window outputs and consumer-visible duplicates.
Operational checklist
Before enabling production traffic, verify that:
- Kafka ACLs grant only the required topic and consumer-group actions;
- encryption in transit and at rest is enabled;
- source offsets and output transactions are checkpointed;
- output consumers use committed reads for transactional delivery;
- topic retention exceeds recovery time;
- alerts cover lag, watermark delay, backpressure, failed checkpoints, DLQ volume, and task restarts;
- a game-day replays a measured stream after terminating a task manager.
The core design is therefore not just a fast transformation graph. It is a recoverable position in a log, a deterministic state transition, and an observable contract for every sink.