
5. State Transition Tracking
Finite State Machine Pattern
Concept: Track valid state transitions and maintain history
-- Define valid state transitions
CREATE TABLE state_transitions (
from_state VARCHAR(50) NOT NULL,
to_state VARCHAR(50) NOT NULL,
PRIMARY KEY (from_state, to_state)
);
-- Seed valid transitions for orders
INSERT INTO state_transitions (from_state, to_state) VALUES
('INITIAL', 'created'),
('created', 'payment_pending'),
('payment_pending', 'paid'),
('payment_pending', 'cancelled'),
('paid', 'processing'),
('processing', 'shipped'),
('shipped', 'delivered'),
('delivered', 'completed'),
('paid', 'refunded'),
('processing', 'cancelled');
-- Main entity table
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
order_number VARCHAR(50) UNIQUE NOT NULL,
customer_id BIGINT NOT NULL,
current_state VARCHAR(50) NOT NULL DEFAULT 'created',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- State history table
CREATE TABLE order_state_history (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL REFERENCES orders(id),
from_state VARCHAR(50) NOT NULL,
to_state VARCHAR(50) NOT NULL,
-- Enforce valid transitions
FOREIGN KEY (from_state, to_state)
REFERENCES state_transitions(from_state, to_state),
transitioned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
transitioned_by VARCHAR(100) NOT NULL,
reason TEXT,
metadata JSONB,
-- Ensure transitions are sequential
sort_key INT NOT NULL,
is_current BOOLEAN NOT NULL DEFAULT true,
CONSTRAINT unique_current_per_order
UNIQUE (order_id, is_current) WHERE is_current = true
);
-- Index for querying current state
CREATE INDEX idx_order_state_history_current
ON order_state_history(order_id, is_current)
WHERE is_current = true;
-- Index for timeline queries
CREATE INDEX idx_order_state_history_timeline
ON order_state_history(order_id, sort_key);State Transition Function
CREATE OR REPLACE FUNCTION transition_order_state(
p_order_id BIGINT,
p_to_state VARCHAR(50),
p_user VARCHAR(100),
p_reason TEXT DEFAULT NULL
) RETURNS BOOLEAN AS $$
DECLARE
v_current_state VARCHAR(50);
v_next_sort_key INT;
v_is_valid BOOLEAN;
BEGIN
-- Get current state
SELECT current_state INTO v_current_state
FROM orders
WHERE id = p_order_id
FOR UPDATE; -- Lock row
IF NOT FOUND THEN
RAISE EXCEPTION 'Order not found: %', p_order_id;
END IF;
-- Check if transition is valid
SELECT EXISTS(
SELECT 1 FROM state_transitions
WHERE from_state = v_current_state
AND to_state = p_to_state
) INTO v_is_valid;
IF NOT v_is_valid THEN
RAISE EXCEPTION 'Invalid state transition: % -> %',
v_current_state, p_to_state;
END IF;
-- Get next sort key
SELECT COALESCE(MAX(sort_key), 0) + 1
INTO v_next_sort_key
FROM order_state_history
WHERE order_id = p_order_id;
-- Mark current state as no longer current
UPDATE order_state_history
SET is_current = false
WHERE order_id = p_order_id
AND is_current = true;
-- Insert new state
INSERT INTO order_state_history (
order_id, from_state, to_state, transitioned_by,
reason, sort_key, is_current
) VALUES (
p_order_id, v_current_state, p_to_state, p_user,
p_reason, v_next_sort_key, true
);
-- Update current state on main table
UPDATE orders
SET current_state = p_to_state
WHERE id = p_order_id;
RETURN true;
END;
$$ LANGUAGE plpgsql;Querying State History
-- Get complete timeline for an order
SELECT
from_state,
to_state,
transitioned_at,
transitioned_by,
reason,
sort_key
FROM order_state_history
WHERE order_id = 123
ORDER BY sort_key;
-- Find all orders in a specific state
SELECT o.id, o.order_number, o.current_state
FROM orders o
WHERE o.current_state = 'shipped';
-- Find orders that transitioned through a specific state
SELECT DISTINCT o.id, o.order_number
FROM orders o
JOIN order_state_history h ON o.id = h.order_id
WHERE h.to_state = 'processing';
-- Get duration in each state
SELECT
order_id,
to_state,
transitioned_at,
LEAD(transitioned_at) OVER (PARTITION BY order_id ORDER BY sort_key)
- transitioned_at AS duration_in_state
FROM order_state_history
WHERE order_id = 123
ORDER BY sort_key;Editorial State Changes and Their Audit Rows
The API's editorial lifecycle is a practical state-transition example. A content entry has a current revision pointer, an optional approved revision pointer, and an optional archive timestamp. An edit requires the caller's version to match the current version. It creates the next revision, moves the current pointer, and records an edit audit action. Approval points the entry at its current revision; withdrawal clears the approved pointer; archival clears approval and records the archive time.
These operations run under the PostgreSQL adapter's editorial transaction lock. The lock serializes this API's editorial write workflows, while the transaction keeps the content pointer and audit row in one commit. This protects the sequence from two API writers interleaving those steps.
This model is for editorial content. An order workflow can use different states and permitted transitions, but the same design questions apply: what state is authoritative, which transitions are allowed, how concurrency is controlled, and which actor/action record is written with each transition?
References: PostgreSQL transaction isolation.
Expanded from the supplied audit-log article
Follow a real editorial sequence
Suppose an article has these revisions:
- Revision 1: The first draft.
- Revision 2: An edited draft that is approved.
- Revision 3: New changes that have not been approved yet.

Illustrative editorial workflow: the current revision and approved revision can differ.
At the end of this sequence, the entry may point to current_revision_id = 3 and approved_revision_id = 2.
That difference is important. The editor can continue working without automatically replacing the approved public content. The exact serving behavior still depends on the application's publication rules.
The audit history could describe these operations:
content.create entry=17 actor=editor_42 revision=1
content.edit entry=17 actor=editor_42 revision=2
content.approve entry=17 actor=reviewer_8 revision=2
content.edit entry=17 actor=editor_42 revision=3The revision history answers what changed. The audit history answers who performed the operation and when. Neither should pretend to replace the other.
Further reading
Originally published on DEV Community.


