You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by za...@apache.org on 2025/02/11 06:55:34 UTC
(flink) 01/05: [FLINK-36439][docs] Documents for State V2 APIs
This is an automated email from the ASF dual-hosted git repository.
zakelly pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git
commit 4f61d8585dbb26fa9823e25c04421bd097207e15
Author: Zakelly <za...@gmail.com>
AuthorDate: Wed Feb 5 17:31:41 2025 +0800
[FLINK-36439][docs] Documents for State V2 APIs
---
.../datastream-v2/context_and_state_processing.md | 7 +
.../docs/dev/datastream/fault-tolerance/state.md | 2 +-
.../dev/datastream/fault-tolerance/state_v2.md} | 793 ++++++---------------
.../datastream-v2/context_and_state_processing.md | 7 +
.../docs/dev/datastream/fault-tolerance/state.md | 2 +-
.../fault-tolerance/{state.md => state_v2.md} | 792 ++++++--------------
6 files changed, 454 insertions(+), 1149 deletions(-)
diff --git a/docs/content.zh/docs/dev/datastream-v2/context_and_state_processing.md b/docs/content.zh/docs/dev/datastream-v2/context_and_state_processing.md
index cd17fe26d86..4e95270fac0 100644
--- a/docs/content.zh/docs/dev/datastream-v2/context_and_state_processing.md
+++ b/docs/content.zh/docs/dev/datastream-v2/context_and_state_processing.md
@@ -281,4 +281,11 @@ The specific rules are shown in the following table:
flink will check the legality of state declaration in advance. If an illegal state is declared in `usesStates` method, exception will be thrown at job compile time.
+### State Access Methods
+
+Note that the datastream v2 is using the state v2 APIs. For more detail about the state access
+methods, please refer to the
+[Using Keyed State V2]({{< ref "docs/dev/datastream/fault-tolerance/state_v2#using-keyed-state-v2" >}}).
+
+
{{< top >}}
diff --git a/docs/content.zh/docs/dev/datastream/fault-tolerance/state.md b/docs/content.zh/docs/dev/datastream/fault-tolerance/state.md
index e4d8c3b9c13..4f269a545dc 100644
--- a/docs/content.zh/docs/dev/datastream/fault-tolerance/state.md
+++ b/docs/content.zh/docs/dev/datastream/fault-tolerance/state.md
@@ -1,6 +1,6 @@
---
title: "Working with State"
-weight: 2
+weight: 1
type: docs
aliases:
- /zh/dev/stream/state/state.html
diff --git a/docs/content/docs/dev/datastream/fault-tolerance/state.md b/docs/content.zh/docs/dev/datastream/fault-tolerance/state_v2.md
similarity index 51%
copy from docs/content/docs/dev/datastream/fault-tolerance/state.md
copy to docs/content.zh/docs/dev/datastream/fault-tolerance/state_v2.md
index 2486212055e..6ef16802f80 100644
--- a/docs/content/docs/dev/datastream/fault-tolerance/state.md
+++ b/docs/content.zh/docs/dev/datastream/fault-tolerance/state_v2.md
@@ -1,10 +1,10 @@
---
-title: "Working with State"
+title: "Working with State V2"
weight: 2
type: docs
aliases:
- - /dev/stream/state/state.html
- - /apis/streaming/state.html
+ - /dev/stream/state/state_v2.html
+ - /apis/streaming/state_v2.html
---
<!--
Licensed to the Apache Software Foundation (ASF) under one
@@ -25,20 +25,26 @@ specific language governing permissions and limitations
under the License.
-->
-# Working with State
+# Working with State V2 (New APIs)
-In this section you will learn about the APIs that Flink provides for writing
+In this section you will learn about the new APIs that Flink provides for writing
stateful programs. Please take a look at [Stateful Stream
Processing]({{< ref "docs/concepts/stateful-stream-processing" >}})
to learn about the concepts behind stateful stream processing.
+The new state API is designed to be more flexible than the previous API. User can perform
+asynchronous state operations, thus making it more powerful and more efficient.
+The asynchronous state access is essential for the state backend to be able to handle
+large state sizes and to be able to spill to remote file systems when necessary.
+
## Keyed DataStream
If you want to use keyed state, you first need to specify a key on a
`DataStream` that should be used to partition the state (and also the records
in the stream themselves). You can specify a key using `keyBy(KeySelector)`
-in Java/Scala API or `key_by(KeySelector)` in Python API on a `DataStream`.
-This will yield a `KeyedStream`, which then allows operations that use keyed state.
+in Java API on a `DataStream`. This will yield a `KeyedStream`, which then allows operations
+that use keyed state. You should perform `enableAsyncState()` on the `KeyedStream` to enable
+asynchronous state operations.
A key selector function takes a single record as input and returns the key for
that record. The key can be of any type and **must** be derived from
@@ -52,85 +58,132 @@ grouping operator.
The following example shows a key selector function that simply returns the
field of an object:
-{{< tabs "54e3bde7-659a-4683-81fa-112a2c81036b" >}}
+{{< tabs "54e3bde7-659a-4683-81fa-312a2c81036b" >}}
{{< tab "Java" >}}
```java
// some ordinary POJO
-public class WC {
+public class WordCount {
public String word;
public int count;
public String getWord() { return word; }
}
-DataStream<WC> words = // [...]
-KeyedStream<WC> keyed = words
- .keyBy(WC::getWord);
-```
-
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-// some ordinary case class
-case class WC(word: String, count: Int)
-val words: DataStream[WC] = // [...]
-val keyed = words.keyBy( _.word )
-```
-{{< /tab >}}
-
-{{< tab "Python" >}}
-```python
-words = # type: DataStream[Row]
-keyed = words.key_by(lambda row: row[0])
+DataStream<WordCount> words = // [...]
+KeyedStream<WordCount> keyed = words
+ .keyBy(WordCount::getWord).enableAsyncState();
```
-{{< /tab >}}
{{< /tabs >}}
-#### Tuple Keys and Expression Keys
-
-Flink also has two alternative ways of defining keys: tuple keys and expression
-keys in the Java/Scala API(still not supported in the Python API). With this you can
-specify keys using tuple field indices or expressions
-for selecting fields of objects. We don't recommend using these today but you
-can refer to the Javadoc of DataStream to learn about them. Using a KeySelector
-function is strictly superior: with Java lambdas they are easy to use and they
-have potentially less overhead at runtime.
-
{{< top >}}
-## Using Keyed State
+## Using Keyed State V2
-The keyed state interfaces 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 `stream.keyBy(…)` in Java/Scala API or `stream.key_by(…)` in Python API.
+Unlike the previous state API, the new state API is designed for asynchronous state access.
+Each type of state gives two versions of the API: synchronous and asynchronous. The synchronous
+API is a blocking API that waits for the state access to complete. The asynchronous API is
+non-blocking and returns a `StateFuture` that will be completed when the state access
+is done. After that a callback or following logic will be invoked (if any).
+The asynchronous API is more efficient and should be used whenever possible.
+It is highly **not** recommended to mixed synchronous and asynchronous state access in the same
+user function.
-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:
+The keyed state interfaces provide 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 `stream.keyBy(…)` in Java. And then most importantly,
+the keyed stream needs to be enabled for asynchronous state access by calling `enableAsyncState()`.
+The new API set are only available on `KeyedStream` with `enableAsyncState()` invoked.
+
+Now, we will look at the different types of state available, and then we will see
+how they can be used in a program. Since the synchronous APIs are identical with the original APIs,
+We only focus on the asynchronous ones here.
+
+### The Return Values
+
+First of all, we should get familiar with the return value of those asynchronous state access methods.
+
+`StateFuture<T>` is a future that will be completed with the result of the state access.
+The return bype is T. It provides multiple methods to handle the result, listed as:
+* `StateFuture<Void> thenAccept(Consumer<T>)`: This method takes a `Consumer` that will be called with the result
+ when the state access is done. It returns a `StateFuture<Void>`, which will be finished when the
+ `Consumer` is done.
+* `StateFuture<R> thenApply(Function<T, R>)`: This method takes a `Function` that will be called with the result
+ when the state access is done. The return value of the function will be the result of the following
+ `StateFuture`, which will be finished when the `Function` is done.
+* `StateFuture<R> thenCompose(Function<T, StateFuture<R>>)`: This method takes a `Function` that will
+ be called with the result when the state access is done. The return value of the function should be
+ a `StateFuture<R>`, which is exposed to the invoker of `thenCompose` as a return value.
+ The `StateFuture<R>` will be finished when the inner `StateFuture<R>` of `Function` is finished.
+* `StateFuture<R> thenCombine(StateFuture<U>, BiFunction<T, U, R>)`: This method takes another `StateFuture` and a
+ `BiFunction` that will be called with the results of both `StateFuture`s when they are done. The return
+ value of the `BiFunction` will be the result of the following `StateFuture`, which will be finished when
+ the `BiFunction` is done.
+
+Those methods are similar to the corresponding ones of the `CompletableFuture`. Besides these methods,
+keep in mind that `StateFuture` does not provide a `get()` method to block the current thread until the
+state access is done. This is because blocking the current thread may cause recursive blocking. The
+`StateFuture<T>` also provides conditional version of `thenAccept`, `thenApply`, `thenCompose` and `thenCombine`,
+which is for the case that the state access is done and the following logic will be split into two branches
+based on the result of the state access. The conditional version of those methods are `thenConditionallyAccept`,
+`thenConditionallyApply`, `thenConditionallyCompose` and `thenConditionallyCombine`.
+
+`StateIterator<T>` is an iterator that can be used to iterate over the elements of a state. It provides
+the following methods:
+* `boolean isEmpty()` : A synchronous method returns a `true` if the iterator has no elements, and `false` otherwise.
+* `StateFuture<Void> onNext(Consumer<T>)` : This method takes a `Consumer` that will be called with the next element
+ when the state access is done. It returns a `StateFuture<Void>`, which will be finished when the `Consumer` is done.
+ Also, a function version of `onNext` is provided, which is `StateFuture<Collection<R>> onNext(Function<T, R>)`. This method
+ takes a `Function` that will be called with the next element when the state access is done. The return value of the function
+ will be collected and returned as a collection of the following `StateFuture`, which will be
+ finished when the `Function` is done.
+
+We also provide a `StateFutureUtils` class that contains some utility methods to handle `StateFuture`s.
+These methods are:
+* `StateFuture<T> completedFuture(T)`: This method returns a completed `StateFuture` with the given value. This is
+useful when you want to return a constant value in a `thenCompose` method for further processing.
+* `StateFuture<Void> completedVoidFuture()`: This method returns a completed `StateFuture` with `null` value.
+A void value version of `completedFuture`.
+* `StateFuture<Collection<T>> combineAll(Collection<StateFuture<T>>)` : This method takes a collection of `StateFuture`s
+and returns a `StateFuture` that will be completed when all the input `StateFuture`s are completed. The result of the
+returned `StateFuture` is a collection of the results of the input `StateFuture`s. This is useful when you want to
+combine the results of multiple `StateFuture`s.
+* `StateFuture<Iterable<T>> toIterable(StateFuture<StateIterator<T>>)` : This method takes a `StateFuture` of `StateIterator`
+and returns a `StateFuture` of `Iterable`. The result of the returned `StateFuture` is an `Iterable` that contains all
+the elements of the `StateIterator`. This is useful when you want to convert a `StateIterator` to an `Iterable`.
+There is no good reason to do so, since this may disable the capability of lazy loading. Only useful when the further
+calculation depends on the whole data from the iterator.
+
+
+### State Primitives
+
+The available state primitives are:
* `ValueState<T>`: This keeps a value that can be updated and
retrieved (scoped to key of the input element as 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
-`T value()`.
+for each key that the operation sees). The value can be set using `asyncUpdate(T)` and retrieved using
+`StateFuture<T> asyncValue()`.
-* `ListState<T>`: This keeps a list of elements. You can append elements and retrieve an `Iterable`
-over all currently stored elements. Elements are added using `add(T)` or `addAll(List<T>)`, the Iterable can
-be retrieved using `Iterable<T> get()`. You can also override the existing list with `update(List<T>)`
+* `ListState<T>`: This keeps a list of elements. You can append elements and retrieve an `StateIterator`
+over all currently stored elements. Elements are added using `asyncAdd(T)` or `asyncAddAll(List<T>)`,
+the Iterable can be retrieved using `StateFuture<StateIterator<T>> asyncGet()`.
+You can also override the existing list with `asyncUpdate(List<T>)`
* `ReducingState<T>`: This keeps a single value that represents the aggregation of all values
added to the state. The interface is similar to `ListState` but elements added using
-`add(T)` are reduced to an aggregate using a specified `ReduceFunction`.
+`asyncAdd(T)` are reduced to an aggregate using a specified `ReduceFunction`.
* `AggregatingState<IN, OUT>`: This keeps a single value that represents the aggregation of all values
added to the state. Contrary to `ReducingState`, the aggregate type may be different from the type
of elements that are added to the state. The interface is the same as for `ListState` but elements
-added using `add(IN)` are aggregated using a specified `AggregateFunction`.
+added using `asyncAdd(IN)` are aggregated using a specified `AggregateFunction`.
* `MapState<UK, UV>`: This keeps a list of mappings. You can put key-value pairs into the state and
-retrieve an `Iterable` over all currently stored mappings. Mappings are added using `put(UK, UV)` or
-`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 `entries()`, `keys()` and `values()` respectively.
-You can also use `isEmpty()` to check whether this map contains any key-value mappings.
+retrieve an `StateIterator` over all currently stored mappings. Mappings are added using `asyncPut(UK, UV)` or
+`asyncPutAll(Map<UK, UV>)`. The value associated with a user key can be retrieved using `asyncGet(UK)`.
+The iterable views for mappings, keys and values can be retrieved using `asyncEntries()`,
+`asyncKeys()` and `asyncValues()` respectively. You can also use `asyncIsEmpty()` to check whether
+this map contains any key-value mappings.
-All types of state also have a method `clear()` that clears the state for the currently
+All types of state also have a method `asyncClear()` 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
@@ -145,6 +198,8 @@ that you can reference them), the type of the values that the state holds, and p
a user-specified function, such as a `ReduceFunction`. Depending on what type of state you
want to retrieve, you create either a `ValueStateDescriptor`, a `ListStateDescriptor`,
an `AggregatingStateDescriptor`, a `ReducingStateDescriptor`, or a `MapStateDescriptor`.
+To differentiate between the previous state APIs, you should use the `StateDescriptor`s under the
+`org.apache.flink.api.common.state.v2` package (note the **v2**).
State is accessed using the `RuntimeContext`, so it is only possible in *rich functions*.
Please see [here]({{< ref "docs/dev/datastream/user_defined_functions" >}}#rich-functions) for
@@ -159,7 +214,7 @@ is available in a `RichFunction` has these methods for accessing state:
This is an example `FlatMapFunction` that shows how all of the parts fit together:
-{{< tabs "348fd48c-fa36-4d27-9e53-9bffb74d8a86" >}}
+{{< tabs "348fd48c-fa36-4d27-9e53-9bffb74d8a87" >}}
{{< tab "Java" >}}
```java
public class CountWindowAverage extends RichFlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Long>> {
@@ -173,22 +228,26 @@ public class CountWindowAverage extends RichFlatMapFunction<Tuple2<Long, Long>,
public void flatMap(Tuple2<Long, Long> input, Collector<Tuple2<Long, Long>> out) throws Exception {
// access the state value
- Tuple2<Long, Long> currentSum = sum.value();
-
- // update the count
- currentSum.f0 += 1;
-
- // add the second field of the input value
- currentSum.f1 += input.f1;
-
- // update the state
- sum.update(currentSum);
-
- // if the count reaches 2, emit the average and clear the state
- if (currentSum.f0 >= 2) {
- out.collect(new Tuple2<>(input.f0, currentSum.f1 / currentSum.f0));
- sum.clear();
- }
+ sum.asyncValue().thenApply(currentSum -> {
+ // if it hasn't been used before, it will be null
+ Tuple2<Long, Long> current = currentSum == null ? Tuple2.of(0L, 0L) : currentSum;
+
+ // update the count
+ current.f0 += 1;
+
+ // add the second field of the input value
+ current.f1 += input.f1;
+
+ return current;
+ }).thenAccept(r -> {
+ // if the count reaches 2, emit the average and clear the state
+ if (r.f0 >= 2) {
+ out.collect(Tuple2.of(input.f0, r.f1 / r.f0));
+ sum.asyncClear();
+ } else {
+ sum.asyncUpdate(r);
+ }
+ });
}
@Override
@@ -196,8 +255,7 @@ public class CountWindowAverage extends RichFlatMapFunction<Tuple2<Long, Long>,
ValueStateDescriptor<Tuple2<Long, Long>> descriptor =
new ValueStateDescriptor<>(
"average", // the state name
- TypeInformation.of(new TypeHint<Tuple2<Long, Long>>() {}), // type information
- Tuple2.of(0L, 0L)); // default value of the state, if nothing was set
+ TypeInformation.of(new TypeHint<Tuple2<Long, Long>>() {})); // type information
sum = getRuntimeContext().getState(descriptor);
}
}
@@ -205,117 +263,13 @@ public class CountWindowAverage extends RichFlatMapFunction<Tuple2<Long, Long>,
// this can be used in a streaming program like this (assuming we have a StreamExecutionEnvironment env)
env.fromElements(Tuple2.of(1L, 3L), Tuple2.of(1L, 5L), Tuple2.of(1L, 7L), Tuple2.of(1L, 4L), Tuple2.of(1L, 2L))
.keyBy(value -> value.f0)
+ .enableAsyncState()
.flatMap(new CountWindowAverage())
.print();
// the printed output will be (1,4) and (1,5)
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-class CountWindowAverage extends RichFlatMapFunction[(Long, Long), (Long, Long)] {
-
- private var sum: ValueState[(Long, Long)] = _
-
- override def flatMap(input: (Long, Long), out: Collector[(Long, Long)]): Unit = {
-
- // access the state value
- val tmpCurrentSum = sum.value
-
- // If it hasn't been used before, it will be null
- val currentSum = if (tmpCurrentSum != null) {
- tmpCurrentSum
- } else {
- (0L, 0L)
- }
-
- // update the count
- val newSum = (currentSum._1 + 1, currentSum._2 + input._2)
-
- // update the state
- sum.update(newSum)
-
- // if the count reaches 2, emit the average and clear the state
- if (newSum._1 >= 2) {
- out.collect((input._1, newSum._2 / newSum._1))
- sum.clear()
- }
- }
-
- override def open(parameters: Configuration): Unit = {
- sum = getRuntimeContext.getState(
- new ValueStateDescriptor[(Long, Long)]("average", createTypeInformation[(Long, Long)])
- )
- }
-}
-
-
-object ExampleCountWindowAverage extends App {
- val env = StreamExecutionEnvironment.getExecutionEnvironment
-
- env.fromCollection(List(
- (1L, 3L),
- (1L, 5L),
- (1L, 7L),
- (1L, 4L),
- (1L, 2L)
- )).keyBy(_._1)
- .flatMap(new CountWindowAverage())
- .print()
- // the printed output will be (1,4) and (1,5)
-
- env.execute("ExampleKeyedState")
-}
-```
-{{< /tab >}}
-
-{{< tab "Python" >}}
-```python
-from pyflink.common.typeinfo import Types
-from pyflink.datastream import StreamExecutionEnvironment, FlatMapFunction, RuntimeContext
-from pyflink.datastream.state import ValueStateDescriptor
-
-class CountWindowAverage(FlatMapFunction):
-
- def __init__(self):
- self.sum = None
-
- def open(self, runtime_context: RuntimeContext):
- descriptor = ValueStateDescriptor(
- "average", # the state name
- Types.PICKLED_BYTE_ARRAY() # type information
- )
- self.sum = runtime_context.get_state(descriptor)
-
- def flat_map(self, value):
- # access the state value
- current_sum = self.sum.value()
- if current_sum is None:
- current_sum = (0, 0)
-
- # update the count
- current_sum = (current_sum[0] + 1, current_sum[1] + value[1])
-
- # update the state
- self.sum.update(current_sum)
-
- # if the count reaches 2, emit the average and clear the state
- if current_sum[0] >= 2:
- self.sum.clear()
- yield value[0], int(current_sum[1] / current_sum[0])
-
-
-env = StreamExecutionEnvironment.get_execution_environment()
-env.from_collection([(1, 3), (1, 5), (1, 7), (1, 4), (1, 2)]) \
- .key_by(lambda row: row[0]) \
- .flat_map(CountWindowAverage()) \
- .print()
-
-env.execute()
-
-# the printed output will be (1,4) and (1,5)
-```
-{{< /tab >}}
{{< /tabs >}}
This example implements a poor man's counting window. We key the tuples by the first field
@@ -324,6 +278,45 @@ a `ValueState`. Once the count reaches 2 it will emit the average and clear the
we start over from `0`. Note that this would keep a different state value for each different input
key if we had tuples with different values in the first field.
+### Execution Order
+
+The state access methods are executed asynchronously. This means that the state access methods
+will not block the current thread. With synchronous APIs, the state access methods will be executed in
+the order they are called. However, with asynchronous APIs, the state access methods will be executed
+out of order, especially for those invokes for different incoming elements. For the above example,
+if the `flatMap` function is invoked for two different incoming elements A and B, the state access
+methods for A and B will be executed. Firstly, `asyncGet` is executed for A, then `asyncGet` is
+allowed to execute for B. The finish order of the two `asyncGet` is not guaranteed. Thus the order
+of continuation of the two `StateFuture`s is not guaranteed. Thus invokes of `asyncClear` or
+`asyncUpdate`for A and B are not determined.
+
+Although the state access methods are executed out of order, this not mean that all the user code
+are run in parallel. The user code in the `processElement`, `flatMap` or `thenXXxx` methods
+following the state access methods will be executed in a single thread (the task thread). So there
+is no concurrency issue for the user code.
+
+Typically, you don't need to worry about the execution order of the state access methods, but there
+is still some rules the Flink will ensure:
+* The execution order of user code entry `flatMap` for same-key elements are invoked strictly in
+order of element arrival.
+* The consumers or functions passed to the `thenXXxx` methods are executed in the order they are
+chained. If they are not chained, or there are multiple chains, the order is not guaranteed.
+
+### Best practice of asynchronous APIs
+
+The asynchronous APIs are designed to be more efficient and more powerful than the synchronous APIs.
+There are some best practices that you should follow when using the asynchronous APIs:
+* **Avoid mixing synchronous and asynchronous state access**
+* Use chaining of `thenXXxx` methods to handle the result of the state access and then gives another
+ state access or result. Divide the logic into multiple steps split by `thenXXxx` methods.
+* Avoid accessing mutable members of the user function (`RichFlatMapFunction`). Since the state access
+ methods are executed out of order, the mutable members may be accessed in unpredictable order.
+ Instead, use the result of the state access to pass the data between different steps. The
+ `StateFutureUtils.completedFuture` or `thenApply` method can be used to pass the data. Or use
+ a captured container (`AtomicReference`) which is initialized for each invoke of the `flatMap`
+ to share between lambdas.
+
+
### State Time-To-Live (TTL)
A *time-to-live* (TTL) can be assigned to the keyed state of any type. If a TTL is configured and a
@@ -336,7 +329,7 @@ expire independently.
In order to use state TTL one must first build a `StateTtlConfig` configuration object. The TTL
functionality can then be enabled in any state descriptor by passing the configuration:
-{{< tabs "43221f5b-b56c-42e5-833e-ed416e9d9b4e" >}}
+{{< tabs "43221f0b-b56c-42e5-833e-ed416e5f9b4e" >}}
{{< tab "Java" >}}
```java
import org.apache.flink.api.common.state.StateTtlConfig;
@@ -353,38 +346,6 @@ ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("text
stateDescriptor.enableTimeToLive(ttlConfig);
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-import org.apache.flink.api.common.state.ValueStateDescriptor
-import java.time.Duration
-
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
- .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
- .build
-
-val stateDescriptor = new ValueStateDescriptor[String]("text state", classOf[String])
-stateDescriptor.enableTimeToLive(ttlConfig)
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common.time import Time
-from pyflink.common.typeinfo import Types
-from pyflink.datastream.state import ValueStateDescriptor, StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .set_update_type(StateTtlConfig.UpdateType.OnCreateAndWrite) \
- .set_state_visibility(StateTtlConfig.StateVisibility.NeverReturnExpired) \
- .build()
-
-state_descriptor = ValueStateDescriptor("text state", Types.STRING())
-state_descriptor.enable_time_to_live(ttl_config)
-```
-{{< /tab >}}
{{< /tabs >}}
The configuration has several options to consider:
@@ -420,14 +381,15 @@ Another option `ReturnExpiredIfNotCleanedUp` allows to return the expired state
- The state backends store the timestamp of the last modification along with the user value,
which means that enabling this feature increases consumption of state storage.
Heap state backend stores an additional Java object with a reference to the user state object
-and a primitive long value in memory. The RocksDB state backend adds 8 bytes per stored value, list entry or map entry.
+and a primitive long value in memory. The RocksDB/ForSt state backend adds 8 bytes per stored value,
+list entry or map entry.
- Only TTLs in reference to *processing time* are currently supported.
- Trying to restore state, which was previously configured without TTL, using TTL enabled descriptor or vice versa
will lead to compatibility failure and `StateMigrationException`.
-- The TTL configuration is not part of check- or savepoints but rather a way of how Flink treats it in the currently running job.
+- The TTL configuration is not part of checkpoints or savepoints but rather a way of how Flink treats it in the currently running job.
- It is not recommended to restore checkpoint state with adjusting the ttl from a short value to a long value,
which may cause potential data errors.
@@ -442,7 +404,7 @@ If the serializer does not support null values, it can be wrapped with `Nullable
By default, expired values are explicitly removed on read, such as `ValueState#value`, and periodically garbage collected
in the background if supported by the configured state backend. Background cleanup can be disabled in the `StateTtlConfig`:
-{{< tabs "dfad4bf4-84ec-49a9-8372-c63b59122603" >}}
+{{< tabs "df774bf4-84ec-49a9-8372-c63b59122608" >}}
{{< tab "Java" >}}
```java
import org.apache.flink.api.common.state.StateTtlConfig;
@@ -452,149 +414,25 @@ StateTtlConfig ttlConfig = StateTtlConfig
.build();
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .disableCleanupInBackground
- .build
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common.time import Time
-from pyflink.datastream.state import StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .disable_cleanup_in_background() \
- .build()
-```
-{{< /tab >}}
{{< /tabs >}}
-For more fine-grained control over some special cleanup in background, you can configure it separately as described below.
-Currently, heap state backend relies on incremental cleanup and RocksDB backend uses compaction filter for background cleanup.
-
-##### Cleanup in full snapshot
+{{ <hint info> }}
+Currently the ForSt State Backend only cleanup the state in compaction process. If you are using
+a state backend other than ForSt and want to read about other cleanup strategies, please refer to the
+[State V1 documentation]({{< ref "docs/dev/datastream/fault-tolerance/state#cleanup-of-expired-state" >}})
+about the expired state cleanup.
+{{ </hint > }
-Additionally, you can activate the cleanup at the moment of taking the full state snapshot which
-will reduce its size. The local state is not cleaned up under the current implementation
-but it will not include the removed expired state in case of restoration from the previous snapshot.
-It can be configured in `StateTtlConfig`:
-
-{{< tabs "ad8a4c67-222c-4beb-9547-ca5f8085695c" >}}
-{{< tab "Java" >}}
-```java
-import org.apache.flink.api.common.state.StateTtlConfig;
-import java.time.Duration;
-
-StateTtlConfig ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupFullSnapshot()
- .build();
-```
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-import java.time.Duration
-
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupFullSnapshot
- .build
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common.time import Time
-from pyflink.datastream.state import StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .cleanup_full_snapshot() \
- .build()
-```
-{{< /tab >}}
-{{< /tabs >}}
-
-This option is not applicable for the incremental checkpointing in the RocksDB state backend.
-
-{{< hint info >}}
-For existing jobs, this cleanup strategy can be activated or deactivated anytime in `StateTtlConfig`,
-e.g. after restart from savepoint.
-{{< /hint >}}
-
-##### Incremental cleanup
-
-Another option is to trigger cleanup of some state entries incrementally.
-The trigger can be a callback from each state access or/and each record processing.
-If this cleanup strategy is active for certain state,
-The storage backend keeps a lazy global iterator for this state over all its entries.
-Every time incremental cleanup is triggered, the iterator is advanced.
-The traversed state entries are checked and expired ones are cleaned up.
-
-This feature can be configured in `StateTtlConfig`:
+##### Cleanup during compaction
-{{< tabs "e8c96bb9-6485-4f86-8fdb-5e538e538827" >}}
-{{< tab "Java" >}}
-```java
-import org.apache.flink.api.common.state.StateTtlConfig;
- StateTtlConfig ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupIncrementally(10, true)
- .build();
-```
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupIncrementally(10, true)
- .build
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common.time import Time
-from pyflink.datastream.state import StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .cleanup_incrementally(10, True) \
- .build()
-```
-{{< /tab >}}
-{{< /tabs >}}
-
-This strategy has two parameters. The first one is number of checked state entries per each cleanup triggering.
-It is always triggered per each state access.
-The second parameter defines whether to trigger cleanup additionally per each record processing.
-The default background cleanup for heap backend checks 5 entries without cleanup per record processing.
-
-**Notes:**
-- If no access happens to the state or no records are processed, expired state will persist.
-- Time spent for the incremental cleanup increases record processing latency.
-- At the moment incremental cleanup is implemented only for Heap state backend. Setting it for RocksDB will have no effect.
-- If heap state backend is used with synchronous snapshotting, the global iterator keeps a copy of all keys
-while iterating because of its specific implementation which does not support concurrent modifications.
-Enabling of this feature will increase memory consumption then. Asynchronous snapshotting does not have this problem.
-- For existing jobs, this cleanup strategy can be activated or deactivated anytime in `StateTtlConfig`,
-e.g. after restart from savepoint.
-
-##### Cleanup during RocksDB compaction
-
-If the RocksDB state backend is used, a Flink specific compaction filter will be called for the background cleanup.
-RocksDB periodically runs asynchronous compactions to merge state updates and reduce storage.
+If the ForSt state backend is used, a Flink specific compaction filter will be called for the background cleanup.
+ForSt periodically runs asynchronous compactions to merge state updates and reduce storage.
Flink compaction filter checks expiration timestamp of state entries with TTL
-and excludes expired values.
+and excludes expired values.
This feature can be configured in `StateTtlConfig`:
-{{< tabs "4db505be-2c9c-4ef7-aa01-74763968b7a1" >}}
+{{< tabs "4db505be-2c9c-6ef7-aa01-74763968b7a9" >}}
{{< tab "Java" >}}
```java
import org.apache.flink.api.common.state.StateTtlConfig;
@@ -605,40 +443,18 @@ StateTtlConfig ttlConfig = StateTtlConfig
.build();
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupInRocksdbCompactFilter(1000, Duration.ofHours(1))
- .build
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common import Duration
-from pyflink.common.time import Time
-from pyflink.datastream.state import StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .cleanup_in_rocksdb_compact_filter(1000, Duration.of_hours(1)) \
- .build()
-```
-{{< /tab >}}
{{< /tabs >}}
-RocksDB compaction filter will query current timestamp, used to check expiration, from Flink every time
+ForSt compaction filter will query current timestamp, used to check expiration, from Flink every time
after processing certain number of state entries.
-You can change it and pass a custom value to
-`StateTtlConfig.newBuilder(...).cleanupInRocksdbCompactFilter(long queryTimeAfterNumEntries)` method.
-Updating the timestamp more often can improve cleanup speed
+You can change it and pass a custom value to
+`StateTtlConfig.newBuilder(...).cleanupInRocksdbCompactFilter(long queryTimeAfterNumEntries)` method.
+Updating the timestamp more often can improve cleanup speed
but it decreases compaction performance because it uses JNI call from native code.
-The default background cleanup for RocksDB backend queries the current timestamp each time 1000 entries have been processed.
+The default background cleanup for ForSt backend queries the current timestamp each time 1000 entries have been processed.
-Periodic compaction could speed up expired state entries cleanup, especially for state entries rarely accessed.
-Files older than this value will be picked up for compaction, and re-written to the same level as they were before.
+Periodic compaction could speed up expired state entries cleanup, especially for state entries rarely accessed.
+Files older than this value will be picked up for compaction, and re-written to the same level as they were before.
It makes sure a file goes through compaction filters periodically.
You can change it and pass a custom value to
`StateTtlConfig.newBuilder(...).cleanupInRocksdbCompactFilter(long queryTimeAfterNumEntries, Duration periodicCompactionTime)` method.
@@ -646,42 +462,22 @@ The default value of Periodic compaction seconds is 30 days.
You could set it to 0 to turn off periodic compaction or set a small value to speed up expired state entries cleanup, but it
would trigger more compactions.
-You can activate debug logs from the native code of RocksDB filter
+You can activate debug logs from the native code of ForSt filter
by activating debug level for `FlinkCompactionFilter`:
-`log4j.logger.org.rocksdb.FlinkCompactionFilter=DEBUG`
+`log4j.logger.org.forstdb.FlinkCompactionFilter=DEBUG`
-**Notes:**
-- Calling of TTL filter during compaction slows it down.
-The TTL filter has to parse timestamp of last access and check its expiration
-for every stored state entry per key which is being compacted.
-In case of collection state type (list or map) the check is also invoked per stored element.
+**Notes:**
+- Calling of TTL filter during compaction slows it down.
+ The TTL filter has to parse timestamp of last access and check its expiration
+ for every stored state entry per key which is being compacted.
+ In case of collection state type (list or map) the check is also invoked per stored element.
- If this feature is used with a list state which has elements with non-fixed byte length,
-the native TTL filter has to call additionally a Flink java type serializer of the element over JNI per each state entry
-where at least the first element has expired to determine the offset of the next unexpired element.
-- For existing jobs, this cleanup strategy can be activated or deactivated anytime in `StateTtlConfig`,
-e.g. after restart from savepoint.
+ the native TTL filter has to call additionally a Flink java type serializer of the element over JNI per each state entry
+ where at least the first element has expired to determine the offset of the next unexpired element.
+- For existing jobs, this cleanup strategy can be activated or deactivated anytime in `StateTtlConfig`,
+ e.g. after restart from savepoint.
- Periodic compaction could only work when TTL is enabled.
-
-### State in the Scala DataStream API
-
-In addition to the interface described above, the Scala API has shortcuts for stateful
-`map()` or `flatMap()` functions with a single `ValueState` on `KeyedStream`. The user function
-gets the current value of the `ValueState` in an `Option` and must return an updated value that
-will be used to update the state.
-
-```scala
-val stream: DataStream[(String, Int)] = ...
-
-val counts: DataStream[(String, Int)] = stream
- .keyBy(_._1)
- .mapWithState((in: (String, Int), count: Option[Int]) =>
- count match {
- case Some(c) => ( (in._1, c), Some(c + in._2) )
- case None => ( (in._1, 0), Some(in._2) )
- })
-```
-
## Operator State
*Operator State* (or *non-keyed state*) is state that is bound to one
@@ -697,8 +493,6 @@ In a typical stateful Flink Application you don't need operators state. It is
mostly a special type of state that is used in source/sink implementations and
scenarios where you don't have a key by which state can be partitioned.
-**Notes:** Operator state is still not supported in Python DataStream API.
-
## Broadcast State
*Broadcast State* is a special type of *Operator State*. It was introduced to
@@ -762,7 +556,7 @@ Below is an example of a stateful `SinkFunction` that uses `CheckpointedFunction
to buffer elements before sending them to the outside world. It demonstrates
the basic even-split redistribution list state:
-{{< tabs "5b99313c-1801-486c-a085-ce66882a2e49" >}}
+{{< tabs "5b99663c-1801-486c-a085-ce66882a2k49" >}}
{{< tab "Java" >}}
```java
public class BufferingSink
@@ -814,49 +608,6 @@ public class BufferingSink
}
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-class BufferingSink(threshold: Int = 0)
- extends SinkFunction[(String, Int)]
- with CheckpointedFunction {
-
- @transient
- private var checkpointedState: ListState[(String, Int)] = _
-
- private val bufferedElements = ListBuffer[(String, Int)]()
-
- override def invoke(value: (String, Int), context: Context): Unit = {
- bufferedElements += value
- if (bufferedElements.size >= threshold) {
- for (element <- bufferedElements) {
- // send it to the sink
- }
- bufferedElements.clear()
- }
- }
-
- override def snapshotState(context: FunctionSnapshotContext): Unit = {
- checkpointedState.update(bufferedElements.asJava)
- }
-
- override def initializeState(context: FunctionInitializationContext): Unit = {
- val descriptor = new ListStateDescriptor[(String, Int)](
- "buffered-elements",
- TypeInformation.of(new TypeHint[(String, Int)]() {})
- )
-
- checkpointedState = context.getOperatorStateStore.getListState(descriptor)
-
- if(context.isRestored) {
- for(element <- checkpointedState.get().asScala) {
- bufferedElements += element
- }
- }
- }
-
-}
-```
-{{< /tab >}}
{{< /tabs >}}
The `initializeState` method takes as argument a `FunctionInitializationContext`. This is used to initialize
@@ -879,18 +630,6 @@ ListStateDescriptor<Tuple2<String, Integer>> descriptor =
checkpointedState = context.getOperatorStateStore().getListState(descriptor);
```
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-
-val descriptor = new ListStateDescriptor[(String, Long)](
- "buffered-elements",
- TypeInformation.of(new TypeHint[(String, Long)]() {})
-)
-
-checkpointedState = context.getOperatorStateStore.getListState(descriptor)
-
-```
{{< /tab >}}
{{< /tabs >}}
The naming convention of the state access methods contain its redistribution
@@ -909,110 +648,16 @@ of all objects included by the previous checkpoint, and is then filled with the
As a side note, the keyed state can also be initialized in the `initializeState()` method. This can be done
using the provided `FunctionInitializationContext`.
-### 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.
-
-{{< tabs "aa821e89-7cc6-4c1e-be5b-90bfa0df6036" >}}
-{{< tab "Java" >}}
-```java
-public static class CounterSource
- extends RichParallelSourceFunction<Long>
- implements CheckpointedFunction {
-
- /** current offset for exactly once semantics */
- private Long offset = 0L;
-
- /** flag for job cancellation */
- private volatile boolean isRunning = true;
-
- /** Our state object. */
- private ListState<Long> state;
-
- @Override
- public void run(SourceContext<Long> ctx) {
- final Object lock = ctx.getCheckpointLock();
-
- while (isRunning) {
- // output and state update are atomic
- synchronized (lock) {
- ctx.collect(offset);
- offset += 1;
- }
- }
- }
-
- @Override
- public void cancel() {
- isRunning = false;
- }
-
- @Override
- public void initializeState(FunctionInitializationContext context) throws Exception {
- state = context.getOperatorStateStore().getListState(new ListStateDescriptor<>(
- "state",
- LongSerializer.INSTANCE));
-
- // restore any state that we might already have to our fields, initialize state
- // is also called in case of restore.
- for (Long l : state.get()) {
- offset = l;
- }
- }
-
- @Override
- public void snapshotState(FunctionSnapshotContext context) throws Exception {
- state.update(Collections.singletonList(offset));
- }
-}
-```
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-class CounterSource
- extends RichParallelSourceFunction[Long]
- with CheckpointedFunction {
-
- @volatile
- private var isRunning = true
-
- private var offset = 0L
- private var state: ListState[Long] = _
-
- override def run(ctx: SourceFunction.SourceContext[Long]): Unit = {
- val lock = ctx.getCheckpointLock
-
- while (isRunning) {
- // output and state update are atomic
- lock.synchronized({
- ctx.collect(offset)
-
- offset += 1
- })
- }
- }
+{{< top >}}
- override def cancel(): Unit = isRunning = false
-
- override def initializeState(context: FunctionInitializationContext): Unit = {
- state = context.getOperatorStateStore.getListState(
- new ListStateDescriptor[Long]("state", classOf[Long]))
+## Migrate from the Old State API
- for (l <- state.get().asScala) {
- offset = l
- }
- }
+It is very easy to migrate from the old state API to the new one. Please take the following steps:
- override def snapshotState(context: FunctionSnapshotContext): Unit = {
- state.update(java.util.Collections.singletonList(offset))
- }
-}
-```
-{{< /tab >}}
-{{< /tabs >}}
-
-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 `org.apache.flink.api.common.state.CheckpointListener` interface.
-
-{{< top >}}
+1. Invoke `enableAsyncState()` on the `KeyedStream` to enable the new state API.
+2. Replace the `StateDescriptor`s with the new ones under `v2` package. Also, replace the old state
+handles with the new ones under `v2` package.
+3. Rewrite the old state access methods with the new asynchronous ones.
+4. It is recommended to use ForSt State Backend for the new state API, which could perform
+async state access. Other state backends only support synchronous execution of state access,
+although it can be used with the new state API.
diff --git a/docs/content/docs/dev/datastream-v2/context_and_state_processing.md b/docs/content/docs/dev/datastream-v2/context_and_state_processing.md
index cd17fe26d86..4e95270fac0 100644
--- a/docs/content/docs/dev/datastream-v2/context_and_state_processing.md
+++ b/docs/content/docs/dev/datastream-v2/context_and_state_processing.md
@@ -281,4 +281,11 @@ The specific rules are shown in the following table:
flink will check the legality of state declaration in advance. If an illegal state is declared in `usesStates` method, exception will be thrown at job compile time.
+### State Access Methods
+
+Note that the datastream v2 is using the state v2 APIs. For more detail about the state access
+methods, please refer to the
+[Using Keyed State V2]({{< ref "docs/dev/datastream/fault-tolerance/state_v2#using-keyed-state-v2" >}}).
+
+
{{< top >}}
diff --git a/docs/content/docs/dev/datastream/fault-tolerance/state.md b/docs/content/docs/dev/datastream/fault-tolerance/state.md
index 2486212055e..86714d0b7cb 100644
--- a/docs/content/docs/dev/datastream/fault-tolerance/state.md
+++ b/docs/content/docs/dev/datastream/fault-tolerance/state.md
@@ -1,6 +1,6 @@
---
title: "Working with State"
-weight: 2
+weight: 1
type: docs
aliases:
- /dev/stream/state/state.html
diff --git a/docs/content/docs/dev/datastream/fault-tolerance/state.md b/docs/content/docs/dev/datastream/fault-tolerance/state_v2.md
similarity index 51%
copy from docs/content/docs/dev/datastream/fault-tolerance/state.md
copy to docs/content/docs/dev/datastream/fault-tolerance/state_v2.md
index 2486212055e..d1abd47ae49 100644
--- a/docs/content/docs/dev/datastream/fault-tolerance/state.md
+++ b/docs/content/docs/dev/datastream/fault-tolerance/state_v2.md
@@ -1,10 +1,10 @@
---
-title: "Working with State"
+title: "Working with State V2"
weight: 2
type: docs
aliases:
- - /dev/stream/state/state.html
- - /apis/streaming/state.html
+ - /dev/stream/state/state_v2.html
+ - /apis/streaming/state_v2.html
---
<!--
Licensed to the Apache Software Foundation (ASF) under one
@@ -25,20 +25,26 @@ specific language governing permissions and limitations
under the License.
-->
-# Working with State
+# Working with State V2 (New APIs)
-In this section you will learn about the APIs that Flink provides for writing
+In this section you will learn about the new APIs that Flink provides for writing
stateful programs. Please take a look at [Stateful Stream
Processing]({{< ref "docs/concepts/stateful-stream-processing" >}})
to learn about the concepts behind stateful stream processing.
+The new state API is designed to be more flexible than the previous API. User can perform
+asynchronous state operations, thus making it more powerful and more efficient.
+The asynchronous state access is essential for the state backend to be able to handle
+large state sizes and to be able to spill to remote file systems when necessary.
+
## Keyed DataStream
If you want to use keyed state, you first need to specify a key on a
`DataStream` that should be used to partition the state (and also the records
in the stream themselves). You can specify a key using `keyBy(KeySelector)`
-in Java/Scala API or `key_by(KeySelector)` in Python API on a `DataStream`.
-This will yield a `KeyedStream`, which then allows operations that use keyed state.
+in Java API on a `DataStream`. This will yield a `KeyedStream`, which then allows operations
+that use keyed state. You should perform `enableAsyncState()` on the `KeyedStream` to enable
+asynchronous state operations.
A key selector function takes a single record as input and returns the key for
that record. The key can be of any type and **must** be derived from
@@ -52,85 +58,132 @@ grouping operator.
The following example shows a key selector function that simply returns the
field of an object:
-{{< tabs "54e3bde7-659a-4683-81fa-112a2c81036b" >}}
+{{< tabs "54e3bde7-659a-4683-81fa-312a2c81036b" >}}
{{< tab "Java" >}}
```java
// some ordinary POJO
-public class WC {
+public class WordCount {
public String word;
public int count;
public String getWord() { return word; }
}
-DataStream<WC> words = // [...]
-KeyedStream<WC> keyed = words
- .keyBy(WC::getWord);
-```
-
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-// some ordinary case class
-case class WC(word: String, count: Int)
-val words: DataStream[WC] = // [...]
-val keyed = words.keyBy( _.word )
-```
-{{< /tab >}}
-
-{{< tab "Python" >}}
-```python
-words = # type: DataStream[Row]
-keyed = words.key_by(lambda row: row[0])
+DataStream<WordCount> words = // [...]
+KeyedStream<WordCount> keyed = words
+ .keyBy(WordCount::getWord).enableAsyncState();
```
-{{< /tab >}}
{{< /tabs >}}
-#### Tuple Keys and Expression Keys
-
-Flink also has two alternative ways of defining keys: tuple keys and expression
-keys in the Java/Scala API(still not supported in the Python API). With this you can
-specify keys using tuple field indices or expressions
-for selecting fields of objects. We don't recommend using these today but you
-can refer to the Javadoc of DataStream to learn about them. Using a KeySelector
-function is strictly superior: with Java lambdas they are easy to use and they
-have potentially less overhead at runtime.
-
{{< top >}}
-## Using Keyed State
+## Using Keyed State V2
-The keyed state interfaces 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 `stream.keyBy(…)` in Java/Scala API or `stream.key_by(…)` in Python API.
+Unlike the previous state API, the new state API is designed for asynchronous state access.
+Each type of state gives two versions of the API: synchronous and asynchronous. The synchronous
+API is a blocking API that waits for the state access to complete. The asynchronous API is
+non-blocking and returns a `StateFuture` that will be completed when the state access
+is done. After that a callback or following logic will be invoked (if any).
+The asynchronous API is more efficient and should be used whenever possible.
+It is highly **not** recommended to mixed synchronous and asynchronous state access in the same
+user function.
-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:
+The keyed state interfaces provide 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 `stream.keyBy(…)` in Java. And then most importantly,
+the keyed stream needs to be enabled for asynchronous state access by calling `enableAsyncState()`.
+The new API set are only available on `KeyedStream` with `enableAsyncState()` invoked.
+
+Now, we will look at the different types of state available, and then we will see
+how they can be used in a program. Since the synchronous APIs are identical with the original APIs,
+We only focus on the asynchronous ones here.
+
+### The Return Values
+
+First of all, we should get familiar with the return value of those asynchronous state access methods.
+
+`StateFuture<T>` is a future that will be completed with the result of the state access.
+The return bype is T. It provides multiple methods to handle the result, listed as:
+* `StateFuture<Void> thenAccept(Consumer<T>)`: This method takes a `Consumer` that will be called with the result
+ when the state access is done. It returns a `StateFuture<Void>`, which will be finished when the
+ `Consumer` is done.
+* `StateFuture<R> thenApply(Function<T, R>)`: This method takes a `Function` that will be called with the result
+ when the state access is done. The return value of the function will be the result of the following
+ `StateFuture`, which will be finished when the `Function` is done.
+* `StateFuture<R> thenCompose(Function<T, StateFuture<R>>)`: This method takes a `Function` that will
+ be called with the result when the state access is done. The return value of the function should be
+ a `StateFuture<R>`, which is exposed to the invoker of `thenCompose` as a return value.
+ The `StateFuture<R>` will be finished when the inner `StateFuture<R>` of `Function` is finished.
+* `StateFuture<R> thenCombine(StateFuture<U>, BiFunction<T, U, R>)`: This method takes another `StateFuture` and a
+ `BiFunction` that will be called with the results of both `StateFuture`s when they are done. The return
+ value of the `BiFunction` will be the result of the following `StateFuture`, which will be finished when
+ the `BiFunction` is done.
+
+Those methods are similar to the corresponding ones of the `CompletableFuture`. Besides these methods,
+keep in mind that `StateFuture` does not provide a `get()` method to block the current thread until the
+state access is done. This is because blocking the current thread may cause recursive blocking. The
+`StateFuture<T>` also provides conditional version of `thenAccept`, `thenApply`, `thenCompose` and `thenCombine`,
+which is for the case that the state access is done and the following logic will be split into two branches
+based on the result of the state access. The conditional version of those methods are `thenConditionallyAccept`,
+`thenConditionallyApply`, `thenConditionallyCompose` and `thenConditionallyCombine`.
+
+`StateIterator<T>` is an iterator that can be used to iterate over the elements of a state. It provides
+the following methods:
+* `boolean isEmpty()` : A synchronous method returns a `true` if the iterator has no elements, and `false` otherwise.
+* `StateFuture<Void> onNext(Consumer<T>)` : This method takes a `Consumer` that will be called with the next element
+ when the state access is done. It returns a `StateFuture<Void>`, which will be finished when the `Consumer` is done.
+ Also, a function version of `onNext` is provided, which is `StateFuture<Collection<R>> onNext(Function<T, R>)`. This method
+ takes a `Function` that will be called with the next element when the state access is done. The return value of the function
+ will be collected and returned as a collection of the following `StateFuture`, which will be
+ finished when the `Function` is done.
+
+We also provide a `StateFutureUtils` class that contains some utility methods to handle `StateFuture`s.
+These methods are:
+* `StateFuture<T> completedFuture(T)`: This method returns a completed `StateFuture` with the given value. This is
+useful when you want to return a constant value in a `thenCompose` method for further processing.
+* `StateFuture<Void> completedVoidFuture()`: This method returns a completed `StateFuture` with `null` value.
+A void value version of `completedFuture`.
+* `StateFuture<Collection<T>> combineAll(Collection<StateFuture<T>>)` : This method takes a collection of `StateFuture`s
+and returns a `StateFuture` that will be completed when all the input `StateFuture`s are completed. The result of the
+returned `StateFuture` is a collection of the results of the input `StateFuture`s. This is useful when you want to
+combine the results of multiple `StateFuture`s.
+* `StateFuture<Iterable<T>> toIterable(StateFuture<StateIterator<T>>)` : This method takes a `StateFuture` of `StateIterator`
+and returns a `StateFuture` of `Iterable`. The result of the returned `StateFuture` is an `Iterable` that contains all
+the elements of the `StateIterator`. This is useful when you want to convert a `StateIterator` to an `Iterable`.
+There is no good reason to do so, since this may disable the capability of lazy loading. Only useful when the further
+calculation depends on the whole data from the iterator.
+
+
+### State Primitives
+
+The available state primitives are:
* `ValueState<T>`: This keeps a value that can be updated and
retrieved (scoped to key of the input element as 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
-`T value()`.
+for each key that the operation sees). The value can be set using `asyncUpdate(T)` and retrieved using
+`StateFuture<T> asyncValue()`.
-* `ListState<T>`: This keeps a list of elements. You can append elements and retrieve an `Iterable`
-over all currently stored elements. Elements are added using `add(T)` or `addAll(List<T>)`, the Iterable can
-be retrieved using `Iterable<T> get()`. You can also override the existing list with `update(List<T>)`
+* `ListState<T>`: This keeps a list of elements. You can append elements and retrieve an `StateIterator`
+over all currently stored elements. Elements are added using `asyncAdd(T)` or `asyncAddAll(List<T>)`,
+the Iterable can be retrieved using `StateFuture<StateIterator<T>> asyncGet()`.
+You can also override the existing list with `asyncUpdate(List<T>)`
* `ReducingState<T>`: This keeps a single value that represents the aggregation of all values
added to the state. The interface is similar to `ListState` but elements added using
-`add(T)` are reduced to an aggregate using a specified `ReduceFunction`.
+`asyncAdd(T)` are reduced to an aggregate using a specified `ReduceFunction`.
* `AggregatingState<IN, OUT>`: This keeps a single value that represents the aggregation of all values
added to the state. Contrary to `ReducingState`, the aggregate type may be different from the type
of elements that are added to the state. The interface is the same as for `ListState` but elements
-added using `add(IN)` are aggregated using a specified `AggregateFunction`.
+added using `asyncAdd(IN)` are aggregated using a specified `AggregateFunction`.
* `MapState<UK, UV>`: This keeps a list of mappings. You can put key-value pairs into the state and
-retrieve an `Iterable` over all currently stored mappings. Mappings are added using `put(UK, UV)` or
-`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 `entries()`, `keys()` and `values()` respectively.
-You can also use `isEmpty()` to check whether this map contains any key-value mappings.
+retrieve an `StateIterator` over all currently stored mappings. Mappings are added using `asyncPut(UK, UV)` or
+`asyncPutAll(Map<UK, UV>)`. The value associated with a user key can be retrieved using `asyncGet(UK)`.
+The iterable views for mappings, keys and values can be retrieved using `asyncEntries()`,
+`asyncKeys()` and `asyncValues()` respectively. You can also use `asyncIsEmpty()` to check whether
+this map contains any key-value mappings.
-All types of state also have a method `clear()` that clears the state for the currently
+All types of state also have a method `asyncClear()` 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
@@ -145,6 +198,8 @@ that you can reference them), the type of the values that the state holds, and p
a user-specified function, such as a `ReduceFunction`. Depending on what type of state you
want to retrieve, you create either a `ValueStateDescriptor`, a `ListStateDescriptor`,
an `AggregatingStateDescriptor`, a `ReducingStateDescriptor`, or a `MapStateDescriptor`.
+To differentiate between the previous state APIs, you should use the `StateDescriptor`s under the
+`org.apache.flink.api.common.state.v2` package (note the **v2**).
State is accessed using the `RuntimeContext`, so it is only possible in *rich functions*.
Please see [here]({{< ref "docs/dev/datastream/user_defined_functions" >}}#rich-functions) for
@@ -159,7 +214,7 @@ is available in a `RichFunction` has these methods for accessing state:
This is an example `FlatMapFunction` that shows how all of the parts fit together:
-{{< tabs "348fd48c-fa36-4d27-9e53-9bffb74d8a86" >}}
+{{< tabs "348fd48c-fa36-4d27-9e53-9bffb74d8a87" >}}
{{< tab "Java" >}}
```java
public class CountWindowAverage extends RichFlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Long>> {
@@ -173,22 +228,26 @@ public class CountWindowAverage extends RichFlatMapFunction<Tuple2<Long, Long>,
public void flatMap(Tuple2<Long, Long> input, Collector<Tuple2<Long, Long>> out) throws Exception {
// access the state value
- Tuple2<Long, Long> currentSum = sum.value();
-
- // update the count
- currentSum.f0 += 1;
-
- // add the second field of the input value
- currentSum.f1 += input.f1;
-
- // update the state
- sum.update(currentSum);
-
- // if the count reaches 2, emit the average and clear the state
- if (currentSum.f0 >= 2) {
- out.collect(new Tuple2<>(input.f0, currentSum.f1 / currentSum.f0));
- sum.clear();
- }
+ sum.asyncValue().thenApply(currentSum -> {
+ // if it hasn't been used before, it will be null
+ Tuple2<Long, Long> current = currentSum == null ? Tuple2.of(0L, 0L) : currentSum;
+
+ // update the count
+ current.f0 += 1;
+
+ // add the second field of the input value
+ current.f1 += input.f1;
+
+ return current;
+ }).thenAccept(r -> {
+ // if the count reaches 2, emit the average and clear the state
+ if (r.f0 >= 2) {
+ out.collect(Tuple2.of(input.f0, r.f1 / r.f0));
+ sum.asyncClear();
+ } else {
+ sum.asyncUpdate(r);
+ }
+ });
}
@Override
@@ -196,8 +255,7 @@ public class CountWindowAverage extends RichFlatMapFunction<Tuple2<Long, Long>,
ValueStateDescriptor<Tuple2<Long, Long>> descriptor =
new ValueStateDescriptor<>(
"average", // the state name
- TypeInformation.of(new TypeHint<Tuple2<Long, Long>>() {}), // type information
- Tuple2.of(0L, 0L)); // default value of the state, if nothing was set
+ TypeInformation.of(new TypeHint<Tuple2<Long, Long>>() {})); // type information
sum = getRuntimeContext().getState(descriptor);
}
}
@@ -205,117 +263,13 @@ public class CountWindowAverage extends RichFlatMapFunction<Tuple2<Long, Long>,
// this can be used in a streaming program like this (assuming we have a StreamExecutionEnvironment env)
env.fromElements(Tuple2.of(1L, 3L), Tuple2.of(1L, 5L), Tuple2.of(1L, 7L), Tuple2.of(1L, 4L), Tuple2.of(1L, 2L))
.keyBy(value -> value.f0)
+ .enableAsyncState()
.flatMap(new CountWindowAverage())
.print();
// the printed output will be (1,4) and (1,5)
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-class CountWindowAverage extends RichFlatMapFunction[(Long, Long), (Long, Long)] {
-
- private var sum: ValueState[(Long, Long)] = _
-
- override def flatMap(input: (Long, Long), out: Collector[(Long, Long)]): Unit = {
-
- // access the state value
- val tmpCurrentSum = sum.value
-
- // If it hasn't been used before, it will be null
- val currentSum = if (tmpCurrentSum != null) {
- tmpCurrentSum
- } else {
- (0L, 0L)
- }
-
- // update the count
- val newSum = (currentSum._1 + 1, currentSum._2 + input._2)
-
- // update the state
- sum.update(newSum)
-
- // if the count reaches 2, emit the average and clear the state
- if (newSum._1 >= 2) {
- out.collect((input._1, newSum._2 / newSum._1))
- sum.clear()
- }
- }
-
- override def open(parameters: Configuration): Unit = {
- sum = getRuntimeContext.getState(
- new ValueStateDescriptor[(Long, Long)]("average", createTypeInformation[(Long, Long)])
- )
- }
-}
-
-
-object ExampleCountWindowAverage extends App {
- val env = StreamExecutionEnvironment.getExecutionEnvironment
-
- env.fromCollection(List(
- (1L, 3L),
- (1L, 5L),
- (1L, 7L),
- (1L, 4L),
- (1L, 2L)
- )).keyBy(_._1)
- .flatMap(new CountWindowAverage())
- .print()
- // the printed output will be (1,4) and (1,5)
-
- env.execute("ExampleKeyedState")
-}
-```
-{{< /tab >}}
-
-{{< tab "Python" >}}
-```python
-from pyflink.common.typeinfo import Types
-from pyflink.datastream import StreamExecutionEnvironment, FlatMapFunction, RuntimeContext
-from pyflink.datastream.state import ValueStateDescriptor
-
-class CountWindowAverage(FlatMapFunction):
-
- def __init__(self):
- self.sum = None
-
- def open(self, runtime_context: RuntimeContext):
- descriptor = ValueStateDescriptor(
- "average", # the state name
- Types.PICKLED_BYTE_ARRAY() # type information
- )
- self.sum = runtime_context.get_state(descriptor)
-
- def flat_map(self, value):
- # access the state value
- current_sum = self.sum.value()
- if current_sum is None:
- current_sum = (0, 0)
-
- # update the count
- current_sum = (current_sum[0] + 1, current_sum[1] + value[1])
-
- # update the state
- self.sum.update(current_sum)
-
- # if the count reaches 2, emit the average and clear the state
- if current_sum[0] >= 2:
- self.sum.clear()
- yield value[0], int(current_sum[1] / current_sum[0])
-
-
-env = StreamExecutionEnvironment.get_execution_environment()
-env.from_collection([(1, 3), (1, 5), (1, 7), (1, 4), (1, 2)]) \
- .key_by(lambda row: row[0]) \
- .flat_map(CountWindowAverage()) \
- .print()
-
-env.execute()
-
-# the printed output will be (1,4) and (1,5)
-```
-{{< /tab >}}
{{< /tabs >}}
This example implements a poor man's counting window. We key the tuples by the first field
@@ -324,6 +278,45 @@ a `ValueState`. Once the count reaches 2 it will emit the average and clear the
we start over from `0`. Note that this would keep a different state value for each different input
key if we had tuples with different values in the first field.
+### Execution Order
+
+The state access methods are executed asynchronously. This means that the state access methods
+will not block the current thread. With synchronous APIs, the state access methods will be executed in
+the order they are called. However, with asynchronous APIs, the state access methods will be executed
+out of order, especially for those invokes for different incoming elements. For the above example,
+if the `flatMap` function is invoked for two different incoming elements A and B, the state access
+methods for A and B will be executed. Firstly, `asyncGet` is executed for A, then `asyncGet` is
+allowed to execute for B. The finish order of the two `asyncGet` is not guaranteed. Thus the order
+of continuation of the two `StateFuture`s is not guaranteed. Thus invokes of `asyncClear` or
+`asyncUpdate`for A and B are not determined.
+
+Although the state access methods are executed out of order, this not mean that all the user code
+are run in parallel. The user code in the `processElement`, `flatMap` or `thenXXxx` methods
+following the state access methods will be executed in a single thread (the task thread). So there
+is no concurrency issue for the user code.
+
+Typically, you don't need to worry about the execution order of the state access methods, but there
+is still some rules the Flink will ensure:
+* The execution order of user code entry `flatMap` for same-key elements are invoked strictly in
+order of element arrival.
+* The consumers or functions passed to the `thenXXxx` methods are executed in the order they are
+chained. If they are not chained, or there are multiple chains, the order is not guaranteed.
+
+### Best practice of asynchronous APIs
+
+The asynchronous APIs are designed to be more efficient and more powerful than the synchronous APIs.
+There are some best practices that you should follow when using the asynchronous APIs:
+* **Avoid mixing synchronous and asynchronous state access**
+* Use chaining of `thenXXxx` methods to handle the result of the state access and then gives another
+ state access or result. Divide the logic into multiple steps split by `thenXXxx` methods.
+* Avoid accessing mutable members of the user function (`RichFlatMapFunction`). Since the state access
+ methods are executed out of order, the mutable members may be accessed in unpredictable order.
+ Instead, use the result of the state access to pass the data between different steps. The
+ `StateFutureUtils.completedFuture` or `thenApply` method can be used to pass the data. Or use
+ a captured container (`AtomicReference`) which is initialized for each invoke of the `flatMap`
+ to share between lambdas.
+
+
### State Time-To-Live (TTL)
A *time-to-live* (TTL) can be assigned to the keyed state of any type. If a TTL is configured and a
@@ -336,7 +329,7 @@ expire independently.
In order to use state TTL one must first build a `StateTtlConfig` configuration object. The TTL
functionality can then be enabled in any state descriptor by passing the configuration:
-{{< tabs "43221f5b-b56c-42e5-833e-ed416e9d9b4e" >}}
+{{< tabs "43221f0b-b56c-42e5-833e-ed416e5f9b4e" >}}
{{< tab "Java" >}}
```java
import org.apache.flink.api.common.state.StateTtlConfig;
@@ -353,38 +346,6 @@ ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("text
stateDescriptor.enableTimeToLive(ttlConfig);
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-import org.apache.flink.api.common.state.ValueStateDescriptor
-import java.time.Duration
-
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
- .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
- .build
-
-val stateDescriptor = new ValueStateDescriptor[String]("text state", classOf[String])
-stateDescriptor.enableTimeToLive(ttlConfig)
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common.time import Time
-from pyflink.common.typeinfo import Types
-from pyflink.datastream.state import ValueStateDescriptor, StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .set_update_type(StateTtlConfig.UpdateType.OnCreateAndWrite) \
- .set_state_visibility(StateTtlConfig.StateVisibility.NeverReturnExpired) \
- .build()
-
-state_descriptor = ValueStateDescriptor("text state", Types.STRING())
-state_descriptor.enable_time_to_live(ttl_config)
-```
-{{< /tab >}}
{{< /tabs >}}
The configuration has several options to consider:
@@ -420,14 +381,15 @@ Another option `ReturnExpiredIfNotCleanedUp` allows to return the expired state
- The state backends store the timestamp of the last modification along with the user value,
which means that enabling this feature increases consumption of state storage.
Heap state backend stores an additional Java object with a reference to the user state object
-and a primitive long value in memory. The RocksDB state backend adds 8 bytes per stored value, list entry or map entry.
+and a primitive long value in memory. The RocksDB/ForSt state backend adds 8 bytes per stored value,
+list entry or map entry.
- Only TTLs in reference to *processing time* are currently supported.
- Trying to restore state, which was previously configured without TTL, using TTL enabled descriptor or vice versa
will lead to compatibility failure and `StateMigrationException`.
-- The TTL configuration is not part of check- or savepoints but rather a way of how Flink treats it in the currently running job.
+- The TTL configuration is not part of checkpoints or savepoints but rather a way of how Flink treats it in the currently running job.
- It is not recommended to restore checkpoint state with adjusting the ttl from a short value to a long value,
which may cause potential data errors.
@@ -442,7 +404,7 @@ If the serializer does not support null values, it can be wrapped with `Nullable
By default, expired values are explicitly removed on read, such as `ValueState#value`, and periodically garbage collected
in the background if supported by the configured state backend. Background cleanup can be disabled in the `StateTtlConfig`:
-{{< tabs "dfad4bf4-84ec-49a9-8372-c63b59122603" >}}
+{{< tabs "df774bf4-84ec-49a9-8372-c63b59122608" >}}
{{< tab "Java" >}}
```java
import org.apache.flink.api.common.state.StateTtlConfig;
@@ -452,149 +414,25 @@ StateTtlConfig ttlConfig = StateTtlConfig
.build();
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .disableCleanupInBackground
- .build
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common.time import Time
-from pyflink.datastream.state import StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .disable_cleanup_in_background() \
- .build()
-```
-{{< /tab >}}
{{< /tabs >}}
-For more fine-grained control over some special cleanup in background, you can configure it separately as described below.
-Currently, heap state backend relies on incremental cleanup and RocksDB backend uses compaction filter for background cleanup.
-
-##### Cleanup in full snapshot
-
-Additionally, you can activate the cleanup at the moment of taking the full state snapshot which
-will reduce its size. The local state is not cleaned up under the current implementation
-but it will not include the removed expired state in case of restoration from the previous snapshot.
-It can be configured in `StateTtlConfig`:
-
-{{< tabs "ad8a4c67-222c-4beb-9547-ca5f8085695c" >}}
-{{< tab "Java" >}}
-```java
-import org.apache.flink.api.common.state.StateTtlConfig;
-import java.time.Duration;
-
-StateTtlConfig ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupFullSnapshot()
- .build();
-```
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-import java.time.Duration
-
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupFullSnapshot
- .build
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common.time import Time
-from pyflink.datastream.state import StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .cleanup_full_snapshot() \
- .build()
-```
-{{< /tab >}}
-{{< /tabs >}}
-
-This option is not applicable for the incremental checkpointing in the RocksDB state backend.
-
-{{< hint info >}}
-For existing jobs, this cleanup strategy can be activated or deactivated anytime in `StateTtlConfig`,
-e.g. after restart from savepoint.
-{{< /hint >}}
-
-##### Incremental cleanup
-
-Another option is to trigger cleanup of some state entries incrementally.
-The trigger can be a callback from each state access or/and each record processing.
-If this cleanup strategy is active for certain state,
-The storage backend keeps a lazy global iterator for this state over all its entries.
-Every time incremental cleanup is triggered, the iterator is advanced.
-The traversed state entries are checked and expired ones are cleaned up.
+{{ <hint info> }}
+Currently the ForSt State Backend only cleanup the state in compaction process. If you are using
+a state backend other than ForSt and want to read about other cleanup strategies, please refer to the
+[State V1 documentation]({{< ref "docs/dev/datastream/fault-tolerance/state#cleanup-of-expired-state" >}})
+about the expired state cleanup.
+{{ </hint > }
-This feature can be configured in `StateTtlConfig`:
+##### Cleanup during compaction
-{{< tabs "e8c96bb9-6485-4f86-8fdb-5e538e538827" >}}
-{{< tab "Java" >}}
-```java
-import org.apache.flink.api.common.state.StateTtlConfig;
- StateTtlConfig ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupIncrementally(10, true)
- .build();
-```
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupIncrementally(10, true)
- .build
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common.time import Time
-from pyflink.datastream.state import StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .cleanup_incrementally(10, True) \
- .build()
-```
-{{< /tab >}}
-{{< /tabs >}}
-
-This strategy has two parameters. The first one is number of checked state entries per each cleanup triggering.
-It is always triggered per each state access.
-The second parameter defines whether to trigger cleanup additionally per each record processing.
-The default background cleanup for heap backend checks 5 entries without cleanup per record processing.
-
-**Notes:**
-- If no access happens to the state or no records are processed, expired state will persist.
-- Time spent for the incremental cleanup increases record processing latency.
-- At the moment incremental cleanup is implemented only for Heap state backend. Setting it for RocksDB will have no effect.
-- If heap state backend is used with synchronous snapshotting, the global iterator keeps a copy of all keys
-while iterating because of its specific implementation which does not support concurrent modifications.
-Enabling of this feature will increase memory consumption then. Asynchronous snapshotting does not have this problem.
-- For existing jobs, this cleanup strategy can be activated or deactivated anytime in `StateTtlConfig`,
-e.g. after restart from savepoint.
-
-##### Cleanup during RocksDB compaction
-
-If the RocksDB state backend is used, a Flink specific compaction filter will be called for the background cleanup.
-RocksDB periodically runs asynchronous compactions to merge state updates and reduce storage.
+If the ForSt state backend is used, a Flink specific compaction filter will be called for the background cleanup.
+ForSt periodically runs asynchronous compactions to merge state updates and reduce storage.
Flink compaction filter checks expiration timestamp of state entries with TTL
-and excludes expired values.
+and excludes expired values.
This feature can be configured in `StateTtlConfig`:
-{{< tabs "4db505be-2c9c-4ef7-aa01-74763968b7a1" >}}
+{{< tabs "4db505be-2c9c-6ef7-aa01-74763968b7a9" >}}
{{< tab "Java" >}}
```java
import org.apache.flink.api.common.state.StateTtlConfig;
@@ -605,40 +443,18 @@ StateTtlConfig ttlConfig = StateTtlConfig
.build();
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-import org.apache.flink.api.common.state.StateTtlConfig
-
-val ttlConfig = StateTtlConfig
- .newBuilder(Duration.ofSeconds(1))
- .cleanupInRocksdbCompactFilter(1000, Duration.ofHours(1))
- .build
-```
-{{< /tab >}}
-{{< tab "Python" >}}
-```python
-from pyflink.common import Duration
-from pyflink.common.time import Time
-from pyflink.datastream.state import StateTtlConfig
-
-ttl_config = StateTtlConfig \
- .new_builder(Duration.ofSeconds(1)) \
- .cleanup_in_rocksdb_compact_filter(1000, Duration.of_hours(1)) \
- .build()
-```
-{{< /tab >}}
{{< /tabs >}}
-RocksDB compaction filter will query current timestamp, used to check expiration, from Flink every time
+ForSt compaction filter will query current timestamp, used to check expiration, from Flink every time
after processing certain number of state entries.
-You can change it and pass a custom value to
-`StateTtlConfig.newBuilder(...).cleanupInRocksdbCompactFilter(long queryTimeAfterNumEntries)` method.
-Updating the timestamp more often can improve cleanup speed
+You can change it and pass a custom value to
+`StateTtlConfig.newBuilder(...).cleanupInRocksdbCompactFilter(long queryTimeAfterNumEntries)` method.
+Updating the timestamp more often can improve cleanup speed
but it decreases compaction performance because it uses JNI call from native code.
-The default background cleanup for RocksDB backend queries the current timestamp each time 1000 entries have been processed.
+The default background cleanup for ForSt backend queries the current timestamp each time 1000 entries have been processed.
-Periodic compaction could speed up expired state entries cleanup, especially for state entries rarely accessed.
-Files older than this value will be picked up for compaction, and re-written to the same level as they were before.
+Periodic compaction could speed up expired state entries cleanup, especially for state entries rarely accessed.
+Files older than this value will be picked up for compaction, and re-written to the same level as they were before.
It makes sure a file goes through compaction filters periodically.
You can change it and pass a custom value to
`StateTtlConfig.newBuilder(...).cleanupInRocksdbCompactFilter(long queryTimeAfterNumEntries, Duration periodicCompactionTime)` method.
@@ -646,42 +462,23 @@ The default value of Periodic compaction seconds is 30 days.
You could set it to 0 to turn off periodic compaction or set a small value to speed up expired state entries cleanup, but it
would trigger more compactions.
-You can activate debug logs from the native code of RocksDB filter
+You can activate debug logs from the native code of ForSt filter
by activating debug level for `FlinkCompactionFilter`:
-`log4j.logger.org.rocksdb.FlinkCompactionFilter=DEBUG`
+`log4j.logger.org.forstdb.FlinkCompactionFilter=DEBUG`
-**Notes:**
-- Calling of TTL filter during compaction slows it down.
-The TTL filter has to parse timestamp of last access and check its expiration
-for every stored state entry per key which is being compacted.
-In case of collection state type (list or map) the check is also invoked per stored element.
+**Notes:**
+- Calling of TTL filter during compaction slows it down.
+ The TTL filter has to parse timestamp of last access and check its expiration
+ for every stored state entry per key which is being compacted.
+ In case of collection state type (list or map) the check is also invoked per stored element.
- If this feature is used with a list state which has elements with non-fixed byte length,
-the native TTL filter has to call additionally a Flink java type serializer of the element over JNI per each state entry
-where at least the first element has expired to determine the offset of the next unexpired element.
-- For existing jobs, this cleanup strategy can be activated or deactivated anytime in `StateTtlConfig`,
-e.g. after restart from savepoint.
+ the native TTL filter has to call additionally a Flink java type serializer of the element over JNI per each state entry
+ where at least the first element has expired to determine the offset of the next unexpired element.
+- For existing jobs, this cleanup strategy can be activated or deactivated anytime in `StateTtlConfig`,
+ e.g. after restart from savepoint.
- Periodic compaction could only work when TTL is enabled.
-### State in the Scala DataStream API
-
-In addition to the interface described above, the Scala API has shortcuts for stateful
-`map()` or `flatMap()` functions with a single `ValueState` on `KeyedStream`. The user function
-gets the current value of the `ValueState` in an `Option` and must return an updated value that
-will be used to update the state.
-
-```scala
-val stream: DataStream[(String, Int)] = ...
-
-val counts: DataStream[(String, Int)] = stream
- .keyBy(_._1)
- .mapWithState((in: (String, Int), count: Option[Int]) =>
- count match {
- case Some(c) => ( (in._1, c), Some(c + in._2) )
- case None => ( (in._1, 0), Some(in._2) )
- })
-```
-
## Operator State
*Operator State* (or *non-keyed state*) is state that is bound to one
@@ -697,8 +494,6 @@ In a typical stateful Flink Application you don't need operators state. It is
mostly a special type of state that is used in source/sink implementations and
scenarios where you don't have a key by which state can be partitioned.
-**Notes:** Operator state is still not supported in Python DataStream API.
-
## Broadcast State
*Broadcast State* is a special type of *Operator State*. It was introduced to
@@ -762,7 +557,7 @@ Below is an example of a stateful `SinkFunction` that uses `CheckpointedFunction
to buffer elements before sending them to the outside world. It demonstrates
the basic even-split redistribution list state:
-{{< tabs "5b99313c-1801-486c-a085-ce66882a2e49" >}}
+{{< tabs "5b99663c-1801-486c-a085-ce66882a2k49" >}}
{{< tab "Java" >}}
```java
public class BufferingSink
@@ -814,49 +609,6 @@ public class BufferingSink
}
```
{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-class BufferingSink(threshold: Int = 0)
- extends SinkFunction[(String, Int)]
- with CheckpointedFunction {
-
- @transient
- private var checkpointedState: ListState[(String, Int)] = _
-
- private val bufferedElements = ListBuffer[(String, Int)]()
-
- override def invoke(value: (String, Int), context: Context): Unit = {
- bufferedElements += value
- if (bufferedElements.size >= threshold) {
- for (element <- bufferedElements) {
- // send it to the sink
- }
- bufferedElements.clear()
- }
- }
-
- override def snapshotState(context: FunctionSnapshotContext): Unit = {
- checkpointedState.update(bufferedElements.asJava)
- }
-
- override def initializeState(context: FunctionInitializationContext): Unit = {
- val descriptor = new ListStateDescriptor[(String, Int)](
- "buffered-elements",
- TypeInformation.of(new TypeHint[(String, Int)]() {})
- )
-
- checkpointedState = context.getOperatorStateStore.getListState(descriptor)
-
- if(context.isRestored) {
- for(element <- checkpointedState.get().asScala) {
- bufferedElements += element
- }
- }
- }
-
-}
-```
-{{< /tab >}}
{{< /tabs >}}
The `initializeState` method takes as argument a `FunctionInitializationContext`. This is used to initialize
@@ -879,18 +631,6 @@ ListStateDescriptor<Tuple2<String, Integer>> descriptor =
checkpointedState = context.getOperatorStateStore().getListState(descriptor);
```
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-
-val descriptor = new ListStateDescriptor[(String, Long)](
- "buffered-elements",
- TypeInformation.of(new TypeHint[(String, Long)]() {})
-)
-
-checkpointedState = context.getOperatorStateStore.getListState(descriptor)
-
-```
{{< /tab >}}
{{< /tabs >}}
The naming convention of the state access methods contain its redistribution
@@ -909,110 +649,16 @@ of all objects included by the previous checkpoint, and is then filled with the
As a side note, the keyed state can also be initialized in the `initializeState()` method. This can be done
using the provided `FunctionInitializationContext`.
-### 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.
-
-{{< tabs "aa821e89-7cc6-4c1e-be5b-90bfa0df6036" >}}
-{{< tab "Java" >}}
-```java
-public static class CounterSource
- extends RichParallelSourceFunction<Long>
- implements CheckpointedFunction {
-
- /** current offset for exactly once semantics */
- private Long offset = 0L;
-
- /** flag for job cancellation */
- private volatile boolean isRunning = true;
-
- /** Our state object. */
- private ListState<Long> state;
-
- @Override
- public void run(SourceContext<Long> ctx) {
- final Object lock = ctx.getCheckpointLock();
-
- while (isRunning) {
- // output and state update are atomic
- synchronized (lock) {
- ctx.collect(offset);
- offset += 1;
- }
- }
- }
-
- @Override
- public void cancel() {
- isRunning = false;
- }
-
- @Override
- public void initializeState(FunctionInitializationContext context) throws Exception {
- state = context.getOperatorStateStore().getListState(new ListStateDescriptor<>(
- "state",
- LongSerializer.INSTANCE));
-
- // restore any state that we might already have to our fields, initialize state
- // is also called in case of restore.
- for (Long l : state.get()) {
- offset = l;
- }
- }
-
- @Override
- public void snapshotState(FunctionSnapshotContext context) throws Exception {
- state.update(Collections.singletonList(offset));
- }
-}
-```
-{{< /tab >}}
-{{< tab "Scala" >}}
-```scala
-class CounterSource
- extends RichParallelSourceFunction[Long]
- with CheckpointedFunction {
-
- @volatile
- private var isRunning = true
-
- private var offset = 0L
- private var state: ListState[Long] = _
-
- override def run(ctx: SourceFunction.SourceContext[Long]): Unit = {
- val lock = ctx.getCheckpointLock
-
- while (isRunning) {
- // output and state update are atomic
- lock.synchronized({
- ctx.collect(offset)
-
- offset += 1
- })
- }
- }
+{{< top >}}
- override def cancel(): Unit = isRunning = false
-
- override def initializeState(context: FunctionInitializationContext): Unit = {
- state = context.getOperatorStateStore.getListState(
- new ListStateDescriptor[Long]("state", classOf[Long]))
+## Migrate from the Old State API
- for (l <- state.get().asScala) {
- offset = l
- }
- }
+It is very easy to migrate from the old state API to the new one. Please take the following steps:
- override def snapshotState(context: FunctionSnapshotContext): Unit = {
- state.update(java.util.Collections.singletonList(offset))
- }
-}
-```
-{{< /tab >}}
-{{< /tabs >}}
-
-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 `org.apache.flink.api.common.state.CheckpointListener` interface.
-
-{{< top >}}
+1. Invoke `enableAsyncState()` on the `KeyedStream` to enable the new state API.
+2. Replace the `StateDescriptor`s with the new ones under `v2` package. Also, replace the old state
+handles with the new ones under `v2` package.
+3. Rewrite the old state access methods with the new asynchronous ones.
+4. It is recommended to use ForSt State Backend for the new state API, which could perform
+async state access. Other state backends only support synchronous execution of state access,
+although it can be used with the new state API.