惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
Finite State Machines for Backend Workflow Orchestration
The Practica · 2026-06-07 · via The Practical Developer

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.