DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

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.



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.

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.

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

ALTER TABLE licenses
    ADD COLUMN status license_status NOT NULL DEFAULT 'issued';
Enter fullscreen mode Exit fullscreen mode

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.

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');
Enter fullscreen mode Exit fullscreen mode

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.

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();
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

{
  "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
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)