The Practical Developer

Finite State Machines for Backend Workflow Orchestration

Your order-fulfillment code is a tangle of boolean flags, if-else chains, and silent failure paths. Replace it with an explicit state machine that is testable, auditable, and survives server restarts.

An automated warehouse with packages moving through a conveyor system, the physical version of a workflow state machine

Every order-processing system I have touched starts the same way: a status column with a few string values, a pile of if (order.status === 'pending') checks spread across different services, and a monthly incident where an order gets stuck in “shipped” because some callback ran twice and the status transition logic did not see it coming.

The real problem is not the bugs. The real problem is that the workflow lives in your head, not in the code. You know the five states an order can be in and the seven transitions between them, but none of that knowledge is explicit. It is scattered across fifteen handlers, three cron jobs, and a dead-letter queue that nobody checks.

Finite state machines fix this by making the workflow the first-class citizen. You define every state, every valid transition, and every side effect in one place. The code becomes a declarative map of the business process. Invalid transitions throw errors immediately. Stalled workflows are detectable. And the whole thing is testable without a staging environment.

This post builds a lightweight state machine pattern in TypeScript, wires it to PostgreSQL for persistence, and walks through a complete order-fulfillment workflow. No external libraries, no magic. Just a pattern you can use in any Node.js backend.

The spaghetti workflow

Here is the kind of code I keep finding in production. An order goes through these states:

// order-service/src/handlers/fulfillment.ts -- a real mess
async function processPayment(orderId: string) {
  const order = await db.orders.findById(orderId);
  if (order.status === 'pending' && order.paymentIntent) {
    const result = await paymentGateway.charge(order.paymentIntent);
    if (result.success) {
      await db.orders.update(orderId, { status: 'paid' });
      await inventory.reserve(order.items);
      await notification.send(order.userId, 'payment_confirmed');
    } else if (result.declined) {
      await db.orders.update(orderId, { status: 'payment_failed' });
      await notification.send(order.userId, 'payment_declined');
    }
  }
}

async function shipOrder(orderId: string) {
  const order = await db.orders.findById(orderId);
  if (order.status === 'paid' && order.shippingAddress) {
    // ... ship it
  } else if (order.status === 'payment_failed') {
    // should we ship failed orders? nobody knows
  }
}

This looks innocent. But after six months it grows into:

  • Status strings that no handler checks for (“refund_requested” is set by the support tool, but the main fulfillment pipeline never handles it)
  • Impossible states (an order can be simultaneously “shipped” and “refund_pending” if two handlers run concurrently)
  • Silent failures (a transition fails, the status stays “pending”, and nobody learns about it until the CEO asks why a VIP order has been pending for three days)

You have seen this before. You have probably written it. The fix is to replace the implicit workflow with an explicit one.

What a finite state machine is

A finite state machine (FSM) has three things:

  • States: the finite set of conditions a workflow can be in (e.g., pending, paid, shipped, delivered)
  • Transitions: the allowed moves between states, triggered by events (e.g., payment_succeeded transitions from pending to paid)
  • Guards: conditions that must be true for a transition to fire (e.g., the payment intent must exist)
  • Actions: side effects that run when a transition fires (e.g., call the shipping API, send an email)

The rule is: at any moment, the workflow is in exactly one state. It can only move to another state through a defined transition. No magic jumps, no dual-status hacks.

Building a lightweight state machine

You do not need a framework for this. A TypeScript class with about 50 lines does it:

// state-machine.ts
type State = string;
type Event = string;
type Context = Record<string, unknown>;

type TransitionDefinition<S extends State, E extends Event> = {
  from: S | S[];
  to: S;
  event: E;
  guard?: (context: Context) => boolean | Promise<boolean>;
  action?: (context: Context) => Promise<Context>;
};

type StateMachineDefinition<S extends State, E extends Event> = {
  initialState: S;
  states: S[];
  transitions: TransitionDefinition<S, E>[];
};

export class StateMachine<S extends State, E extends Event> {
  private def: StateMachineDefinition<S, E>;

  constructor(def: StateMachineDefinition<S, E>) {
    this.def = def;
    this.validate();
  }

  private validate() {
    for (const t of this.def.transitions) {
      const froms = Array.isArray(t.from) ? t.from : [t.from];
      for (const from of froms) {
        if (!this.def.states.includes(from)) {
          throw new Error(`Invalid state '${from}' in transition for event '${t.event}'`);
        }
      }
      if (!this.def.states.includes(t.to)) {
        throw new Error(`Invalid target state '${t.to}' in transition for event '${t.event}'`);
      }
    }
  }

  async transition(
    currentState: S,
    event: E,
    context: Context
  ): Promise<{ state: S; context: Context }> {
    const candidate = this.def.transitions.find((t) => {
      const froms = Array.isArray(t.from) ? t.from : [t.from];
      return t.event === event && froms.includes(currentState);
    });

    if (!candidate) {
      throw new Error(
        `Invalid transition: cannot move from '${currentState}' on event '${event}'`
      );
    }

    if (candidate.guard) {
      const allowed = await candidate.guard(context);
      if (!allowed) {
        throw new Error(
          `Guard rejected transition: '${currentState}' -> '${candidate.to}' on '${event}'`
        );
      }
    }

    const newContext = candidate.action ? await candidate.action(context) : context;

    return { state: candidate.to, context: newContext };
  }

  canTransition(currentState: S, event: E): boolean {
    return this.def.transitions.some((t) => {
      const froms = Array.isArray(t.from) ? t.from : [t.from];
      return t.event === event && froms.includes(currentState);
    });
  }
}

That is it. The machine validates itself at construction time (no undefined states in transitions), rejects illegal moves at runtime, and passes an immutable context through every action so you can track what happened.

Example: order fulfillment workflow

Now apply the machine to a real order flow. Define every state and every allowed transition:

// order-machine.ts
import { StateMachine } from './state-machine';

type OrderState =
  | 'pending'
  | 'payment_processing'
  | 'paid'
  | 'payment_failed'
  | 'fulfillment_pending'
  | 'shipped'
  | 'delivered'
  | 'cancel_requested'
  | 'cancelled'
  | 'refund_pending'
  | 'refunded';

type OrderEvent =
  | 'SUBMIT'
  | 'PAYMENT_STARTED'
  | 'PAYMENT_SUCCEEDED'
  | 'PAYMENT_FAILED'
  | 'INVENTORY_RESERVED'
  | 'SHIP'
  | 'DELIVER'
  | 'CANCEL'
  | 'CANCEL_CONFIRMED'
  | 'REFUND_REQUEST'
  | 'REFUND_COMPLETE';

type OrderContext = {
  orderId: string;
  userId: string;
  items: Array<{ sku: string; qty: number }>;
  paymentIntentId?: string;
  shipmentId?: string;
  refundId?: string;
  reason?: string;
  failedAttempts?: number;
};

const orderMachine = new StateMachine<OrderState, OrderEvent>({
  initialState: 'pending',
  states: [
    'pending',
    'payment_processing',
    'paid',
    'payment_failed',
    'fulfillment_pending',
    'shipped',
    'delivered',
    'cancel_requested',
    'cancelled',
    'refund_pending',
    'refunded',
  ],
  transitions: [
    // Payment flow
    { from: 'pending', to: 'payment_processing', event: 'SUBMIT',
      guard: (ctx) => ctx.items.length > 0,
      action: async (ctx) => ({ ...ctx, failedAttempts: 0 }) },
    { from: 'payment_processing', to: 'paid', event: 'PAYMENT_SUCCEEDED' },
    { from: 'payment_processing', to: 'payment_failed', event: 'PAYMENT_FAILED',
      action: async (ctx) => ({
        ...ctx,
        failedAttempts: (ctx.failedAttempts ?? 0) + 1,
      })},
    { from: 'payment_failed', to: 'payment_processing', event: 'SUBMIT',
      guard: (ctx) => (ctx.failedAttempts ?? 0) < 3 },

    // Fulfillment
    { from: 'paid', to: 'fulfillment_pending', event: 'INVENTORY_RESERVED' },
    { from: 'fulfillment_pending', to: 'shipped', event: 'SHIP',
      action: async (ctx) => ({ ...ctx, shipmentId: crypto.randomUUID() }) },
    { from: 'shipped', to: 'delivered', event: 'DELIVER' },

    // Cancellation
    { from: ['pending', 'payment_processing', 'payment_failed'], to: 'cancel_requested',
      event: 'CANCEL' },
    { from: 'cancel_requested', to: 'cancelled', event: 'CANCEL_CONFIRMED' },

    // Refund (only after payment went through)
    { from: ['paid', 'fulfillment_pending', 'shipped', 'delivered'], to: 'refund_pending',
      event: 'REFUND_REQUEST',
      guard: (ctx) => !!ctx.paymentIntentId },
    { from: 'refund_pending', to: 'refunded', event: 'REFUND_COMPLETE' },
  ],
});

Every valid path through the order workflow is defined in one place. You can see at a glance that:

  • A payment can be retried up to 3 times
  • Cancellation is only allowed before shipping
  • Refunds require a payment intent ID
  • Shipping generates a shipment ID as a side effect

If someone sends a SHIP event for an order that is still pending, the machine throws immediately. No silent no-op, no partial state update.

Persisting state in PostgreSQL

A state machine that lives only in memory is a debugging exercise. The real value comes from persisting every transition so you can audit the entire lifecycle of a workflow, recover from crashes, and detect stalls. PostgreSQL is a perfect fit here: one table for the current state, one table for the event log.

// order-repository.ts
import { Pool } from 'pg';

type StoredWorkflow = {
  id: string;
  workflow_type: string;
  state: string;
  context: Record<string, unknown>;
  version: number;
  created_at: Date;
  updated_at: Date;
};

type StoredEvent = {
  id: string;
  workflow_id: string;
  from_state: string;
  to_state: string;
  event: string;
  context: Record<string, unknown>;
  created_at: Date;
};

export class OrderRepository {
  constructor(private pool: Pool) {
    this.ensureTables();
  }

  private async ensureTables() {
    await this.pool.query(`
      CREATE TABLE IF NOT EXISTS workflows (
        id TEXT PRIMARY KEY,
        workflow_type TEXT NOT NULL,
        state TEXT NOT NULL,
        context JSONB NOT NULL DEFAULT '{}',
        version INTEGER NOT NULL DEFAULT 1,
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      );

      CREATE TABLE IF NOT EXISTS workflow_events (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        workflow_id TEXT NOT NULL REFERENCES workflows(id),
        from_state TEXT NOT NULL,
        to_state TEXT NOT NULL,
        event TEXT NOT NULL,
        context JSONB NOT NULL DEFAULT '{}',
        created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
      );

      CREATE INDEX IF NOT EXISTS idx_workflow_events_workflow_id
        ON workflow_events(workflow_id, created_at);
    `);
  }

  async createWorkflow(
    id: string,
    workflowType: string,
    initialState: string,
    context: Record<string, unknown>
  ): Promise<void> {
    await this.pool.query(
      `INSERT INTO workflows (id, workflow_type, state, context)
       VALUES ($1, $2, $3, $4)
       ON CONFLICT (id) DO NOTHING`,
      [id, workflowType, initialState, JSON.stringify(context)]
    );
  }

  async getWorkflow(id: string): Promise<StoredWorkflow | null> {
    const result = await this.pool.query(
      'SELECT * FROM workflows WHERE id = $1',
      [id]
    );
    return result.rows[0] || null;
  }

  async transition(
    id: string,
    fromState: string,
    toState: string,
    event: string,
    context: Record<string, unknown>,
    expectedVersion: number
  ): Promise<boolean> {
    // Optimistic concurrency: only update if version matches
    const result = await this.pool.query(
      `UPDATE workflows
       SET state = $1, context = $2, version = version + 1, updated_at = NOW()
       WHERE id = $3 AND version = $4
       RETURNING version`,
      [toState, JSON.stringify(context), id, expectedVersion]
    );

    if (result.rowCount === 0) {
      return false; // Concurrent modification detected
    }

    // Record the event
    await this.pool.query(
      `INSERT INTO workflow_events (workflow_id, from_state, to_state, event, context)
       VALUES ($1, $2, $3, $4, $5)`,
      [id, fromState, toState, event, JSON.stringify(context)]
    );

    return true;
  }

  async getEventHistory(workflowId: string): Promise<StoredEvent[]> {
    const result = await this.pool.query(
      'SELECT * FROM workflow_events WHERE workflow_id = $1 ORDER BY created_at',
      [workflowId]
    );
    return result.rows;
  }

  async findStalledWorkflows(
    workflowType: string,
    activeStates: string[],
    timeoutMinutes: number
  ): Promise<StoredWorkflow[]> {
    const result = await this.pool.query(
      `SELECT * FROM workflows
       WHERE workflow_type = $1
         AND state = ANY($2)
         AND updated_at < NOW() - INTERVAL '1 minute' * $3
       ORDER BY updated_at`,
      [workflowType, activeStates, timeoutMinutes]
    );
    return result.rows;
  }
}

The optimistic concurrency control using version is critical. If two handlers try to transition the same order simultaneously, one fails with a clean error instead of silently overwriting the other’s update. The event log gives you a complete audit trail: you can reconstruct the exact sequence of transitions for any order.

Wiring it together

Here is how the repository and the state machine work together in a real request handler:

// handlers.ts -- the real thing
import { pool } from './db';
import { orderMachine } from './order-machine';
import { OrderRepository } from './order-repository';

const repo = new OrderRepository(pool);

export async function handlePaymentWebhook(payload: {
  orderId: string;
  status: 'succeeded' | 'failed';
  paymentIntentId: string;
}) {
  const workflow = await repo.getWorkflow(payload.orderId);
  if (!workflow) {
    throw new Error(`Order ${payload.orderId} not found`);
  }

  const event = payload.status === 'succeeded'
    ? 'PAYMENT_SUCCEEDED'
    : 'PAYMENT_FAILED';

  if (!orderMachine.canTransition(workflow.state as any, event)) {
    // This is not an error -- the webhook may arrive after we already
    // transitioned. Log and return 200 so the webhook sender stops retrying.
    console.log(`Ignored ${event} for order ${payload.orderId} in state ${workflow.state}`);
    return;
  }

  const context = {
    ...workflow.context as Record<string, unknown>,
    paymentIntentId: payload.paymentIntentId,
  };

  const result = await orderMachine.transition(
    workflow.state as any,
    event,
    context
  );

  const applied = await repo.transition(
    payload.orderId,
    workflow.state,
    result.state,
    event,
    result.context,
    workflow.version
  );

  if (!applied) {
    // Concurrent modification. Retry once.
    console.warn(`Concurrent modification on order ${payload.orderId}, retrying`);
    return handlePaymentWebhook(payload);
  }

  // After the transition, run any post-transition side effects
  if (result.state === 'paid') {
    await reserveInventory(payload.orderId, result.context);
  }
}

async function reserveInventory(orderId: string, context: Record<string, unknown>) {
  const items = context.items as Array<{ sku: string; qty: number }>;
  await inventoryClient.reserve(items);

  // After reserving, emit the next event -- this is where the
  // state machine shines: you can chain transitions naturally
  await emitEvent(orderId, 'INVENTORY_RESERVED', context);
}

async function emitEvent(orderId: string, event: string, context: Record<string, unknown>) {
  // In production, this could push to a message queue or trigger
  // an internal event bus. For simplicity, call the handler directly.
  const workflow = await repo.getWorkflow(orderId);
  if (!workflow) return;

  if (!orderMachine.canTransition(workflow.state as any, event)) {
    console.log(`Cannot emit ${event} for order ${orderId} in state ${workflow.state}`);
    return;
  }

  const result = await orderMachine.transition(
    workflow.state as any,
    event,
    context as any
  );

  await repo.transition(
    orderId,
    workflow.state,
    result.state,
    event,
    result.context,
    workflow.version
  );
}

The pattern is: load the workflow, check if the transition is valid, apply it with optimistic concurrency, then run side effects that trigger the next logical transition. Every step is guarded by the state machine. No handler can accidentally skip a state or apply an invalid transition.

Detecting stalled workflows

One of the best features of an explicit state machine is that you can query for stalled workflows directly. The findStalledWorkflows method returns every order that has been in an active state (paid, fulfillment_pending, shipped) longer than a threshold.

Run this as a cron job:

// stall-detector.ts
export async function detectStalledOrders() {
  const stalled = await repo.findStalledWorkflows(
    'order',
    ['payment_processing', 'fulfillment_pending', 'shipped'], // active states
    120 // stalled after 2 hours
  );

  for (const workflow of stalled) {
    console.warn(`Stalled workflow: ${workflow.id} in state ${workflow.state} since ${workflow.updated_at}`);

    // Alert your team
    await alerting.pagerDuty({
      title: `Order ${workflow.id} stalled in ${workflow.state}`,
      severity: 'warning',
      context: workflow.context,
    });
  }
}

Without an explicit state machine, detecting stalls requires parsing logs or writing ad-hoc queries against the orders table. With the machine, you ask “what orders are in an active state and have not transitioned in N minutes?” and get the answer in one SQL query.

Testing the state machine

When the workflow is implicit, testing it requires setting up a database, creating orders with specific statuses, and running handlers that may or may not do the right thing. When the workflow is explicit, you test the machine directly:

// order-machine.test.ts
import { describe, it, expect } from 'vitest';
import { orderMachine } from './order-machine';

describe('order state machine', () => {
  it('rejects payment on a non-existent order', async () => {
    await expect(
      orderMachine.transition('pending', 'PAYMENT_SUCCEEDED', { orderId: 'x', items: [] })
    ).rejects.toThrow('Invalid transition');
  });

  it('allows submit only with items', async () => {
    const ctx = { orderId: '1', userId: 'u1', items: [{ sku: 'ABC', qty: 1 }] };
    const result = await orderMachine.transition('pending', 'SUBMIT', ctx);
    expect(result.state).toBe('payment_processing');
  });

  it('prevents submit without items', async () => {
    const ctx = { orderId: '1', userId: 'u1', items: [] };
    await expect(
      orderMachine.transition('pending', 'SUBMIT', ctx)
    ).rejects.toThrow('Guard rejected');
  });

  it('blocks cancellation after shipping', () => {
    expect(orderMachine.canTransition('shipped', 'CANCEL')).toBe(false);
  });

  it('allows refund after delivery', () => {
    const ctx = { orderId: '1', userId: 'u1', items: [], paymentIntentId: 'pi_123' };
    expect(orderMachine.canTransition('delivered', 'REFUND_REQUEST')).toBe(true);
  });

  it('tracks failed payment attempts', async () => {
    const ctx = { orderId: '1', userId: 'u1', items: [{ sku: 'ABC', qty: 1 }] };
    const step1 = await orderMachine.transition('pending', 'SUBMIT', ctx);
    expect(step1.context.failedAttempts).toBe(0);

    const step2 = await orderMachine.transition('payment_processing', 'PAYMENT_FAILED', step1.context);
    expect(step2.context.failedAttempts).toBe(1);
  });

  it('blocks retry after 3 failed attempts', async () => {
    const ctx = { orderId: '1', userId: 'u1', items: [{ sku: 'ABC', qty: 1 }], failedAttempts: 3 };
    await expect(
      orderMachine.transition('payment_failed', 'SUBMIT', ctx)
    ).rejects.toThrow('Guard rejected');
  });
});

These tests run in milliseconds. No database, no network, no order fixtures. They test the business rules directly, and they fail with clear messages when a rule is wrong or missing.

When not to use this pattern

Finite state machines are not the answer to every problem. Here is where they hurt more than they help:

  • Simple CRUD flows. If your entity has two states (active/inactive) and one transition, a state machine adds ceremony with no benefit.
  • Deeply hierarchical workflows. If you need nested states (an order can be “pending_approval” AND “pending_payment” at the same time), you need a statechart (hierarchical state machine), not a flat FSM.
  • High-throughput stateless pipelines. If you are processing 100,000 events per second through a pipeline where each event is independent, the overhead of persisting every transition to PostgreSQL will cost you. Use a stream processor instead.
  • Teams that will not maintain it. The state machine pattern is only better than spaghetti if the team keeps the definition current. If nobody updates the machine when the business adds a new state, it becomes a lie with validation on top.

For everything else — multi-step order flows, refund pipelines, deployment release stages, user onboarding sequences, compliance review workflows — the explicit state machine is the difference between a system you debug by reading the code and one you debug by reading the logs.

The practical takeaway

You do not need a fancy framework or a dedicated workflow engine to bring order to your backend workflows. A 50-line TypeScript class, a PostgreSQL table with a version column, and a disciplined approach to defining states and transitions are enough to eliminate entire categories of bugs.

Start small. Pick one workflow — the one that generates the most support tickets or the one everyone is afraid to touch. Define its states, its transitions, and its guards in one file. Persist every transition. Write a cron job to detect stalls. Then watch the incident count drop.

The state machine is not infrastructure. It is documentation that runs.


A note from Yojji

The work of replacing implicit, if-else workflows with explicit, auditable state machines is the kind of engineering that does not show up in a feature demo but prevents the 2 AM support calls. It requires the discipline to define every state before writing a single handler, and the experience to know which transitions need guards and which need side effects.

That kind of production-aware backend architecture is exactly what Yojji ships. Yojji is an international custom software development company, founded in 2016, with offices in Europe, the US, and the UK. Their teams specialize in the JavaScript stack (React, Node.js, TypeScript), cloud platforms (AWS, Azure, Google Cloud), and microservices architectures, and they run dedicated senior outstaffed teams alongside full-cycle product engagements covering discovery, design, development, QA, and DevOps.

If your team would rather hire the practice of building reliable, well-instrumented backend services than learn it the hard way during a stalled-workflow incident, Yojji is worth a conversation.