Lesson 4 of 7 Amazon Kinesis and Amazon MSK

Processing Streams Statefully with Amazon Managed Service for Apache Flink

This lesson explains how Amazon Managed Service for Apache Flink runs Apache Flink applications for stateful stream processing, aggregating over time windows, joining streams and detecting patterns, without servers to manage.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe what stateful stream processing with Flink provides.
  • Explain how checkpoints provide exactly-once state.
  • Identify the ways Flink applications are written and run.
  • Decide when Flink is the right processing service.

What Flink provides

Apache Flink is designed for stateful processing of unbounded streams: it remembers information across events, which simple per-record processing cannot. Its most common use is windowed aggregation over tumbling windows, which are fixed and non-overlapping, such as each minute; sliding windows, which overlap, such as the last five minutes updated every minute; and session windows, which group a user's events until a period of inactivity.

Flink also joins streams with each other and enriches them with reference data, and it detects patterns across events, such as a sequence of failed logins followed by a password change. It processes by event time, the time each event actually happened, using watermarks to decide when a window is complete, so late and out-of-order records are still counted in the right window.

The following diagram compares the three window types over the same events.

Three kinds of window over the same events. Tumbling windows are fixed and do not overlap, so each event belongs to one window. Sliding windows overlap, so an event can count in several windows. Session windows group a key's events until a gap of inactivity closes the session.
Each dot is an event; the window lengths are illustrative.
Match the pairs

Window types

Exam skills 1.1.12 · 1.1.1

Match each requirement with the window type that fits it.

Log in to try this activity Interactive activities are free with an account.

State and exactly-once processing

Flink keeps application state, such as running totals per key, and saves it periodically in checkpoints. After a failure, the application restores the last checkpoint and replays the source from the matching position, which gives exactly-once state consistency. Snapshots taken on demand preserve state across application updates. End-to-end exactly-once output also needs a transactional or idempotent sink.

The following diagram shows five-minute tumbling windows in a sensor application and how the watermark lets a reading that arrives 20 seconds late still count in the right window.

Five-minute tumbling windows in the sensor application. Windows are assigned by the time each reading was taken. A reading taken at 10:04:50 that arrives 20 seconds late is still counted in the 10:00 window, because the watermark, 30 seconds behind the newest reading, has not yet passed 10:05. Averages above 80 go to an alert stream, and checkpoints keep partial averages across restarts.
The reading times are illustrative.

Building and running applications

Managed Service for Apache Flink runs Flink applications without servers to manage. Applications can be written in Java, Scala or Python, or in SQL through Flink's Table API, which lets analysts write streaming queries. Studio notebooks, based on Apache Zeppelin, let you explore live streams interactively with SQL before building an application.

Applications read from Kinesis Data Streams, MSK or other Kafka clusters and write to S3, OpenSearch, Kinesis, MSK, Firehose or databases. Their processing capacity, called parallelism, is measured in Kinesis Processing Units (KPUs), and it can scale automatically with the load. The following table summarises these options.

AspectOptions
LanguagesJava, Scala, Python, or SQL through the Table API
Interactive developmentStudio notebooks (Apache Zeppelin) for exploring streams with SQL
Sources and sinksKinesis Data Streams, MSK and Kafka in; S3, OpenSearch, Kinesis, MSK, Firehose and databases out
ScalingParallelism in Kinesis Processing Units (KPUs), with automatic scaling
True or false

Running Flink

Exam skills 1.1.1

Decide whether each statement about Managed Service for Apache Flink is true.

Log in to try this activity Interactive activities are free with an account.

When to choose Flink

Several services can process streams, and Flink is the most powerful but not always the simplest. Flink is the answer when processing needs state across many records: aggregations over time windows, joins between streams or detecting patterns, based on when events actually happened rather than when they arrived.

Simpler requirements have simpler answers. Transforming each record on its own and delivering it to S3 is done by Firehose with a Lambda transformation. Processing each record with simple counts over fixed windows can be done by Lambda with tumbling windows. Stream ETL that reuses existing Spark batch code suits Glue streaming jobs. The following table summarises the choice.

RequirementChoose
Stateful windows, joins or pattern detection with event-time semanticsManaged Service for Apache Flink
Simple per-record transformation and delivery to S3Firehose with a Lambda transformation
Per-record processing with simple tumbling-window countsLambda with tumbling windows
Spark-based stream ETL reusing batch codeGlue streaming jobs
Sort into groups

Flink or something simpler?

Exam skills 1.1.1 · 1.2.5

Choose the simplest service for each stream processing need.

Log in to try this activity Interactive activities are free with an account.
Worked example

Five-minute averages per sensor

A factory streams temperature readings from 2,000 sensors into Kinesis Data Streams. Operators need the average per sensor over each five-minute period, based on when the reading was taken, and an alert when an average exceeds 80 degrees. A Flink SQL application computes the windows as follows.

CREATE TABLE readings (
  sensor_id STRING, temperature DOUBLE, reading_time TIMESTAMP(3),
  WATERMARK FOR reading_time AS reading_time - INTERVAL '30' SECOND
) WITH ('connector' = 'kinesis', 'stream' = 'sensor-readings', 'format' = 'json');

SELECT sensor_id, window_start, AVG(temperature) AS avg_temp
FROM TABLE(TUMBLE(TABLE readings, DESCRIPTOR(reading_time), INTERVAL '5' MINUTES))
GROUP BY sensor_id, window_start, window_end
HAVING AVG(temperature) > 80;

The watermark allows readings up to 30 seconds late to be counted in the right window. The results are written to another stream that triggers alerts. Checkpoints preserve the partial averages if the application restarts, so no window is counted twice or lost.

Check yourself

What gives a Flink application exactly-once state consistency after a failure?

Show answer

Checkpoints, which save the application's state so it can resume from a consistent point.

Exam Tips

Remember for the exam

  • Stateful real-time aggregations, windows and joins call for Managed Service for Apache Flink.
  • Flink checkpoints give exactly-once state consistency after failures.
  • Flink applications can be written in SQL, as well as Java, Scala and Python.
  • For interactive SQL exploration of a stream, use Studio notebooks.
  • For simple delivery without state, Firehose is simpler and cheaper than Flink.