Video in progress
How do you build a state machine for a long-running business process: Spring Statemachine or your own code?
Most of the time I write it myself: the state is a database column, the transition table is in code, and every transition is protected by an optimistic lock. Spring Statemachine makes sense when you need complex hierarchical states, but persisting it and debugging it is harder.
📖 Answer
A loan application, a KYC check, an order delivery: these take days. So the state lives in the database, not in memory, and any pod can run any step.
The schema I use:
create table application (
id bigint primary key,
state varchar(32) not null,
version bigint not null,
updated_at timestamptz not null
);
create table application_transition (
application_id bigint, from_state varchar(32), to_state varchar(32),
event varchar(64), actor varchar(64), at timestamptz
);
A transition: a (state, event) -> newState table in code, executed in a single transaction: check the state, write the side effect to the outbox, then update ... where id = ? and version = ?. If two workers try to transition at once, one gets an OptimisticLockException. That is expected; it re-reads and decides again.
The history table isn't only for audit: it answers the question "why did the application sit in REVIEW for 3 days?". Monitoring the "maximum time in this state" for each state is the easiest way to find stuck processes.
What Spring Statemachine gives you: hierarchical and parallel states, guards, actions, and configuration close to UML. The cost: its own abstractions, extra setup for persistence, and errors that are harder to trace. Also, the project's activity has slowed in recent years, so I take that into account before adding it to a new system.
If the process spans many services and has many timers and compensations, it's time to talk about a workflow engine (Temporal, Camunda).
Sign up to mark studied questions and save your progress.