Video in progress
How do you design an audit log system: reliably storing and searching who changed what, and when?
Audit records are stored in an append-only place that can't be modified, and written in the same transaction as the business change or through an outbox. To avoid slowing down the main request, they are moved asynchronously into a separate store built for search, and immutability is enforced with permissions and a hash chain.
📖 Answer
I start with the requirements: who (user, service, IP), when, which object, what changed (old and new value), through which request (traceId). And most important — nobody, not even an admin, should be able to change this silently.
Write reliability. If the audit is sent "later" and the application crashes in between, the change exists with no trace. So the record goes in the same transaction as the business change:
CREATE TABLE audit_log (
id BIGSERIAL PRIMARY KEY,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
actor_id BIGINT, actor_ip INET,
entity TEXT NOT NULL, entity_id TEXT NOT NULL,
action TEXT NOT NULL,
changes JSONB NOT NULL,
trace_id TEXT
);
-- the application user gets INSERT privileges only
REVOKE UPDATE, DELETE ON audit_log FROM app_user;
You can automate this with Hibernate Envers or Debezium (CDC), but CDC doesn't answer "who" — the application still has to record the actor.
Search is a separate matter. Among millions of records, queries like "what did this user do in the last month" shouldn't land on the prod DB. The audit goes through an outbox or CDC into Elasticsearch/ClickHouse, while the main table is partitioned by time and old months move to the archive.
Immutability. If permissions aren't enough (a DBA can still do anything), add the previous record's hash to each record — if one record is removed from the chain, a verification will show it. Or keep the archive in object storage with WORM mode (S3 Object Lock).
Passwords, card numbers and tokens aren't written to the audit — they're masked in the list of changes. Otherwise the audit log itself becomes the most dangerous database.
Sign up to mark studied questions and save your progress.