How-To: Build a stateful service

    In this article you’ll learn how you can create a stateful service which can be horizontally scaled, using opt-in concurrency and consistency models.

    This frees developers from difficult state coordination, conflict resolution and failure handling, and allows them instead to consume these capabilities as APIs from Dapr.

    A state store component represents a resource that Dapr uses to communicate with a database. For the purpose of this guide, we’ll use a Redis state store.

    See a list of supported state stores here

    The Dapr CLI automatically provisions a state store (Redis) and creates the relevant YAML when running your app with . To change the state store being used, replace the YAML under with the file of your choice.

    Kubernetes

    See the instructions here on how to setup different state stores on Kubernetes.

    For get requests, Dapr will make sure the store returns the most up to date data consistently among replicas. The default is eventual consistency, unless specified otherwise in the request to the state API.

    The following examples illustrates using strong consistency:

    The following example is written in Python, but is applicable to any programming language

    Getting state

    The following example is written in Python, but is applicable to any programming language

    The following example is written in Python, but is applicable to any programming language

    Last-write concurrency is the default concurrency mode if the option is not specified.

    The default mode for Dapr is Last-write-wins.

    Dapr uses version numbers to determine whether a specific key has been updated. Clients retain the version number when reading the data for a key and then use the version number during updates such as writes and deletes. If the version information has changed since the client retrieved, an error is thrown, which then requires the client to perform a read again to get the latest version information and state.

    Dapr utilizes ETags to determine the state’s version number. ETags are returned from state requests in an header.

    Using ETags, clients know that a resource has been updated since the last time they checked by erroring when there’s an ETag mismatch.

    The following example shows how to get an ETag, and then use it to save state and then delete the state:

    The following example is written in Python, but is applicable to any programming language

    Handling version mismatch failures