State
You can store key-value state in Restate. Restate makes sure the state is consistent with the processing of the code execution.
This feature is only available for Virtual Objects. State is isolated per Virtual Object.
Command-line introspection
You can inspect and edit the K/V state stored in Restate via psql
and the CLI.
Have a look at the introspection docs for more information.
You can do the following operations on the state:
- Java
- Kotlin
Listing state keys
For a single Virtual Object, you can list all the state keys that have entries in the state store via:
- Java
- Kotlin
Collection<String> keys = ctx.stateKeys();
val keys = ctx.stateKeys()
Retrieving state
- Java
- Kotlin
// Getting String valueStateKey<String> STRING_STATE_KEY = StateKey.of("my-key", CoreSerdes.JSON_STRING);String stringState = ctx.get(STRING_STATE_KEY).orElse("my-default");// Getting integer valueStateKey<Integer> INT_STATE_KEY = StateKey.of("my-key", CoreSerdes.JSON_INT);int intState = ctx.get(INT_STATE_KEY).orElse(0);
- Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
- Use
ctx.get
to retrieve the state for a specific key.
// Getting String valueval STRING_STATE_KEY = KtStateKey.json<String>("my-key")val stringState: String? = ctx.get(STRING_STATE_KEY)// Getting integer valueval INT_STATE_KEY = KtStateKey.json<Int>("my-key")val intState: Int? = ctx.get(INT_STATE_KEY)
- Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
- Use
ctx.get
to retrieve the state for a specific key.
Setting state
- Java
- Kotlin
StateKey<String> STRING_STATE_KEY = StateKey.of("my-key", CoreSerdes.JSON_STRING);ctx.set(STRING_STATE_KEY, "my-new-value");
- Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
- Use
ctx.set
to set the state for a specific key. The type of value needs to line up with the type that was defined in the StateKey.
val STRING_STATE_KEY = KtStateKey.json<String>("my-key")ctx.set(STRING_STATE_KEY, "my-new-value")
- Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
- Use
ctx.set
to set the state for a specific key. The type of value needs to line up with the type that was defined in the StateKey.
Clearing state
- Java
- Kotlin
StateKey<String> STRING_STATE_KEY = StateKey.of("my-key", CoreSerdes.JSON_STRING);ctx.clear(STRING_STATE_KEY);
- Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
- Use
ctx.clear
to delete the state for a specific key.
val STRING_STATE_KEY = KtStateKey.json<String>("my-key")ctx.clear(STRING_STATE_KEY)
- Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
- Use
ctx.clear
to delete the state for a specific key.
Clearing all state
- Java
- Kotlin
ctx.clearAll();
ctx.clearAll()
This will delete all the state stored in Restate for the Virtual Object.