PostgreSQL Audit Logging: Triggers, CDC, and pgAudit

Compare PostgreSQL triggers, logical decoding, and pgAudit for tracking order updates, including event fields, rollback behavior, ordering, and capture limits.

published: reading time: 9 min read author: Geek Workbench updated: November 5, 2026
Quick Summary

Track PostgreSQL order status changes with triggers, logical decoding, or pgAudit. Compare what each records, how transactions and rollbacks affect events, and what ordering and replay limits to plan for.

PostgreSQL Audit Logging: Triggers, CDC, and pgAudit

Scope and example

This guide follows one PostgreSQL 18 workload: a checkout service changes order 42 from pending to paid. The database team needs to know which row changed, what field changed, and which application identity submitted the transaction.

A row trigger, logical decoding, and pgAudit answer different questions. A trigger can store old and new row values in the same transaction. Logical decoding streams committed changes from the write-ahead log (WAL). pgAudit records configured SQL statements in PostgreSQL’s server log, including reads that row-change capture does not see.

This page covers database capture. For identity and accountability across applications, infrastructure, storage, access review, and retention, see Audit Trails: Building Complete Data Accountability.

The examples target PostgreSQL 18. PostgreSQL’s trigger, logical decoding, and event-trigger behavior was checked against the PostgreSQL 18 documentation on 2026-11-05. The pgAudit project maps its 18.x branch to PostgreSQL 18; confirm the matching branch and installation instructions for the server you run.

Define the event first

Choose fields that let an investigator follow this one order change. Keep a field allowlist: copying whole rows can put credentials, payment data, or personal details into another store.

Field Meaning
event_id Unique row identifier in the trigger table; sequence gaps are possible after rollbacks.
captured_at Time the database capture code ran, not necessarily the transaction commit time.
transaction_id PostgreSQL transaction ID, useful for grouping changes from one transaction.
table_name, operation, primary_key The changed relation, operation, and row identity.
before, after Allowlisted values relevant to the investigation, such as the old and new order status.
actor_id Application identity supplied by the trusted service, when available.
database_role, application_name Database session context; these do not necessarily identify the person using the application.
source_position WAL location or connector offset when the event came from CDC; a row trigger does not have this value.

A normalized trigger event might look like this:

{
  "event_id": 8127,
  "captured_at": "2026-11-05T08:42:13.451Z",
  "transaction_id": "9014",
  "table_name": "public.orders",
  "operation": "UPDATE",
  "primary_key": { "id": 42 },
  "before": { "status": "pending" },
  "after": { "status": "paid" },
  "actor_id": "customer-123",
  "database_role": "checkout_app",
  "application_name": "checkout",
  "source_position": null
}

The same field names can help downstream consumers, but pgAudit produces a statement event rather than a row event. Keep its SQL text and session fields in their own event type; do not invent old/new row values that it never captured.

Option 1: a row trigger

Use a row trigger when the audit row must commit or roll back with the order update. The example records only changes to orders.status.

CREATE TABLE order_audit_event (
    event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    captured_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    transaction_id text NOT NULL,
    table_name text NOT NULL,
    operation text NOT NULL CHECK (operation = 'UPDATE'),
    order_id bigint NOT NULL,
    before_data jsonb NOT NULL,
    after_data jsonb NOT NULL,
    actor_id text,
    database_role name NOT NULL,
    application_name text
);

CREATE OR REPLACE FUNCTION audit_order_status()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
    INSERT INTO order_audit_event (
        transaction_id,
        table_name,
        operation,
        order_id,
        before_data,
        after_data,
        actor_id,
        database_role,
        application_name
    )
    VALUES (
        pg_current_xact_id()::text,
        TG_TABLE_SCHEMA || '.' || TG_TABLE_NAME,
        TG_OP,
        NEW.id,
        jsonb_build_object('status', OLD.status),
        jsonb_build_object('status', NEW.status),
        NULLIF(current_setting('app.actor_id', true), ''),
        session_user,
        NULLIF(current_setting('application_name', true), '')
    );

    RETURN NULL;
END;
$$;

CREATE TRIGGER orders_status_audit
AFTER UPDATE OF status ON public.orders
FOR EACH ROW
WHEN (OLD.status IS DISTINCT FROM NEW.status)
EXECUTE FUNCTION audit_order_status();

The application sets its actor context inside the same transaction as the write:

BEGIN;
SELECT set_config('app.actor_id', 'customer-123', true);
UPDATE public.orders SET status = 'paid' WHERE id = 42;
COMMIT;

The third argument to set_config makes the setting local to the transaction, so it resets at transaction end. Treat app.actor_id as context supplied by the application, not as proof of identity: a role allowed to issue SQL can set a custom value itself. session_user records the database login, which may be a shared connection-pool role.

PostgreSQL runs a trigger as part of the statement’s transaction. If the order update commits, its audit row commits too. If the transaction rolls back, both are discarded. If the trigger insert fails, the order update fails with it. That is useful when an audit row is required for every status change, but it adds work to the write path.

A row trigger sees table changes made by its configured DML events. It does not see a SELECT or ordinary DDL. PostgreSQL event triggers handle selected DDL events at database scope, but they are a separate mechanism and do not provide row snapshots; see the PostgreSQL 18 event-trigger docs. Privileged owners can also alter or disable triggers and change the audit table, so this pattern alone does not make records tamper-proof.

Option 2: logical decoding and CDC

PostgreSQL logical decoding reads persistent changes from WAL and exposes them through an output plugin. A replication slot gives a consumer a change stream for one database. For the same order update, a CDC connector can emit the changed row and transaction metadata without running a trigger function for every row.

Logical decoding is transaction-aware. PostgreSQL decodes concurrent transactions in commit order; transactions rolled back explicitly or implicitly are not decoded. Configure REPLICA IDENTITY deliberately: the old row version for an update or delete depends on that setting. The new row version is available to the output plugin. See the PostgreSQL 18 logical decoding overview, output-plugin transaction callbacks, and logical replication message formats.

CDC does not provide a complete audit record by itself. It does not capture SELECT statements, application reasons, or an authenticated end-user identity unless the application stored that context in the changed data or another correlated event. The basic row stream also does not turn DDL into row events; schema-change handling depends on the connector or output plugin.

Plan for replay. A logical slot can resend recent changes after a crash because its persisted position may move back to an earlier checkpoint. Make the consumer idempotent and use the connector’s stable source-position metadata for deduplication. Monitor slot lag and retained WAL: an abandoned slot can prevent required WAL from being removed and consume disk.

CDC fits when several systems need the same committed change stream or trigger work would make the write transaction too expensive. It moves delivery outside the order transaction, so the database commit can succeed while the consumer is delayed or unavailable. Your audit store is only current through the latest event it has received and applied.

Option 3: pgAudit

pgAudit logs configured database statements through PostgreSQL’s standard logging facility. For this workload, read can record SELECT statements and write can record the UPDATE; ddl covers configured DDL activity. Session logging applies by statement class, while object auditing can target relations with supported commands. The pgAudit project documentation describes these modes and maps pgAudit 18.x to PostgreSQL 18.

A pgAudit entry can identify the database session, command class, relation, and statement text, depending on settings. It does not provide the previous and resulting row values. Statement parameters can also expose sensitive data if parameter logging is enabled, so check log configuration and access before turning it on broadly.

pgAudit is best-effort and not transactional. A statement may be logged even if its transaction later rolls back. Conversely, PostgreSQL’s logging facility does not synchronously flush each audit entry as part of the database commit or fail the SQL session if the log write fails. A committed order update can therefore lack a durable pgAudit record. Use it to answer questions about statements and sessions, not as a same-transaction row-change ledger.

Compare the three for the order update

Question Row trigger Logical decoding / CDC pgAudit
What does it record? Selected row changes, including allowlisted old/new fields. Row changes from WAL; old values depend on replica identity. Configured statements and session/object details.
What happens on rollback? The audit row rolls back with the order update. Rolled-back transactions are not decoded as committed changes. The statement may still appear in the server log.
When can a reader see it? After the transaction commits. After commit and after the consumer catches up. As the server log is written and shipped.
Does it capture reads? No. No. Yes, when read or object-audit settings cover them.
Does it capture DDL? Not a row trigger; event triggers are a separate PostgreSQL feature. Not as ordinary row changes; plugin-specific behavior may add schema events. Yes, when ddl logging is configured.
Main operational cost Synchronous trigger work and per-table maintenance. Slot, WAL, connector, and consumer operations. Server-log volume, storage, and sensitive statement text.

For this order-status requirement, a trigger is the direct choice if a failed audit insert must block the status update. Choose CDC when downstream consumers need committed changes and can tolerate delivery lag and replay. Add pgAudit when the investigation also needs statement or read activity. Combining them can cover distinct questions, but it does not create one universal guarantee: document which source answers which question.

Ordering and retention boundaries

Do not use captured_at or an identity sequence as a global commit order. A trigger timestamp is taken while the transaction is running, and identity values can have gaps after rollback. The trigger table groups events by transaction ID but does not include a commit LSN. For commit ordering across transactions, CDC exposes source transaction order and log positions. Downstream parallel processing can still reorder events unless the consumer preserves the order it needs, such as serializing updates for a given order ID.

Retention, access review, cross-system identity, and tamper-evident storage are organization-wide controls. Decide those separately from the database capture method. Audit Trails: Building Complete Data Accountability covers those choices and how to correlate records across systems.

Further reading

Conclusion

Triggers, CDC, and pgAudit capture different evidence. For an order status change that must have a matching row record at commit, a trigger writes the record in the same transaction. CDC gives downstream systems a transaction-ordered stream, with replay and lag to handle. pgAudit records configured SQL activity, but it cannot replace row snapshots or a transactional audit table.

Start from the question an investigation must answer, then choose the capture path whose transaction and ordering guarantees match it.

Category

Related Posts

Data Masking Strategies for Non-Production Environments

Learn static and dynamic data masking: nulling, shuffling, hashing, and range techniques. Understand GDPR and PII considerations for PostgreSQL and Oracle.

#database #data-masking #security

Encryption at Rest: TDE, Key Management, and Performance

Compare storage encryption, database TDE, and application encryption. Review threat boundaries, key management, and a practical performance benchmark plan.

#database #encryption #security

GDPR Engineering Patterns for Database Systems

Engineering patterns for GDPR data requests, backups, consent, processors, and breach response, with legal scope and implementation limits.

#database #gdpr #compliance