Skip to main content

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 and Workflows:

  • For Virtual Objects, the state is isolated per Virtual Object and lives forever (across invocations for that object).
  • For Workflows, you can think of it as if every workflow execution is a new object. So the state is isolated to a single workflow execution. The state can only be mutated by the run handler of the workflow. The other handlers can only read the state.
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:

Listing state keys

For a single Virtual Object, you can list all the state keys that have entries in the state store via:

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

Retrieving state

// Getting String value
StateKey<String> STRING_STATE_KEY = StateKey.of("my-key", JsonSerdes.STRING);
String stringState = ctx.get(STRING_STATE_KEY).orElse("my-default");
// Getting integer value
StateKey<Integer> INT_STATE_KEY = StateKey.of("my-key", JsonSerdes.INT);
int intState = ctx.get(INT_STATE_KEY).orElse(0);
  1. Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
  2. Use ctx.get to retrieve the state for a specific key.

Setting state

StateKey<String> STRING_STATE_KEY = StateKey.of("my-key", JsonSerdes.STRING);
ctx.set(STRING_STATE_KEY, "my-new-value");
  1. Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
  2. 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

StateKey<String> STRING_STATE_KEY = StateKey.of("my-key", JsonSerdes.STRING);
ctx.clear(STRING_STATE_KEY);
  1. Define the state key (key name and (de)serializer) at the top of the Virtual Object class.
  2. Use ctx.clear to delete the state for a specific key.

Clearing all state

ctx.clearAll();

This will delete all the state stored in Restate for the Virtual Object.