Video in progress
How do you build a multi-step process that runs for several days (for example a loan application: scoring, operator review, contract, money transfer) in Spring?
The process state lives in the database as an explicit state machine; every step is idempotent, and timers and waits survive a pod restart. As complexity grows, a workflow engine like Temporal or Camunda ends up cheaper than hand-written orchestration.
📖 Answer
You can't build a process like this with a single method or a chain of @Async calls: pods restart, an operator doesn't respond for two days, the external scoring service is down for 10 minutes. The process state has to live in the database, not in memory.
Option 1: a state machine you write yourself.
enum LoanStatus { SUBMITTED, SCORING, MANUAL_REVIEW, APPROVED, CONTRACT_SIGNED, DISBURSED, REJECTED }
- Every transition is a separate transaction with optimistic locking via
@Version, and the table of allowed transitions lives in code. - An event or a queue triggers the next step (through an outbox).
- Timers ("if the operator doesn't look within 48 hours, escalate") are a
due_atcolumn in the database and a scheduler that reads it in batches (FOR UPDATE SKIP LOCKED). - Every step is idempotent: if "transfer money" is called twice, the second call does nothing.
For a simple process (5–7 states, little branching) this is enough and transparent.
Option 2: a workflow engine. Temporal, Camunda, Flowable:
- state, timers, retry and versioning come ready-made;
- in Temporal the process is written as ordinary code, and the engine saves it after each step and continues after a crash;
- in Camunda there is a BPMN diagram that business analysts can read too.
The cost: new critical infrastructure, a learning curve, versioning rules (how running processes continue with changed code).
How I decide:
- If there are many steps, branches, timers and compensations, and there are several such processes in the system, use an engine.
- A single simple process: state machine + outbox + scheduler.
In both cases I need: the full history of every application (who, when, from which state to which), a dashboard that finds "stuck" processes, and safe tools for an operator to step in manually. In practice, in a process that runs for days some application will end up in a strange state anyway, so design for that up front.
Sign up to mark studied questions and save your progress.