Video in progress

Financial tables need the history of every change. Which do you choose: a trigger, application-level audit, or CDC?

A trigger never misses a write but doesn't know the context; Envers is rich in context but doesn't see native SQL; CDC is asynchronous. In finance I combine a trigger with context supplied by the application (SET LOCAL).

📖 Answer

The main question: if someone runs a manual UPDATE through psql, should it show up in the history? In finance the answer is almost always "yes". Then application-level audit alone isn't enough.

The trigger variant, with context:

CREATE TABLE account_history (
  id bigserial PRIMARY KEY,
  account_id bigint NOT NULL,
  op char(1) NOT NULL,
  old_row jsonb, new_row jsonb,
  changed_by text NOT NULL DEFAULT current_setting('app.user', true),
  request_id text DEFAULT current_setting('app.request_id', true),
  changed_at timestamptz NOT NULL DEFAULT now()
);

On every transaction the application runs SET LOCAL app.user = ...; if someone comes in by hand without setting it, changed_by has no value and the NOT NULL stops the change, which is a signal too. The trigger writes to_jsonb(OLD) and to_jsonb(NEW).

The comparison:

  • Trigger: atomic, can't be bypassed. The cost: every write is doubled, the history table grows fast (it needs partitioning), and the trigger hides logic.
  • Hibernate Envers: easy to set up, with revisions, but native SQL, bulk UPDATEs and other services are left out.
  • CDC (Debezium): no extra load on the main transaction, and the history can be kept in a separate store. But it's asynchronous: there's a window of "the change happened, the audit isn't there yet", and if a slot is lost, a hole appears in the history. For a regulator's requirements, that's a risk.

Another option is to design the data to be immutable from the start: don't UPDATE the balance, only add ledger entries. Then the "history" is the primary data itself, and audit is needed only for context.

The application role gets only the INSERT privilege on the history table, with no UPDATE/DELETE.