Build comprehensive audit logging systems with Postgres change data capture (CDC).
Audit logs are an essential tool for tracking and recording changes in your database. With Sequin, you can create comprehensive audit logs of changes in your Postgres database to:
Track compliance and security: Meet regulatory requirements by monitoring sensitive data modifications
Debug and recover: Trace change history to investigate issues and recover from unwanted changes
Build user features: Create activity feeds, change history views, and undo/redo functionality
First, create a sink to the queue, stream, or webhook endpoint that you want to use to process changes:
1
Select the source
Select the table or schema you want to audit.Optionally add SQL filters to audit a subset of your source table(s).
2
Select the message type
Leave the default “Changes” message type selected.
3
Leave message grouping default
If your sink supports message grouping, leave the default option selected for “Message grouping”.This will ensure that messages are grouped by primary key, helping eliminate race conditions as you write audit logs.
4
Specify backfill
If you want to snapshot your current rows from your source table into your audit logs, specify a backfill.
To make your audit logs more valuable, use transaction annotations to add context to your changes. For example, you can record who made the change or from where.
1
Update your application code
Modify your database transaction code to include annotations:
BEGIN; -- Set annotations for this transaction SELECT pg_logical_emit_message(true, 'sequin:transaction_annotations.set', '{ "username": "paul.atreides", "source": "web_ui", "request_id": "req_123", "metadata": { "reason": "Customer requested update", "client_ip": "192.168.1.100" } }'); -- Your database operations UPDATE users SET email = 'new@example.com' WHERE id = 'user_123';COMMIT;
These annotations will be included in the change messages for all operations following the annotation statement in this transaction.
Once your sink is configured, changes from your source table will flow to your message queue or HTTP endpoint. Before implementing your audit processor, consider these key requirements for reliable audit logging:
Idempotency: Implement idempotent processing to handle edge cases safely
Duplicates are rare and only occur if your processor successfully writes to the database but fails to acknowledge messages from the queue (SQS/Kafka) or fails to return a 200 status code (HTTP endpoints). In these cases, the message will be redelivered to ensure at-least-once delivery.To protect against duplicates, each message includes an idempotency_key which is intended for use by your application to reject any possible duplicate messages.The idempotency key is available in the message metadata as metadata.idempotency_key. For example, in a change message it would look like:
Type handling: Cast JSON to Postgres typesSequin sends events to your consumer in JSON. Since JSON’s types are not as rich as Postgres’ types, you’ll need to cast values appropriately when writing to your database.Common conversions include:
Timestamps/dates: Cast from strings to timestamp or date
UUIDs: Cast from strings to uuid
Numeric types: Cast to decimal, bigint, etc. based on precision needs
Batch processing: For better performance, batch your database operations.
First, create an audit table to store your change history, including fields for transaction annotations:
create_table.sql
create table audit_logs ( id serial primary key, table_name text not null, record_id uuid not null, commit_lsn bigint not null, action text not null, old_values jsonb, new_values jsonb, created_at timestamp not null default now(), updated_at timestamp, -- Fields for transaction annotations username text, source text, request_id text, metadata jsonb);create unique index on audit_logs(commit_lsn, record_id);-- Optional: Add indexes for common queriescreate index on audit_logs(table_name, record_id);create index on audit_logs(created_at);create index on audit_logs(username);create index on audit_logs(request_id);
For better performance, consider batching multiple changes into a single database operation. Batching increases throughput while still maintaining transactional guarantees.
Your audit log table will now be populated with old and new values for each change, along with rich contextual information about who made the change and why.
With transaction annotations, you can create more informative activity feeds that show not just what changed, but who changed it and why:
create table activity_feed ( id serial primary key, record_id uuid not null, commit_lsn bigint not null, action text not null, description text not null, user_id uuid not null, actor text not null, source text not null, request_id text, reason text, metadata jsonb, created_at timestamp not null default now());create unique index on activity_feed(commit_lsn, record_id);create index on activity_feed(user_id, created_at);create index on activity_feed(actor, created_at);
You may need to re-sync your audit logs in these scenarios:
Schema changes: Updates to source or audit table schema
Logic updates: Changes to audit transformation logic
Data recovery: Recovering from processing errors
When streaming changes without retention, you can backfill from the source table. The change messages will be of action read and will only include the value currently in the database. Old values and deleted rows are not included.
Note that backfilled records will not include transaction annotations.