Implementing State Machines in PostgreSQL (2017)

https://news.ycombinator.com/rss Hits: 3
Summary

Implementing State Machines in PostgreSQL Published: July 27, 2017 Finite-state machine (FSM) is a wonderful model of computation that has many practical applications. One of my favorites is turning business logic into simple FSMs. For example consider the following requirements for an order management system: Orders must not ship before they are paid. Orders can be canceled, but only if they haven’t shipped yet. An order that has already been paid, needs to be refunded after canceling. Informally, turning such a list of requirements into an FSM is simply the process of coming up with: a set of states an order can be in, a set of events, a transition function that maps the combination of each state and event to a new state, and an initial state. In practice this is usually done by drawing up a directed graph that shows how the different states are connected to each other via events: Besides guiding our implementation, these graphs can be very useful for discussions and analysis. For example you can immediately see how there is no way for a customer to return an order after it has shipped. Additionally the process of naming the involved states and events automatically creates a precise language that can be adopted by all stakeholders. You might have noticed that the graph above does not show all possible combinations of all states and all events. The reason is that the missing combinations implicitly lead to an error state. The complete FSM can be shown as a graph as well, but I don’t think it’s very useful in practice. Anyway, as promised in the title of this article we’re going to implement this FSM in PostgreSQL. This may not be everybody’s cup of tea, but you might like how this approach us gives advanced analytical powers as a free by-product. Embedding this kind of logic into the database can also help protect against race conditions, but this will perhaps be the topic of a future post . Let’s begin by creating an order_events table which keeps track of all eve...

First seen: 2025-05-08 22:12

Last seen: 2025-05-09 00:12