How-To: Build a stateful service

    In this article, you’ll learn how to create a stateful service which can be horizontally scaled, using opt-in concurrency and consistency models. Consuming the state management API frees developers from difficult state coordination, conflict resolution, and failure handling.

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

    When you run in self-hosted mode, Dapr creates a default Redis statestore.yaml and runs a Redis state store on your local machine, located:

    • On Windows, under
    • On Linux/MacOS, under ~/.dapr/components/statestore.yaml

    With the component, you can easily swap out underlying components without application code changes.

    See a list of supported state stores.

    Kubernetes

    Using strong consistency, Dapr makes sure that the underlying state store:

    • Returns the response once the data has been written to all replicas.
    • Receives an ACK from a quorum before writing or deleting state.

    For get requests, Dapr ensures 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 illustrate how to save, get, and delete state using strong consistency. The example is written in Python, but is applicable to any programming language.

    Getting state

    If the concurrency option hasn’t been specified, the default is last-write concurrency mode.

    Dapr allows developers to opt-in for two common concurrency patterns when working with data stores:

    • Last-write-wins: Default mode for Dapr.
    1. Retain the version number when reading the data for a key.
    2. Use the version number during updates such as writes and deletes.

    If the version information has changed since the version number was retrieved, an error is thrown, requiring you to perform another read 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, your application knows that a resource has been updated since the last time they checked by erroring during an ETag mismatch.

    The following example shows how to:

    • Get an ETag.
    • Use the ETag to save state.
    • Delete the state.

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

    Handling version mismatch failures

    In the following example, you’ll see how to retry a save state operation when the version has changed: