All transformations in Flink may look like functions (in the functional processing terminology), but are in fact stateful operators.
You can make every transformation (
filter, etc) stateful by using Flink’s state interface or checkpointing instance fields of your function.
You can register any instance field as managed state by implementing an interface.
In this case, and also in the case of using Flink’s native state interface, Flink will automatically take consistent snapshots of your state periodically, and restore its value in the case of a failure.
Keyed State and
Keyed State is always relative to keys and can only be used in functions and operators on a
You can think of Keyed State as Operator State that has been partitioned, or sharded, with exactly one state-partition per key. Each keyed-state is logically bound to a unique composite of <parallel-operator-instance, key>, and since each key “belongs” to exactly one parallel instance of a keyed operator, we can think of this simply as <operator, key>.
Keyed State is further organized into so-called Key Groups. Key Groups are the atomic unit by which Flink can redistribute Keyed State; there are exactly as many Key Groups as the defined maximum parallelism. During execution each parallel instance of a keyed operator works with the keys for one or more Key Groups.
Keyed state 只能用于在
Keyed state会以key做partitioned, or sharded，每个keyed-state在逻辑上都会关联一个<parallel-operator-instance, key>，即keyed-state 只属于某一keyed operator的parallel instance
Keyed state的问题在于，在并发度增加时，需要把Keyed State切分开
为了便于keyed state的迁移和管理，实现Key Groups，这是Flink redistribute的最小单位
With Operator State (or non-keyed state), each operator state is bound to one parallel operator instance. The Kafka source connector is a good motivating example for the use of Operator State in Flink. Each parallel instance of this Kafka consumer maintains a map of topic partitions and offsets as its Operator State.
The Operator State interfaces support redistributing state among parallel operator instances when the parallelism is changed. There can be different schemes for doing this redistribution; the following are currently defined:
- List-style redistribution: Each operator returns a List of state elements. The whole state is logically a concatenation of all lists. On restore/redistribution, the list is evenly divided into as many sublists as there are parallel operators. Each operator gets a sublist, which can be empty, or contain one or more elements.
Operator State就是non-keyed state，比如Kafka source connector，会在operator state记录topic partitions and offsets的对应关系
Raw and Managed State
Keyed State and Operator State exist in two forms: managed and raw.
Managed State is represented in data structures controlled by the Flink runtime, such as internal hash tables, or RocksDB. Examples are “ValueState”, “ListState”, etc. Flink’s runtime encodes the states and writes them into the checkpoints.
Raw State is state that operators keep in their own data structures. When checkpointed, they only write a sequence of bytes into the checkpoint. Flink knows nothing about the state’s data structures and sees only the raw bytes.
All datastream functions can use managed state, but the raw state interfaces can only be used when implementing operators. Using managed state (rather than raw state) is recommended, since with managed state Flink is able to automatically redistribute state when the parallelism is changed, and also do better memory management.
Using Managed Keyed State
The Key/Value state interface provides access to different types of state that are all scoped to the key of the current input element.
This means that this type of state can only be used on a
KeyedStream, which can be created via
Key/Value state 只能用于
Now, we will first look at the different types of state available and then we will see how they can be used in a program. The available state primitives are:
ValueState<T>: This keeps a value that can be updated and retrieved (scoped to key of the input element, mentioned above, so there will possibly be one value for each key that the operation sees). The value can be set using
update(T)and retrieved using
ListState<T>: This keeps a list of elements. You can append elements and retrieve an
Iterableover all currently stored elements. Elements are added using
add(T), the Iterable can be retrieved using
ReducingState<T>: This keeps a single value that represents the aggregation of all values added to the state. The interface is the same as for
ListStatebut elements added using
add(T)are reduced to an aggregate using a specified
MapState<UK, UV>: This keeps a list of mappings. You can put key-value pairs into the state and retrieve an
Iterableover all currently stored mappings. Mappings are added using
putAll(Map<UK, UV>). The value associated with a user key can be retrieved using
get(UK). The iterable views for mappings, keys and values can be retrieved using
All types of state also have a method
clear() that clears the state for the currently active key (i.e. the key of the input element).
It is important to keep in mind that these state objects are only used for interfacing with state. The state is not necessarily stored inside but might reside on disk or somewhere else.
The second thing to keep in mind is that the value you get from the state depend on the key of the input element.
So the value you get in one invocation of your user function can be different from the one you get in another invocation if the key of the element is different.
并且取出的状态对象，取决于input element的key；所以不同的调用user function 得到的state value是不一样的，因为element的key 可能不同
To get a state handle you have to create a
StateDescriptor this holds the name of the state (as we will later see you can create several states, and they have to have unique names so that you can reference them), the type of the values that the state holds and possibly a user-specified function, such as a
ReduceFunction. Depending on what type of state you want to retrieve you create one of
State is accessed using the
RuntimeContext, so it is only possible in rich functions.
Please see here for information about that but we will also see an example shortly.
RuntimeContext that is available in a
RichFunction has these methods for accessing state:
MapState<UK, UV> getMapState(MapStateDescriptor<UK, UV>)
This is an example
FlatMapFunction that shows how all of the parts fit together:
Using Managed Operator State
A stateful function can implement either the more general
CheckpointedFunction interface, or the
ListCheckpointed<T extends Serializable> interface.
In both cases, the non-keyed state is expected to be a
List of serializable objects, independent from each other, thus eligible for redistribution upon rescaling. In other words, these objects are the finest granularity at which non-keyed state can be repartitioned. As an example, if with parallelism 1 the checkpointed state of the
BufferingSink contains elements
(test1, 2) and
(test2, 2), when increasing the parallelism to 2,
(test1, 2) may end up in task 0, while
(test2, 2) will go to task 1.
Operator state，即non-keyed state , 被表示为serializable 对象列表，这些对象间是无关的，所以在变更parallelism 时，只需要简单的repartitioned
ListCheckpointed<T extends Serializable>或
ListCheckpointed interface is a more limited variant of
CheckpointedFunction, which only supports list-style state with even-split redistribution scheme on restore
ListCheckpointed interface requires the implementation of two methods:
List<T> snapshotState(long checkpointId, long timestamp) throws Exception; void restoreState(List<T> state) throws Exception;
snapshotState() the operator should return a list of objects to checkpoint and
restoreState has to handle such a list upon recovery.
If the state is not re-partitionable, you can always return a
Collections.singletonList(MY_STATE) in the
CheckpointedFunction interface also requires the implementation of two methods:
void snapshotState(FunctionSnapshotContext context) throws Exception; void initializeState(FunctionInitializationContext context) throws Exception;
Whenever a checkpoint has to be performed
snapshotState() is called. The counterpart,
initializeState(), is called every time the user-defined function is initialized, be that when the function is first initialized or be that when actually recovering from an earlier checkpoint. Given this,
initializeState() is not only the place where different types of state are initialized, but also where state recovery logic is included.
This is an example of a function that uses
CheckpointedFunction, a stateful
SinkFunction that uses state to buffer elements before sending them to the outside world:
Stateful Source Functions
Stateful sources require a bit more care as opposed to other operators.
In order to make the updates to the state and output collection atomic (required for exactly-once semantics on failure/recovery), the user is required to get a lock from the source’s context.
Some operators might need the information when a checkpoint is fully acknowledged by Flink to communicate that with the outside world. In this case see the
Programs written in the Data Stream API often hold state in various forms:
- Windows gather elements or aggregates until they are triggered
- Transformation functions may use the key/value state interface to store values
- Transformation functions may implement the
Checkpointedinterface to make their local variables fault tolerant
Transformation functions中用key/value state interface创建的state
Transformation functions 中通过
Checkpointed interface 去对local variables做的state
When checkpointing is activated, such state is persisted upon checkpoints to guard against data loss and recover consistently.
How the state is represented internally, and how and where it is persisted upon checkpoints depends on the chosen State Backend.
Available State Backends
Out of the box, Flink bundles these state backends:
If nothing else is configured, the system will use the MemoryStateBacked.当前有3种state backends，默认的是用MemoryStateBacked
The MemoryStateBacked holds data internally as objects on the Java heap. Key/value state and window operators hold hash tables that store the values, triggers, etc.
Upon checkpoints, this state backend will snapshot the state and send it as part of the checkpoint acknowledgement messages to the JobManager (master), which stores it on its heap as well.
MemoryStateBackend顾名思义，就是state是存储在Java heap中的；在做checkpoints的时候，state backend 会将state snapshot放入 checkpoint acknowledgement messages 发给JobManager，JobManager 仍然是将它存在heap中。
The FsStateBackend is configured with a file system URL (type, address, path), such as for example “hdfs://namenode:40010/flink/checkpoints” or “file:///data/flink/checkpoints”.
The FsStateBackend holds in-flight data in the TaskManager’s memory. Upon checkpointing, it writes state snapshots into files in the configured file system and directory.
Minimal metadata is stored in the JobManager’s memory (or, in high-availability mode, in the metadata checkpoint).
NOTE: To use the RocksDBStateBackend you also have to add the correct maven dependency to your project:
<dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-statebackend-rocksdb_2.10</artifactId> <version>1.0.3</version> </dependency>
The backend is currently not part of the binary distribution. See here for an explanation of how to include it for cluster execution.
Configuring a State Backend
State backends can be configured per job. In addition, you can define a default state backend to be used when the job does not explicitly define a state backend.
Setting the Per-job State Backend
The per-job state backend is set on the
StreamExecutionEnvironment of the job, as shown in the example below:
Setting Default State Backend
A default state backend can be configured in the
flink-conf.yaml, using the configuration key
Possible values for the config entry are jobmanager (MemoryStateBackend), filesystem (FsStateBackend), or the fully qualified class name of the class that implements the state backend factory FsStateBackendFactory.
In the case where the default state backend is set to filesystem, the entry
state.backend.fs.checkpointdir defines the directory where the checkpoint data will be stored.
A sample section in the configuration file could look as follows:
# The backend that will be used to store operator state checkpoints state.backend: filesystem # Directory for storing checkpoints state.backend.fs.checkpointdir: hdfs://namenode:40010/flink/checkpoints