sqitchcraft

Lifecycles

An invoice is drafted, sent, perhaps overdue, then paid or voided. Each step has rules about where it may go next and work that must happen on the way. This page shows why we let PostgreSQL run that lifecycle as a statechart, using a small example project and its real output.

Everything below ran against PostgreSQL 18 with pg_statecharts 0.2.0 at SERIALIZABLE, deployed with sqitch. Long queries are wrapped, and psql's row counts are left out.

The status column

The usual model is a column and a check constraint:

status text not null default 'draft'
    check (status in ('draft', 'sent', 'overdue', 'paid', 'voided'))

The constraint knows which values exist. It does not know which moves are allowed, so every writer has to. The checkout service marks an invoice paid, the back office voids one, a nightly job marks the late ones overdue, a worker sends reminders. Each of them carries its own copy of the rules, and the bugs are in the gaps between the copies:

None of these is hard to fix once. The trouble is that the rules have no home, so they are fixed once per writer.

The lifecycle as a chart

A statechart gives the rules a home. It is a state machine with nesting: a state can contain states, and a transition on the outer state applies whichever inner state the machine is in. Here is the invoice:

invoice_flow: draft goes to open on issue. Open contains awaiting_payment, which goes to overdue when the due date passes. Open goes to paid on pay and to voided on void. Draft can also be voided. open draft awaiting_payment overdue paid voided issue due_date_passed pay void void
Thick borders are final states. pay and void leave open from whichever state inside it is active.

database/statecharts/invoice_flow-1.0.scxml

<scxml xmlns="http://www.w3.org/2005/07/scxml"
       name="invoice_flow" version="1.0.0" initial="draft">

  <state id="draft">
    <transition event="invoice.issue" target="open"/>
    <transition event="invoice.void"  target="voided"/>
  </state>

  <!-- Sent and not yet paid. pay and void are defined once, here, and work
       from every state inside open. -->
  <state id="open">
    <initial><transition target="awaiting_payment"/></initial>
    <onentry><script src="billing.send_invoice"/></onentry>
    <onexit><script src="billing.cancel_reminders"/></onexit>
    <transition event="invoice.pay"  target="paid"/>
    <transition event="invoice.void" target="voided"/>

    <state id="awaiting_payment">
      <transition event="invoice.due_date_passed" target="overdue"/>
    </state>
    <state id="overdue">
      <onentry><script src="billing.queue_reminder"/></onentry>
    </state>
  </state>

  <final id="paid">
    <onentry><script src="billing.settle_invoice"/></onentry>
  </final>
  <final id="voided">
    <onentry><script src="billing.void_invoice"/></onentry>
  </final>
</scxml>

Read it as the answer to the four bugs. There is no transition out of voided or paid, so nothing pays a voided invoice. Leaving open cancels reminders, whichever event leaves it. pay is written once, on open, so adding a state inside open later (say, disputed) needs no new payment transition. The format is W3C SCXML, so the chart can be drawn by tools that are not ours.

What each state does

The onentry and onexit scripts are ordinary PostgreSQL functions. Each one takes an fsm_event_payload (the machine, the event and its data, the states it moves from and to) and finds its invoice by the machine's id. Emails go to billing_email, a pgmq queue in the same database:

database/deploy/billing/function/invoice_callbacks.sql

-- on_entry of open: the invoice goes out.
create or replace function billing.send_invoice(event_payload fsm_event_payload)
    returns void as
$$
    update billing.invoice
    set issued_at = now()
    where state_machine_id = (event_payload).machine_id;

    select pgmq.send('billing_email', jsonb_build_object('invoice_id', id, 'kind', 'invoice'))
    from billing.invoice
    where state_machine_id = (event_payload).machine_id;
$$ language sql;

-- on_entry of overdue: remind the customer, and keep the message's id.
create or replace function billing.queue_reminder(event_payload fsm_event_payload)
    returns void as
$$
    update billing.invoice
    set reminder_msg_id = (select pgmq.send('billing_email',
            jsonb_build_object('invoice_id', id, 'kind', 'reminder')))
    where state_machine_id = (event_payload).machine_id;
$$ language sql;

-- on_exit of open, however it is left: a reminder still in the queue
-- must not go out now.
create or replace function billing.cancel_reminders(event_payload fsm_event_payload)
    returns void as
$$
    select pgmq.delete('billing_email', reminder_msg_id)
    from billing.invoice
    where state_machine_id = (event_payload).machine_id
      and reminder_msg_id is not null;
$$ language sql;

-- settle_invoice and void_invoice follow the same pattern.
StateOn entryOn exit
openset issued_at, queue the invoice emaildelete a queued reminder
overduequeue a reminder
paidset settled_at, queue a receipt
voidedset voided_at

Two habits keep callbacks cheap and queries plain:

create-migration function statechart writes a callback's skeleton with the payload already unpacked.

The email queue

The queue is pgmq, a message queue built from PostgreSQL tables. Its messages are rows, so they commit or roll back with the event that queued them, and a callback can delete one it queued earlier, as cancel_reminders does. A plain outbox table with a sent_at column would work as well; pgmq adds what the worker would otherwise write itself: visibility timeouts, retries and an archive. The queue is a change of its own:

database/deploy/billing/queue/email.sql

-- A worker reads each email, sends it, then archives the message.
select pgmq.create('billing_email');

After invoice 1 is issued, goes overdue and is paid (below), the worker reads:

=# select msg_id, message from pgmq.read('billing_email', vt => 30, qty => 10);
 msg_id |               message
--------+--------------------------------------
      1 | {"kind": "invoice", "invoice_id": 1}
      3 | {"kind": "receipt", "invoice_id": 1}

Message 2, the reminder, was deleted when the payment left open. The worker sends each email and then calls pgmq.archive; a message it does not archive within 30 seconds is read again. A reminder the worker is sending at that moment can still go out. pgmq is pure SQL, like pg_statecharts, so it installs wherever pg_statecharts does.

One invoice, start to finish

Inserting an invoice creates its machine and starts it in draft (two triggers, below). From then on, the application changes the invoice's state only by sending events, through one function, billing.invoice_event, which returns the states the machine is in afterwards:

=# insert into billing.invoice (customer_email, amount, due_on)
   values ('ana@example.com', 120.00, current_date + 14)
   returning id, state_machine_id;
 id | state_machine_id
----+------------------
  1 |                1

=# select billing.invoice_event(1, 'invoice.issue');
     invoice_event
-----------------------
 awaiting_payment/open

=# select billing.invoice_event(1, 'invoice.due_date_passed');
 invoice_event
---------------
 open/overdue

=# select msg_id, message->>'kind' as kind
   from pgmq.q_billing_email
   where message->>'invoice_id' = '1' order by msg_id;
 msg_id |   kind
--------+----------
      1 | invoice
      2 | reminder

pgmq keeps a queue's messages in a table, pgmq.q_billing_email. Entering open queued the invoice email; entering overdue queued a reminder, which the worker has not sent yet. Now the customer pays:

=# select billing.invoice_event(1, 'invoice.pay');
 invoice_event
---------------
 paid

=# select msg_id, message->>'kind' as kind
   from pgmq.q_billing_email
   where message->>'invoice_id' = '1' order by msg_id;
 msg_id |  kind
--------+---------
      1 | invoice
      3 | receipt

=# select issued_at is not null as issued, settled_at is not null as settled
   from billing.invoice where id = 1;
 issued | settled
--------+---------
 t      | t

pay was defined on open and worked from overdue. Leaving open deleted the reminder from the queue, so the customer gets a receipt and not a reminder for an invoice they just paid. No payment code had to know reminders exist.

Late and duplicate events

Events arrive late and more than once. The payment provider retries a webhook it thinks we missed; the back office voids an invoice the customer paid a minute earlier. Invoice 1 is paid, and gets both:

=# select billing.invoice_event(1, 'invoice.pay');
 invoice_event
---------------
 paid

=# select billing.invoice_event(1, 'invoice.void');
 invoice_event
---------------
 paid

=# select msg_id, message->>'kind' as kind
   from pgmq.q_billing_email
   where message->>'invoice_id' = '1' order by msg_id;
 msg_id |  kind
--------+---------
      1 | invoice
      3 | receipt

=# select name, to_char(created_at, 'HH24:MI:SS.MS') as received
   from fsm.state_machine_event
   where state_machine_id = (select state_machine_id from billing.invoice where id = 1)
   order by id;
          name           |   received
-------------------------+--------------
 invoice.issue           | 08:36:54.019
 invoice.due_date_passed | 08:36:54.024
 invoice.pay             | 08:36:54.027
 done.state.paid         | 08:36:54.027
 invoice.pay             | 08:36:54.030
 invoice.void            | 08:36:54.031

Neither changed anything. paid has no transitions, so no active state accepts either event: the invoice stays paid, no callback runs, and the customer gets one receipt, not two. Both calls succeed, and both events are in the log with the time they arrived.

That is the behaviour we want. A late or repeated event is normal traffic, not a mistake, and raising an error for it would only make every caller catch and ignore it. The webhook handler does not check whether the invoice is already paid, and the void button does not check whether it still can: each sends its event, and the chart decides. A caller that needs to know what happened reads the states the call returns.

The application sends events through one function per entity, which finds the machine from the invoice and returns its states afterwards:

database/deploy/billing/function/invoice_event.sql

create or replace function billing.invoice_event(invoice_id bigint, event text)
    returns text as
$$
    declare
        machine bigint;
        current_state text;
    begin
        select state_machine_id into machine
        from billing.invoice
        where id = invoice_id;

        if machine is null then
            raise exception 'invoice % does not exist', invoice_id;
        end if;

        -- An event no active state accepts changes nothing: a webhook
        -- delivered twice, or a void that arrives after the payment. The
        -- engine logs it and moves on, and so does this.
        perform fsm.notify_state_machine(machine_id => machine, event_name => event);

        select string_agg(state_id, '/' order by entered_at) into current_state
        from fsm.state_machine_state
        where state_machine_id = machine and exited_at is null;

        return current_state;
    end
$$ language plpgsql;

An invoice that does not exist is still an error: that is a bug in the caller, not a late event.

One transaction

The transition, its callbacks and everything else the caller did run in one transaction. Pay an invoice and then roll back, the way a failed payment request would:

=# begin;
=# select billing.invoice_event(2, 'invoice.pay');
 invoice_event
---------------
 paid

=# select settled_at is not null as settled from billing.invoice where id = 2;
 settled
---------
 t

=# rollback;
=# select fsm.is_state_active(machine_id => state_machine_id, state_id => 'open') as open,
          settled_at is not null as settled,
          (select count(*) from pgmq.q_billing_email q
           where q.message->>'invoice_id' = '2' and q.message->>'kind' = 'receipt') as receipts
   from billing.invoice where id = 2;
 open | settled | receipts
------+---------+----------
 t    | f       |        0

The machine is back in open, settled_at is empty again, and no receipt is waiting to be sent. With a state service outside the database, this is the dual-write problem: the service says paid, the database says not, and someone writes a reconciliation job. Here the state is data in the same transaction, so there is nothing to reconcile.

Two requests at once

Statecharts needs every transaction that sends events to run at REPEATABLE READ or SERIALIZABLE; we run them all at SERIALIZABLE. The engine reads a machine's active states and then moves it, without a lock of its own, and the isolation level is what makes two events for one machine safe. We ran the race both ways: session A pays invoice 1 and keeps its transaction open for two seconds, and half a second in, session B voids it.

At SERIALIZABLE, session B waits for A, then fails, and its retry starts from what A committed:

=# select billing.invoice_event(1, 'invoice.void');   -- session B
ERROR:  could not serialize access due to concurrent update
Time: 1510.915 ms (00:01.511)

=# select billing.invoice_event(1, 'invoice.void');   -- session B, retried
 invoice_event
---------------
 paid

The retry is a late event like the ones above: it changes nothing, and the invoice is paid, and only paid. At READ COMMITTED, PostgreSQL's default, the same two events both go through:

=# select state_id from fsm.state_machine_state
   where state_machine_id = 1 and exited_at is null;
 state_id
----------
 paid
 voided

=# select settled_at is not null as settled, voided_at is not null as voided
   from billing.invoice where id = 1;
 settled | voided
---------+--------
 t       | t

Both sessions started from open, so the invoice is paid and voided at once, with both callbacks run.

Send events only from SERIALIZABLE transactions, and retry the ones that fail with SQLSTATE 40001. REPEATABLE READ is the minimum. Set it on the role the application connects as, so no code path can forget it:

alter role app
    set default_transaction_isolation = 'serializable';

A client that already retries serialization failures needs nothing else.

The history

Every state a machine enters is a row in fsm.state_machine_state, closed when it is left. Invoice 1's life:

=# select state_id, to_char(entered_at, 'HH24:MI:SS.MS') as entered,
                    to_char(exited_at, 'HH24:MI:SS.MS') as exited
   from fsm.state_machine_state
   where state_machine_id = (select state_machine_id from billing.invoice where id = 1)
   order by entered_at, state_id;
     state_id     |   entered    |    exited
------------------+--------------+--------------
 draft            | 08:36:54.014 | 08:36:54.022
 awaiting_payment | 08:36:54.019 | 08:36:54.026
 open             | 08:36:54.019 | 08:36:54.028
 overdue          | 08:36:54.024 | 08:36:54.028
 paid             | 08:36:54.027 |

Nobody wrote an audit table, and it cannot drift from the state, because it is the state: the current states are the rows with no exited_at. Questions that used to need an analytics pipeline are one query:

-- How long do invoices stay overdue before they are paid?
select percentile_cont(0.5) within group (order by exited_at - entered_at)
from fsm.state_machine_state o
join fsm.state_machine_state p
  on p.state_machine_id = o.state_machine_id and p.state_id = 'paid'
where o.state_id = 'overdue';

In the repository

The chart is a file next to the definitions, and it reaches the database as an ordinary sqitch change:

database/
├── statecharts/
│   └── invoice_flow-1.0.scxml                 # the chart you edit
├── deploy/
│   ├── billing/
│   │   ├── table/invoice.sql                  # state_machine_id bigint not null unique
│   │   ├── queue/email.sql                    # pgmq.create('billing_email')
│   │   └── function/
│   │       ├── invoice_callbacks.sql          # what each state does
│   │       └── invoice_event.sql              # the wrapper, and the two triggers
│   └── statechart/
│       └── invoice_flow-1.0.0.sql             # generated from the .scxml
└── sqitch.plan

On a development database, the pg_statecharts_dev extension turns the SCXML into that change and appends it to the plan. It reads and writes files on the database server, so it belongs on development machines only:

$ psql -c "create extension if not exists pg_statecharts_dev cascade" \
       -c "select fsm.gen_statechart_sqitch_migrations(
             source_path           => '$PWD/database/statecharts',
             sqitch_plan_file_path => '$PWD/database/sqitch.plan')"
INFO:  created new migration: statechart/invoice_flow-1.0.0

database/deploy/statechart/invoice_flow-1.0.0.sql (generated, abridged)

insert into fsm.statechart (name, version) values ('invoice_flow', fsm.to_semver('1.0.0')) returning id into chart;
insert into fsm.state (statechart_id, id, name, parent_id, is_initial, is_final, on_entry, on_exit) values
(chart, 'draft', '', null, true, false, array[]::fsm_callback_name[], array[]::fsm_callback_name[]),
(chart, 'open', '', null, false, false, array[('billing', 'send_invoice')]::fsm_callback_name[], array[('billing', 'cancel_reminders')]::fsm_callback_name[]),
(chart, 'awaiting_payment', '', 'open', true, false, …),
…
insert into fsm.transition (statechart_id, event, source_state, target_state) values
(chart, 'invoice.issue', 'draft', 'open'),
(chart, 'invoice.void', 'draft', 'voided'),
(chart, 'invoice.pay', 'open', 'paid'),
(chart, 'invoice.void', 'open', 'voided'),
(chart, 'invoice.due_date_passed', 'awaiting_payment', 'overdue');

Its verify script checks that every callback the chart names exists, so the callbacks' change comes first in the plan. The plan for the example:

extension/pg_statecharts
extension/pgmq
billing/schema
billing/table/invoice [billing/schema]
billing/queue/email [extension/pgmq]
billing/function/invoice_callbacks [billing/table/invoice billing/queue/email]
statechart/invoice_flow-1.0.0
billing/function/invoice_event [statechart/invoice_flow-1.0.0]

Each invoice gets its machine from two triggers: a before insert one fills state_machine_id with fsm.create_state_machine_with_latest_statechart(statechart_name => 'invoice_flow'), and an after insert one calls fsm.start_machine, which enters draft and runs its callbacks once the row exists. The whole project deploys, verifies, reverts and deploys again with sqitch.

Changing the chart

A machine runs the chart version it was created with. To change the lifecycle, copy the SCXML to a new version, edit it, and generate again; that adds statechart/invoice_flow-1.1.0 to the plan. Invoices created after the deploy get 1.1; invoices already open stay on 1.0 until they finish. The generated change is never edited and never reworked: a new version is a new change, the way a migration is.

We added a disputed state inside open as version 1.1, with no other change:

$ psql -c "select fsm.gen_statechart_sqitch_migrations(…)"
INFO:  updated existing migration: statechart/invoice_flow-1.0.0
INFO:  created new migration: statechart/invoice_flow-1.1.0
$ git status --short
 M database/sqitch.plan
?? database/deploy/statechart/invoice_flow-1.1.0.sql
?? database/revert/statechart/invoice_flow-1.1.0.sql
?? database/statecharts/invoice_flow-1.1.scxml
?? database/verify/statechart/invoice_flow-1.1.0.sql
$ sqitch deploy
  + statechart/invoice_flow-1.1.0 .. ok

=# select i.id, fsm.semver_text(c.version) as chart
   from billing.invoice i
   join fsm.state_machine m on m.id = i.state_machine_id
   join fsm.statechart c on c.id = m.statechart_id;
 id | chart
----+-------
  1 | 1.0.0
  2 | 1.1.0

=# select billing.invoice_event(2, 'invoice.issue');
 awaiting_payment/open
=# select billing.invoice_event(2, 'invoice.dispute');
 open/disputed
=# select billing.invoice_event(2, 'invoice.pay');
 paid

The 1.0 change was regenerated byte for byte, so git shows it unchanged. Invoice 1 keeps the chart it started with. Invoice 2, created after the deploy, can be disputed, and pay works from disputed without a new transition, because it is defined on open.

Two consequences to plan for:

What it costs

When a status column is enough

A flag that only ever goes from false to true does not need a chart, and neither does a status that nothing reacts to. Statecharts pay for themselves when a lifecycle has moves that must not happen, work attached to its steps, and a history someone will ask about: payments, refunds, orders, onboarding. Start with the entity whose invalid transitions have already cost you an incident.