Stage 3 · Build
Advanced Auth & Tenant Security
Audit Logging
Record security events with actor IDs, resource IDs, before-after fields, IP addresses, and retention policies.
Why Audit Logging
Audit logs answer who did what, when, and from where. They are essential for security investigations, compliance (SOC2, GDPR), and debugging production issues. Without audit logs, you cannot trace unauthorized changes.
Audit Schema
CREATE TABLE audit_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
actor_id UUID NOT NULL,
actor_email VARCHAR(255) NOT NULL,
action VARCHAR(100) NOT NULL,
resource_type VARCHAR(100) NOT NULL,
resource_id UUID,
before_state JSONB,
after_state JSONB,
ip_address INET,
user_agent TEXT,
request_id VARCHAR(100),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_audit_logs_actor ON audit_logs(actor_id);
CREATE INDEX idx_audit_logs_resource ON audit_logs(resource_type, resource_id);
CREATE INDEX idx_audit_logs_created ON audit_logs(created_at);
CREATE INDEX idx_audit_logs_action ON audit_logs(action);Audit logs capture the actor, action, resource, before/after states, IP address, and request ID. Indexes enable fast lookups by actor, resource, and time range.
Recording Events
Before-After Tracking
Before-after fields show what changed. This is critical for debugging — you can see exactly what was modified and by whom.
Retention Policies
-- Create partitioned audit log
CREATE TABLE audit_logs (
id UUID DEFAULT gen_random_uuid(),
actor_id UUID NOT NULL,
action VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
) PARTITION BY RANGE (created_at);
-- Monthly partitions
CREATE TABLE audit_logs_2024_01 PARTITION OF audit_logs
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
-- Retention: drop old partitions
DROP TABLE audit_logs_2023_01;Partition audit logs by month. Drop old partitions for retention. This keeps the table fast and controls storage costs. Keep audit logs for 7 years for compliance.
Querying Audit Logs
Never update or delete audit log entries. They are the source of truth for security investigations. If an audit log entry is wrong, add a correction entry, not a modification.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.