
4. Database Design Patterns for Audit Trails
Pattern 1 - Row Versioning (In-Place Audit)
Concept: Add versioning fields directly to the main table
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
order_number VARCHAR(50) NOT NULL,
customer_id BIGINT NOT NULL,
total_amount DECIMAL(10,2),
status VARCHAR(20),
-- Audit fields
version INT NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_by VARCHAR(100) NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_by VARCHAR(100) NOT NULL,
deleted_at TIMESTAMPTZ,
deleted_by VARCHAR(100)
);Pros:
- Simple to implement
- No extra tables
- Easy to query current state
Cons:
- Loses history of changes
- No details on what changed
- Can't rollback to previous versions
Pattern 2 - Shadow/History Tables
Concept: Separate table mirrors main table with full history
-- Main table (current state)
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
order_number VARCHAR(50) NOT NULL,
customer_id BIGINT NOT NULL,
total_amount DECIMAL(10,2),
status VARCHAR(20),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- History table (all versions)
CREATE TABLE orders_history (
history_id BIGSERIAL PRIMARY KEY,
id BIGINT NOT NULL,
order_number VARCHAR(50),
customer_id BIGINT,
total_amount DECIMAL(10,2),
status VARCHAR(20),
-- Audit metadata
operation VARCHAR(10) NOT NULL, -- INSERT, UPDATE, DELETE
changed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
changed_by VARCHAR(100) NOT NULL,
-- Track what changed
change_reason TEXT
);
-- Trigger to populate history
CREATE OR REPLACE FUNCTION orders_audit_trigger()
RETURNS TRIGGER AS $$
BEGIN
IF (TG_OP = 'DELETE') THEN
INSERT INTO orders_history (id, order_number, customer_id, total_amount,
status, operation, changed_by)
VALUES (OLD.id, OLD.order_number, OLD.customer_id, OLD.total_amount,
OLD.status, 'DELETE', current_user);
RETURN OLD;
ELSIF (TG_OP = 'UPDATE') THEN
INSERT INTO orders_history (id, order_number, customer_id, total_amount,
status, operation, changed_by)
VALUES (NEW.id, NEW.order_number, NEW.customer_id, NEW.total_amount,
NEW.status, 'UPDATE', current_user);
RETURN NEW;
ELSIF (TG_OP = 'INSERT') THEN
INSERT INTO orders_history (id, order_number, customer_id, total_amount,
status, operation, changed_by)
VALUES (NEW.id, NEW.order_number, NEW.customer_id, NEW.total_amount,
NEW.status, 'INSERT', current_user);
RETURN NEW;
END IF;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER orders_audit
AFTER INSERT OR UPDATE OR DELETE ON orders
FOR EACH ROW EXECUTE FUNCTION orders_audit_trigger();Pros:
- Complete history preserved
- Main table stays clean
- Easy to query historical data
Cons:
- Doubles storage requirements
- Schema changes need updating both tables
- Trigger overhead on every operation
Pattern 3 - Generic Audit Log Table
Concept: Single table logs changes to any entity
CREATE TABLE audit_logs (
id BIGSERIAL PRIMARY KEY,
-- What was changed
table_name VARCHAR(100) NOT NULL,
record_id VARCHAR(100) NOT NULL,
-- What changed
field_name VARCHAR(100),
old_value TEXT,
new_value TEXT,
-- Who and when
operation VARCHAR(10) NOT NULL, -- CREATE, UPDATE, DELETE, READ
changed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
changed_by VARCHAR(100) NOT NULL,
-- Context
ip_address INET,
user_agent TEXT,
session_id VARCHAR(100),
request_id VARCHAR(100),
-- Additional metadata
metadata JSONB
);
-- Indexes for common queries
CREATE INDEX idx_audit_logs_table_record ON audit_logs(table_name, record_id);
CREATE INDEX idx_audit_logs_changed_at ON audit_logs(changed_at DESC);
CREATE INDEX idx_audit_logs_changed_by ON audit_logs(changed_by);
CREATE INDEX idx_audit_logs_operation ON audit_logs(operation);Pros:
- Works for any table
- Flexible schema
- Single place for all audits
Cons:
- Less type safety
- Complex queries for reconstruction
- Can grow very large
Pattern 4 - Event Store (Event Sourcing)
Concept: Store all changes as discrete events
CREATE TABLE events (
id BIGSERIAL PRIMARY KEY,
-- Event identification
aggregate_type VARCHAR(100) NOT NULL, -- e.g., "Order"
aggregate_id VARCHAR(100) NOT NULL,
event_type VARCHAR(100) NOT NULL, -- e.g., "OrderCreated", "OrderPaid"
event_version INT NOT NULL,
-- Event data
event_data JSONB NOT NULL,
-- Metadata
occurred_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
caused_by VARCHAR(100) NOT NULL,
correlation_id VARCHAR(100),
-- Ensure ordered sequence per aggregate
CONSTRAINT unique_aggregate_version UNIQUE (aggregate_type, aggregate_id, event_version)
);
CREATE INDEX idx_events_aggregate ON events(aggregate_type, aggregate_id, event_version);
CREATE INDEX idx_events_occurred_at ON events(occurred_at);Example events:
{
"event_type": "OrderCreated",
"aggregate_type": "Order",
"aggregate_id": "ORD-12345",
"event_version": 1,
"event_data": {
"order_number": "ORD-12345",
"customer_id": 567,
"items": [...],
"total": 99.99
}
}
{
"event_type": "OrderPaid",
"aggregate_type": "Order",
"aggregate_id": "ORD-12345",
"event_version": 2,
"event_data": {
"payment_method": "credit_card",
"transaction_id": "TXN-98765"
}
}Pros:
- Complete history with business context
- Can rebuild state by replaying events
- Natural fit for CQRS
- Excellent for complex domains
Cons:
- High complexity
- Schema evolution challenges
- Event versioning required
- Querying current state requires rebuilding
A Compact Audit Table from This API
The API's audit table stores the operation envelope rather than a copy of the entire article:
type AuditLog struct {
Base
Actor string
Action string
Target string
}Base supplies the UUID and lifecycle timestamps. The matching SQL schema requires actor, action and target; it also has a B-tree index on created_at. Article bodies and their versions are stored in content_revisions.data, so an audit query can stay focused on who performed which operation and when.
For example, an operator can inspect recent actions for one entry with:
SELECT created_at, actor, action, target
FROM audit_logs
WHERE target = $1
ORDER BY created_at DESC;This query follows the current schema. If this lookup becomes a measured hot path, review its query plan and add an index through a SQL migration that matches the actual access pattern.
References: PostgreSQL transaction isolation.
Expanded from the supplied audit-log article
A practical PostgreSQL audit table
For a new service, an audit table can start small:
-- Example schema: not the existing RefactorRoom migration.
CREATE TABLE audit_logs (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
actor_id TEXT NOT NULL,
actor_type TEXT NOT NULL,
action TEXT NOT NULL,
target_type TEXT NOT NULL,
target_id TEXT NOT NULL,
request_id TEXT,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
);
CREATE INDEX audit_logs_target_time_idx
ON audit_logs (target_type, target_id, occurred_at DESC);
CREATE INDEX audit_logs_actor_time_idx
ON audit_logs (actor_id, occurred_at DESC);TIMESTAMPTZ represents an instant in time; write the timestamp with an explicit timezone or let PostgreSQL generate it. Index according to real investigation queries, not every possible field. More indexes increase storage and write costs.
You can add outcome, correlation_id or revision references once there is a real need. For a modest content system, do not start with partitioning, a message broker and a separate audit cluster without evidence that they are necessary.
Which audit mechanism should you choose?
There are several ways to capture changes:
| Approach | Strength | Main limitation |
|---|---|---|
| Application-level audit writes | Knows user identity and business action | Direct database writes can bypass the application |
| PostgreSQL triggers | Can capture database-level changes | Business intent and authenticated actor may be unavailable |
| Change data capture (CDC) | Can stream committed database changes | Raw row changes are not the same as meaningful business actions |
| Event sourcing | Complete event history for supported domains | Requires event evolution, replay and more design work |
For a Go content API, I would start with application-level audit writes in a database transaction. Add database triggers when you have a clear need to monitor writes outside the application and add CDC or an outbox only when another system needs the data.
Further reading
Originally published on DEV Community.


