Capture Design
Hybrid triggers, four-step actor resolution, partitioned history layout, security boundaries, and why WAL replication is deferred.
In v0.1, Auditstream captures every mutation inside PostgreSQL using generated triggers that write to a monthly-partitioned auditstream.changes table.
Trigger strategy
INSERTandDELETEare statement-level using transition tables (REFERENCING NEW TABLE/OLD TABLE). The actor is resolved once per statement instead of once per row — cutting a 10,000-row insert from 541–550 ms down to 155–180 ms.UPDATEstays row-level withWHEN (OLD.* IS DISTINCT FROM NEW.*)so no-op updates write nothing. Measuring a statement-level update showed primary-key changes split into two half-events and 4% slower single-row writes.TRUNCATEuses a dedicatedAFTER TRUNCATE FOR EACH STATEMENTtrigger recording the table and actor.- Excluded columns (such as
password_hash) are stripped before storingbeforeandafter; an update touching only excluded columns writes no audit row.
Actor resolution order
Inside every trigger, PostgreSQL resolves the acting identity in strict precedence order:
nullif(current_setting('auditstream.actor', true), '')— set viaset_config(..., true)inside the current transaction.- Trailing
/*auditstream='<base64url>'*/comment at the end ofright(current_query(), 4096)(last comment, body contains no/, length validated outside the regex because PostgreSQL caps regex repetition counts at 255). - The
subclaim fromrequest.jwt.claims(Supabase and PostgREST callers). NULLactor, recordingdb_user = session_user.
Safety rule: A malformed payload never aborts the application’s write. The change is still recorded with
actor = NULLandactor_source = 'invalid'.
History table (auditstream.changes)
| Column | Type | Purpose |
|---|---|---|
id |
bigint identity |
Insert order (not commit order) |
event_id |
uuid |
Stable deduplication ID for downstream sinks |
occurred_at |
timestamptz |
Monthly partition key + BRIN index |
xact_id |
xid8 |
Default pg_current_xact_id() — lossless export cursor |
source |
text |
db for trigger capture, app for audit.log() |
schema_name, table_name, table_oid |
text, text, oid |
Target relation |
op |
text |
INSERT, UPDATE, DELETE, TRUNCATE, or app action |
record_id |
jsonb |
Primary key values |
before, after |
jsonb |
Row images minus excluded columns |
changed |
text[] |
Keys that differed on UPDATE |
actor, context |
jsonb |
Normalized contract objects |
actor_source |
text |
set_config, comment, jwt, invalid, or NULL |
db_user |
text |
session_user |
schema_version |
smallint |
Table layout version |
Commit-safe xid8 export cursor
Each export reads the safe committed window:
SELECT *
FROM auditstream.changes
WHERE xact_id >= $1
AND xact_id < pg_snapshot_xmin(pg_current_snapshot())
ORDER BY xact_id, id;
In testing, a naive id > last_id cursor lost a row when an earlier transaction committed after a later one. Stopping at pg_snapshot_xmin() guarantees zero missed rows without running a continuous daemon or holding a WAL replication slot.
Security & tamper resistance
- Trigger functions run as
SECURITY DEFINERowned by aNOLOGINrole (auditstream_owner) withSET search_path = pg_catalog, pg_temp. - On PostgreSQL 16+ managed clouds (Neon, Supabase), migrations automatically grant
auditstream_ownerto the non-superuser migration role before creating owned objects. - Application roles get
SELECTonly onauditstream.changes. DirectINSERT,UPDATE, andDELETEattempts are denied by Postgres while application writes continue to be captured.
Why triggers first, and when WAL replication
Logical replication (pgoutput) requires wal_level = logical (and an RDS reboot), REPLICA IDENTITY FULL on every audited table, an always-on consumer whose stalled slot can fill disk, and pg_logical_emit_message(true, 'auditstream', ...) inside explicit transactions to carry actors. Auditstream defers logical replication behind the EventSource trait so teams get production audit trails with zero new infrastructure first.