Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

How to design state machines for microservices

November 23, 2021
Avishay Traeger Michael Filanov
Related topics:
Automation and managementGoKubernetes
Related products:
Red Hat OpenShift

    Backend services and microservices typically use state machines to maintain the state of their resources, whether the state machine is defined explicitly or not. To create a well-written service, you must expressly and clearly define its state machine, so that users know what to expect and can ensure that tests cover all possible (and impossible) transitions.

    In this article, you'll learn important guidelines for building state machines. You'll also get an introduction to stateswitch, a Go library that you can use to organize a state machine's transition logic.

    What is a state machine?

    When we discuss state machines in this context, we refer to deterministic finite state machines, which are widely used in mathematics and computer sciences to model problems. State machines have a single start state and one or more accepting, or final, states. Transitions between the states describe the input or event required for moving from one state to another. When designing and developing services or micro-services, it is useful to model the resources that those services manage as state machines.

    As an example, consider a state machine for a user subscription, as illustrated in Figure 1.

    Diagram of an example state machine.
    Figure 1. An example of a state machine.

    This example shows a few kinds of states and transitions. There is a start state, creating, and a final state, canceled. The backend handles the transition from creating to created once processing is complete, making creating an intermediate state. You should use intermediate states when a transition cannot occur within a single database transaction. This avoids races and indicates to users that an operation is in progress. Explicit user actions trigger the transitions to and from suspended and to canceled.

    Implementing state machines

    Visualizing a state machine, as we've done here, can help you determine whether it is robust. The example diagram in Figure 1 should raise some questions: Can a user cancel a suspended subscription, for instance? And is there an error state for subscriptions with an unrecoverable error?

    Here are a few general points to keep in mind when designing state machines for microservices:

    • A resource's state should generally be stored with that resource's metadata—in an SQL database or key-value store, for example. All changes to the resource, including the state change, should be made to in-memory objects and committed in a single transaction at the end of the operation to avoid races.
    • Maintain a state-info property with human-readable text explaining the state and the reasons why the resource might have transitioned there. For example, the state-info corresponding to the canceled state might be "Subscription canceled per user request."
    • Each intermediate state should have a timeout defined so that the service can recover from stalled or aborted operations. You can keep track of the timeout duration with a state-updated-at property containing a timestamp updated when the state changes.
    • At the start of each API action, check to see if the action applies during the current state. If not, return an appropriate error to the user, such as "409 Conflict" in REST.

    Stateswitch: Organizing transition logic

    You should avoid using lengthy sequences of if-else statements to define transitions, as such code is prone to bugs. Instead, you can use stateswitch, a library written in Go, to organize the transition logic. With stateswitch, you define each transition by specifying the source states, a destination state, the condition upon which to transition, and a method to call upon transitioning.

    As an example, consider the Red Hat OpenShift assisted installer. This service exposes REST and Kubernetes APIs that allow users to discover hosts, group them into OpenShift clusters, and monitor cluster installations. The service has state machines for host and cluster resources.

    Use APIs to expose service states

    A final point to consider is using APIs to expose states to users. In REST, it is natural to include the state in the resource's properties. The user sees a concise single-string value, and a user interface (UI) can easily display it. On the downside, the state's meaning might not be apparent to users who don't know how your state machine works. Another downside is that scripts might rely on the order of your state machine's transitions, such that even adding a state could represent a breaking API change.

    You could represent the state properties in OpenAPI format as follows:

          state:
            type: string
            description: State of the subscription.
            enum:
              - creating
              - created
              - suspended
              - canceled
          state_info:
            type: string
            description: Additional information pertaining to the subscription state.
          state_updated_at:
            type: string
            format: date-time
            description: The last time that the subscription state was updated.
    

    Kubernetes-native APIs would typically use conditions to expose the state. In our example state machine, the conditions might be active and suspended. The Kubernetes controller would set the active condition to TRUE if the state is created or suspended, and would set the suspended condition to TRUE if the state is suspended.

    Users and scripts can precisely examine the conditions they are interested in without needing to understand the underlying state machine, and new states can be added without breaking the API. The downside is that the state is not expressed concisely, which can cause problems if it's displayed in a UI. Of course, conditions can be added to a REST API or a concise state added to a Kubernetes API.

    Conclusion

    State machines help engineers visualize a resource's behavior, find gaps or inconsistencies, organize code, and improve test coverage. They also allow users to understand the machine's behavior and know what to expect. In this article, you've learned important guidelines for implementing a state machine, and have seen how the stateswitch library can help.

    Last updated: September 20, 2023

    Related Posts

    • Managing stateful applications with Kubernetes Operators in Golang

    • Create a Kubernetes Operator in Golang to automatically manage a simple, stateful application

    • Behavior is easy, state is hard: Tame inconsistent state in your Java code

    Recent Posts

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    • Fun in the RUN instruction: Why container builds with distroless images can surprise you

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.