Skip to main content

State

Restate offers durable storage of application state, with support for key-value state that can be retrieved, set, and cleared via its key. Using this feature requires no additional setup.

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.

Listing state keys​

To list all the keys that have entries in the state store for that invocation (and its keyed service instance), do:

Collection<String> keys = ctx.stateKeys();

Retrieving state​

To retrieve state in Restate, you can do the following:

First, you need to define the state key: a combination of a key name and (de)serializer. You can use Restate's built-in CoreSerdes for serialization of primitive types. For the serialization of custom types, have a look at the serialization documentation.

Once you have defined the STATE_KEY, you can retrieve the state in your methods as follows:

// Example of retrieving String value from state
StateKey<String> STRING_STATE_KEY = StateKey.of("my-key", CoreSerdes.JSON_STRING);
String stringState = ctx.get(STRING_STATE_KEY).orElse("my-default");

// Example of retrieving integer value from state
StateKey<Integer> INT_STATE_KEY = StateKey.of("my-key", CoreSerdes.JSON_INT);
int intState = ctx.get(INT_STATE_KEY).orElse(0);

This will return either the value that was stored or null if no value was stored.

Setting state​

To set a key-value pair in Restate, do:

ctx.set(STRING_STATE_KEY, "my-new-value");

Have a look at the docs on retrieving state to understand how to create the state key.

The type of value needs to line up with the type that was defined in the StateKey.

Replace my-new-value with the value that you want to set.

Clearing state​

To delete the value of a key in Restate, do:

ctx.clear(STRING_STATE_KEY);

Have a look at the docs on retrieving state to understand how to create the state key.

To delete all K/V state entries for the invocation (and its keyed service instance), do:

ctx.clearAll();