# Enforce the license lifecycle in Postgres


A support ticket that should be impossible: a customer whose license you revoked three weeks ago for a chargeback is activating seats again. The signature verifies, the key is in the database, and its status column says `active`. Someone — or something — set it back. You revoked it; you have the audit row that says so; and yet here it is, live.

Trace it and the cause is mundane. A renewal job read the key, saw a paid invoice, and wrote `status = 'active'` without checking what the status *was*. For a key mid-renewal that is correct. For a revoked key it is a resurrection. The bug is not in the revoke path and not in the renewal path — each is fine alone. The bug is that nothing in the system knew that **`revoked` is terminal**, so no transition out of it is ever legal.

A license is not a flag. It is a small state machine — `issued`, `active`, `suspended`, `revoked`, `expired` — with a fixed set of legal edges between those states. The real question is where that machine lives. If it lives only in the service code, then every code path that writes the status column has to remember every rule, and the day one of them forgets, a revoked key comes back to life. This article is about pushing the machine down into Postgres itself, so that an illegal transition is not a bug you hope to avoid — it is a write the database refuses.

## The states and the legal edges

Start by naming the states and drawing the only transitions you will ever allow.

<figure class="my-8">
<svg viewBox="0 0 700 300" role="img" aria-label="License lifecycle state machine: issued goes to active or expired; active goes to suspended, revoked or expired; suspended goes back to active or on to revoked or expired; revoked and expired are terminal with no outgoing edges." xmlns="http://www.w3.org/2000/svg" style="max-width:700px;width:100%;height:auto;font-family:system-ui,sans-serif">
  <defs><marker id="a" markerWidth="9" markerHeight="9" refX="8" refY="3" orient="auto"><path d="M0,0 L8,3 L0,6 Z" fill="#64748b"/></marker></defs>
  <ellipse cx="90" cy="150" rx="56" ry="30" fill="#6366f1" opacity="0.14" stroke="#6366f1"/>
  <text x="90" y="155" fill="#6366f1" font-size="14" font-weight="600" text-anchor="middle">issued</text>
  <ellipse cx="290" cy="90" rx="56" ry="30" fill="#0891b2" opacity="0.14" stroke="#0891b2"/>
  <text x="290" y="95" fill="#0891b2" font-size="14" font-weight="600" text-anchor="middle">active</text>
  <ellipse cx="290" cy="230" rx="56" ry="30" fill="#0891b2" opacity="0.14" stroke="#0891b2"/>
  <text x="290" y="235" fill="#0891b2" font-size="14" font-weight="600" text-anchor="middle">suspended</text>
  <ellipse cx="560" cy="90" rx="56" ry="30" fill="#ef4444" opacity="0.14" stroke="#ef4444"/>
  <text x="560" y="95" fill="#b91c1c" font-size="14" font-weight="600" text-anchor="middle">revoked</text>
  <ellipse cx="560" cy="230" rx="56" ry="30" fill="#64748b" opacity="0.16" stroke="#64748b"/>
  <text x="560" y="235" fill="#475569" font-size="14" font-weight="600" text-anchor="middle">expired</text>
  <line x1="144" y1="135" x2="238" y2="100" stroke="#64748b" stroke-width="1.5" marker-end="url(#a)"/>
  <text x="188" y="108" fill="#475569" font-size="11" text-anchor="middle">activate</text>
  <line x1="290" y1="120" x2="290" y2="198" stroke="#64748b" stroke-width="1.5" marker-end="url(#a)"/>
  <text x="330" y="163" fill="#475569" font-size="11" text-anchor="middle">suspend</text>
  <line x1="252" y1="208" x2="252" y2="120" stroke="#64748b" stroke-width="1.5" marker-end="url(#a)"/>
  <text x="214" y="163" fill="#475569" font-size="11" text-anchor="middle">resume</text>
  <line x1="346" y1="90" x2="502" y2="90" stroke="#64748b" stroke-width="1.5" marker-end="url(#a)"/>
  <text x="424" y="82" fill="#b91c1c" font-size="11" text-anchor="middle">revoke</text>
  <line x1="340" y1="106" x2="508" y2="216" stroke="#64748b" stroke-width="1.5" marker-end="url(#a)"/>
  <text x="430" y="150" fill="#475569" font-size="11" text-anchor="middle">expire</text>
  <text x="560" y="150" fill="#b91c1c" font-size="11" text-anchor="middle" font-style="italic">terminal</text>
  <text x="560" y="286" fill="#475569" font-size="11" text-anchor="middle" font-style="italic">terminal</text>
</svg>
<figcaption class="text-sm text-muted mt-2">The whole lifecycle: five states, a handful of legal edges, and two terminal states that nothing leaves. Every edge the service is allowed to take is one arrow here; every arrow the diagram does not draw is a transition Postgres must refuse.</figcaption>
</figure>

The shape that matters is the two terminal states on the right. A `revoked` or `expired` license has **no outgoing edges**. Once a row reaches either, every future write to its status is illegal, including the plausible-looking `active` that the renewal job tried. If the database knows that, the resurrection bug cannot happen regardless of what the service does.

## Model the status as an enum, not a string

First, make the column unable to hold a nonsense value at all. A free-text `status` column will happily store `'actve'` or `'cancelled'`; an enum type will not compile a typo.

```sql
CREATE TYPE license_status AS ENUM
    ('issued', 'active', 'suspended', 'revoked', 'expired');

ALTER TABLE licenses
    ADD COLUMN status license_status NOT NULL DEFAULT 'issued';
```

That closes the set of values. It does not yet say anything about *order* — the enum lets you jump from `revoked` straight to `active`, because an enum is a set, not a graph. The legal edges live in a separate, data-driven table.

```sql
CREATE TABLE license_transitions (
    from_status license_status NOT NULL,
    to_status   license_status NOT NULL,
    PRIMARY KEY (from_status, to_status)
);

INSERT INTO license_transitions (from_status, to_status) VALUES
    ('issued',    'active'),
    ('issued',    'expired'),
    ('active',    'suspended'),
    ('active',    'revoked'),
    ('active',    'expired'),
    ('suspended', 'active'),
    ('suspended', 'revoked'),
    ('suspended', 'expired');
```

This table *is* the diagram above, as rows. There is no `('revoked', 'active')` row and no `('expired', *)` row, so those transitions are simply absent. Keeping the edges as data rather than as branches in a trigger means the allowed lifecycle is something you can read, diff in a migration, and reason about without parsing procedural code.

## The trigger that refuses an illegal edge

Now wire a `BEFORE UPDATE` trigger that consults the table on every status change and aborts the write if the edge is not present.

```sql
CREATE OR REPLACE FUNCTION enforce_license_transition()
RETURNS trigger AS $$
BEGIN
    -- Nothing to check if the status is not changing.
    IF NEW.status = OLD.status THEN
        RETURN NEW;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM license_transitions
        WHERE from_status = OLD.status
          AND to_status   = NEW.status
    ) THEN
        RAISE EXCEPTION
            'illegal license transition % -> %', OLD.status, NEW.status
            USING ERRCODE = '23514';   -- check_violation
    END IF;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_license_transition
    BEFORE UPDATE OF status ON licenses
    FOR EACH ROW
    EXECUTE FUNCTION enforce_license_transition();
```

Three details carry the weight. The early `RETURN NEW` when the status is unchanged means ordinary updates — bumping a seat count, writing a last-seen timestamp — never pay for the check. The `EXISTS` lookup is a single indexed hit on an eight-row table. And the `RAISE` reuses the standard `check_violation` SQLSTATE `23514`, so the error arrives at the service as a recognisable, typed failure rather than a generic one. The renewal job that tried `revoked -> active` now does this:

```
ERROR:  illegal license transition revoked -> active
```

The transaction rolls back. The status column is untouched. The resurrection is not logged-and-recovered; it never happened.

## Catching it in the issuing service

The service still owns the domain model — it should reject the transition before it ever reaches the database, with a clean error. But it treats the trigger as the authority of last resort, and maps the database's refusal to the same business outcome.

```csharp
public async Task<LicenseState> TransitionAsync(
    Guid licenseId, LicenseStatus target, CancellationToken ct)
{
    try
    {
        var row = await _db.Licenses
            .Where(l => l.Id == licenseId)
            .ExecuteUpdateAsync(s => s.SetProperty(l => l.Status, target), ct);

        return LicenseState.From(target);
    }
    catch (PostgresException ex) when (ex.SqlState == "23514")
    {
        // The database refused the edge. This is a defined business
        // outcome, not a server fault — surface it as 409, not 500.
        throw new InvalidLicenseTransitionException(licenseId, target, ex.MessageText);
    }
}
```

The `InvalidLicenseTransitionException` becomes an RFC 9457 problem response, so a client or an operator sees *why* the write was refused rather than a stack trace.

```json
{
  "type": "https://keyright/problems/invalid-license-transition",
  "title": "The license cannot move to that state",
  "status": 409,
  "detail": "illegal license transition revoked -> active",
  "retryable": false
}
```

`retryable: false` is the contract that matters to the SDK. A revoked key will never legally become active, so the client must not retry — it surfaces the license's current state and fails closed. That is the opposite of a concurrency conflict, which *is* retryable; conflating the two is the usual mistake.

## Where this guard ends

Be honest about its edges. The trigger protects the `status` column of the `licenses` table and nothing else. If you hold lifecycle state redundantly somewhere — a cached `is_active` boolean, a denormalised copy in another service — the trigger does not reach it, and you have reintroduced the chance to disagree with yourself. Keep status single-sourced.

The whitelist and the service's own state machine must agree. If you add a `('suspended', 'issued')` edge in code but not in the table, the database will reject a transition your service believes is legal, and vice versa. Treat the `license_transitions` rows as the single definition and derive tests from them, so a drift shows up as a failing test rather than a production surprise.

And the guard is about *legality of the edge*, not *authority to take it*. The trigger will happily allow `active -> revoked` for anyone who can issue the UPDATE; whether a given caller is allowed to revoke a license is an authorization question that stays in the service. The database answers "is this edge in the graph?"; it does not answer "should this actor be allowed to walk it?"

## Takeaways

- A license is a state machine, not a flag; model the states as a Postgres enum and the legal edges as rows in a transition table.
- A `BEFORE UPDATE` trigger that rejects any edge absent from that table makes an illegal transition — a revoked key going back to `active` — a write the database refuses, no matter which code path issued it.
- Reuse SQLSTATE `23514` so the service recognises the refusal and maps it to a `409 invalid-license-transition` with `retryable: false`, not a `500`.
- The guard costs nothing on the read-heavy verification path and microseconds on the rare status write, because it only fires when the status actually changes.
- It is defence in depth, not a replacement for the service's own checks or its authorization — keep status single-sourced and keep the whitelist and the code in agreement.

Correctness here is not about remembering the rule in every code path. It is about writing the rule down once, as data the database enforces, so that the code paths you have not written yet are bound by it too. Keyright models the lifecycle this way so that "revoked is forever" is a property of the schema, not a promise made by the latest commit.

