What is an audit log, and how is it different from change history and application logs?

An audit log answers one question after the fact: who did what, to which record, when, and why. It exists for accountability, so each entry names an actor (a user, a service account, or a migration job), the action, the target, a timestamp, and ideally a reason or request ID. Change history and application logs look similar but serve different readers.

Audit trail Change history Application logs
Purpose Accountability, investigations Undo, "previous versions" UI Debugging, operations
Key content Actor, action, target, reason Prior field values Events, errors, timings
Completeness Must not drop writes Per-feature, often partial Sampled, lossy by design
Retention Set by policy, often years As long as the feature needs Days to weeks
Mutability Append-only May be pruned or compacted Rotated and discarded

Merging the three into one table causes problems for all of them. Product code starts pruning "history" rows that auditors expected to keep. Verbose debug payloads bury the actor field. Nobody can say whether a missing row means "no change" or "not captured," and once that is uncertain, nobody trusts the table.

Teams need a real audit trail when an incident review asks who disabled a flag, when a customer disputes a refund, or when a compliance reviewer asks who can see salary data. In a modular monolith, several modules write to one shared database. No single module sees every write path, so ownership belongs with backend and platform engineers who control the transaction boundary and the schema.

How does audit logging work in a modular monolith?

The architecture has three layers. Each module emits domain-level audit events through a narrow audit port, which is a small interface with one job: accept an event and persist it. A shared audit module sits behind that port and owns the schema, storage and retention policy. Modules never touch the audit tables directly. The format can therefore change in one place, and no module can quietly invent its own variant.

The audit record is written in the same transaction as the business change. If the update commits, its audit row commits with it. If either fails, both roll back. This rules out the two failure modes that make audit trails untrustworthy: changes with no record, and records describing changes that never happened.

Underneath, database triggers act as a backstop. They catch writes that bypass the application, such as migrations, manual fixes and batch scripts.

Every event has the same shape:

  • Actor: the user or service account, plus the impersonator when an admin acts on someone's behalf
  • Action: a verb such as approved or refunded, not a generic update
  • Entity type and id, and the owning module
  • Changes: the changed fields or a before/after diff
  • Timestamp and correlation id
  • Reason: optional, for actions that require justification

Actor and request context travel in a request-scoped context object. It is populated once at the edge, after authentication, and read by the audit module. Service methods do not have to pass the actor down through every call, so a developer adding a new write path cannot forget to include it.

+---------------------------+      +----------------------------+
| Edge: authenticate, then  |----->| Request-scoped context:    |
| populate context once     |      | actor, impersonator,       |
+---------------------------+      | correlation id             |
       |                           +----------------------------+
       v                                         |
+---------------------------------+              | read by
| Modules: Orders, Billing, ...   |              | audit module
| (service methods, no actor arg) |              |
+---------------------------------+              |
     | business write    | AuditEvent via port   |
     |                   v                       v
     |       +----------------------------------------------+
     |       | Audit port: record(event)                    |
     |       +----------------------------------------------+
     |       | Audit module: owns schema, storage, retention|
     |       +----------------------------------------------+
     |                                  |
     v                                  v audit row, same tx
+-----------------------------------------------------------+
| ONE DB TRANSACTION: commit or roll back together          |
|  +---------------------+        +----------------------+  |
|  | Business tables     |        | audit_log            |  |
|  +---------------------+        +----------------------+  |
+-----------------------------------------------------------+
          ^ bypassing app                    ^ trigger rows
+--------------------------+     +-----------------------------+
| Migrations, manual fixes,|     | DB triggers on business     |
| batch scripts            |     | tables (backstop)           |
+--------------------------+     +-----------------------------+

Modules write business data and send audit events through a narrow port, and the audit module persists those events in the same transaction using actor and correlation data from the request-scoped context, while database triggers record writes that bypass the application.

How do you implement application-layer audit logging inside the transaction?

Start with a request-scoped context holding three fields: the actor (user id, or a service identity), a correlation id taken from the inbound request or generated at the edge, and an optional "on behalf of" field. The audit module reads this context itself, so callers pass only the change.

Next, each module calls a single record method on a shared audit port. The call names a business event, the affected entity and a small payload. The billing module records invoice.voided with the invoice id, the reason code and the previous status. It does not record a list of changed columns. A reviewer can read "voided by Priya, reason: duplicate" directly. A raw diff such as status: 3 → 7 has to be decoded against code that may have changed since it was written.

The port's adapter uses the caller's open transaction to write either a row in an append-only audit table or an outbox row that a relay publishes later. Because the audit row commits or rolls back with the business change, you avoid two failure modes. You never get a "voided" entry for an invoice that is still open, and you never get a voided invoice without an entry.

Non-HTTP callers set the same context explicitly before doing any work:

  • Background jobs use a service identity such as job:invoice-reminder and carry the correlation id of the request that enqueued them.
  • Scheduled tasks use scheduler:<task-name>.
  • Migrations use migration:<id>.

For impersonation, set the actor to the real operator and the "on behalf of" field to the customer. Recording only the customer would hide who actually made the change.

import { AsyncLocalStorage } from "node:async_hooks";

// Request-scoped context: set once at the edge (HTTP middleware, job runner, migration runner).
type AuditContext = { actor: string; correlationId: string; onBehalfOf?: string };
export const auditContext = new AsyncLocalStorage<AuditContext>();

interface Tx { query(sql: string, params: unknown[]): Promise<{ rows: any[] }>; }

// Shared audit port: callers pass only the business event; actor data comes from context.
export async function record(tx: Tx, event: string, entityId: string, payload: object) {
  const ctx = auditContext.getStore();
  if (!ctx) throw new Error("no audit context: refusing an unattributed change");
  // Same transaction as the business write: both commit or both roll back.
  await tx.query(
    `INSERT INTO audit_log (event, entity_id, actor, on_behalf_of, correlation_id, payload)
     VALUES ($1, $2, $3, $4, $5, $6)`,
    [event, entityId, ctx.actor, ctx.onBehalfOf ?? null, ctx.correlationId, JSON.stringify(payload)],
  );
}

// Billing module: records a named business event, not a column diff.
export async function voidInvoice(tx: Tx, invoiceId: string, reasonCode: string) {
  const { rows } = await tx.query("SELECT status FROM invoices WHERE id = $1 FOR UPDATE", [invoiceId]);
  await tx.query("UPDATE invoices SET status = 'voided' WHERE id = $1", [invoiceId]);
  await record(tx, "invoice.voided", invoiceId, { reasonCode, previousStatus: rows[0].status });
}

// Background job: service identity plus the correlation id of the request that enqueued it.
export function runReminderJob(job: { correlationId: string }, work: () => Promise<void>) {
  return auditContext.run({ actor: "job:invoice-reminder", correlationId: job.correlationId }, work);
}

// Impersonation: the real operator is the actor; the customer goes in onBehalfOf.
// auditContext.run({ actor: "user:op-417", onBehalfOf: "user:cust-9021", correlationId }, handler);
// Scheduled tasks and migrations follow the same pattern: "scheduler:<task-name>", "migration:<id>".

A TypeScript sketch of a request-scoped audit context using AsyncLocalStorage, a shared record() port that inserts into an append-only audit table inside the caller's transaction, a billing module emitting invoice.voided, and service and impersonation actors.

How should database triggers fill the gaps for writes that bypass the application?

The application layer only sees writes that go through it. Someone running an UPDATE in a psql session to fix a production record, a nightly bulk job, a reporting tool with write access to the same database, or an ORM bulk update that skips per-entity hooks all change rows without producing an application audit entry. A row-level trigger on each audited table catches these writes. It records the table, primary key, operation, and old and new values as JSON.

To give the trigger an actor, have the application set a transaction-local setting at the start of every transaction. In PostgreSQL that means SET LOCAL app.actor = '...' or set_config('app.actor', ..., true). The trigger reads it with current_setting('app.actor', true), which returns null if the setting is missing. When it is missing, the trigger falls back to the database role, current_user, and marks the row source = 'trigger' with context = 'low'. That tells reviewers they know which database login made the change but not which person or request.

Avoid plain session-level SET with a connection pooler. A session setting stays on the pooled connection after the request ends. If the next request forgets to overwrite it, its changes are attributed to the previous user. A transaction-scoped setting is cleared at commit or rollback, so it cannot carry over to the next request.

When both layers fire for one change, store the transaction ID on both rows and link them by transaction ID, table, and primary key. The application entry is authoritative because it carries intent, the real actor, and the "on behalf of" field. The trigger row only corroborates it. A trigger row with no matching application entry is the signal worth alerting on.

-- Backstop log: every row lands here whether or not the app wrote its own entry
CREATE TABLE audit_trigger_log (
  id         bigserial PRIMARY KEY,
  tx_id      bigint NOT NULL DEFAULT txid_current(),  -- join key to app-level entries
  table_name text NOT NULL,
  row_pk     text NOT NULL,
  op         text NOT NULL,
  actor      text NOT NULL,
  source     text NOT NULL DEFAULT 'trigger',  -- corroborating, never authoritative
  context    text NOT NULL,                   -- 'low' = only the DB role is known
  old_row    jsonb,
  new_row    jsonb,
  changed_at timestamptz NOT NULL DEFAULT now()
);

CREATE OR REPLACE FUNCTION audit_row_change() RETURNS trigger AS $$
DECLARE
  -- missing_ok = true returns NULL if unset; NULLIF also covers the '' a custom
  -- setting can read as after an earlier SET LOCAL on this pooled connection
  app_actor text := NULLIF(current_setting('app.actor', true), '');
  pk text := to_jsonb(CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END) ->> 'id';
BEGIN
  INSERT INTO audit_trigger_log (table_name, row_pk, op, actor, context, old_row, new_row)
  VALUES (TG_TABLE_NAME, pk, TG_OP,
          COALESCE(app_actor, current_user),  -- fall back to the database login
          CASE WHEN app_actor IS NULL THEN 'low' ELSE 'app' END,
          CASE WHEN TG_OP <> 'INSERT' THEN to_jsonb(OLD) END,
          CASE WHEN TG_OP <> 'DELETE' THEN to_jsonb(NEW) END);
  RETURN NULL;  -- AFTER trigger: return value is ignored
END $$ LANGUAGE plpgsql;  -- not SECURITY DEFINER, so current_user stays the caller

CREATE TRIGGER orders_audit AFTER INSERT OR UPDATE OR DELETE ON orders
  FOR EACH ROW EXECUTE FUNCTION audit_row_change();

-- Application side: first statement of every transaction. The third argument
-- (true) makes it transaction-local, so it is cleared at COMMIT/ROLLBACK.
BEGIN;
SELECT set_config('app.actor', 'user:4821', true);
UPDATE orders SET status = 'refunded' WHERE id = 1042;
COMMIT;

A PostgreSQL row-level trigger records every write with the transaction ID. It reads the actor from a transaction-local setting and falls back to the database role with context = 'low' when the application did not set one.

Making the audit trail append-only, private and queryable

The audit table only helps if the application cannot rewrite it. Grant the application role INSERT and SELECT on the audit table, and revoke UPDATE and DELETE. A bug or a compromised service can then add misleading rows but cannot remove existing ones. Retention jobs should run under a separate role that drops whole time partitions. Partitioning by month makes expiry a metadata operation rather than a slow, lock-heavy delete.

If you need tamper evidence beyond permissions, hash-chain the rows. Each entry stores a hash of its own content plus the previous entry's hash. Anyone who edits a row breaks every hash after it, and a periodic verification job will report the break. This does not stop tampering. It makes tampering detectable.

Redact before you write. Remove secrets such as tokens and password hashes from diffs completely. For personal fields, record that the field changed but not its values. Plan for erasure requests now. Rows that reference a pseudonymous subject id, with the mapping kept in a separate table, can be "forgotten" by deleting the mapping. The append-only log stays intact.

Index for the three queries people actually run:

  • Entity history: (entity_type, entity_id, occurred_at)
  • Actor activity in a window: (actor_id, occurred_at)
  • Module changes overnight: (module, occurred_at), which partition pruning also helps

Expose these queries in an internal admin view. Support and compliance staff then get answers without filing an engineering ticket.

-- PostgreSQL: audit table owned by a dedicated role, partitioned by month.
CREATE TABLE audit_log (
  id           bigserial,
  occurred_at  timestamptz NOT NULL DEFAULT now(),
  actor_id     text        NOT NULL,  -- pseudonymous id, mapping lives elsewhere
  module       text        NOT NULL,
  entity_type  text        NOT NULL,
  entity_id    text        NOT NULL,
  action       text        NOT NULL,
  diff         jsonb,                 -- already redacted by the application
  prev_hash    bytea,                 -- hash chain for tamper evidence
  row_hash     bytea       NOT NULL,
  PRIMARY KEY (id, occurred_at)       -- must include the partition key
) PARTITION BY RANGE (occurred_at);

CREATE TABLE audit_log_2026_11 PARTITION OF audit_log
  FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');

-- Indexes on the parent are created on every partition.
CREATE INDEX ON audit_log (entity_type, entity_id, occurred_at);  -- entity history
CREATE INDEX ON audit_log (actor_id, occurred_at);                -- actor activity
CREATE INDEX ON audit_log (module, occurred_at);                  -- module changes

-- Application role can append and read, never rewrite.
GRANT INSERT, SELECT ON audit_log TO app_rw;
GRANT USAGE ON SEQUENCE audit_log_id_seq TO app_rw;
REVOKE UPDATE, DELETE, TRUNCATE ON audit_log FROM app_rw;

-- Retention runs as the owning role (audit_owner) and drops whole months.
ALTER TABLE audit_log DETACH PARTITION audit_log_2026_11;
DROP TABLE audit_log_2026_11;

A PostgreSQL audit table partitioned by month, indexed for the three common queries, with the application role limited to INSERT and SELECT and retention handled by detaching and dropping whole partitions under the owning role.

What are the alternatives and trade-offs: application layer, triggers, or both?

Each capture point sees a different part of what happened, so the real decision is which gaps you can live with.

Approach Records intent Catches bypassing writes Actor comes from Main risk
Application layer Yes: command, reason, request ID No Authenticated principal Scripts, bulk SQL and migrations go unrecorded
Triggers No, only row deltas Yes Session variable set per transaction Actor is empty or shows the pool user
Both Yes Yes Both, reconciled Duplicate entries unless each carries a source label

Synchronous vs asynchronous. Writing the audit row in the same transaction guarantees it exists if the change commits. The cost is extra latency and lock time. Queueing the write moves that cost off the request path, but a crash between commit and publish loses entries unless you use an outbox.

Snapshots vs diffs. Full snapshots make "what did this look like on Tuesday" a single read, but they grow quickly on wide rows. Field diffs stay small, but rebuilding a past state means replaying the history in order.

Shared vs per-module tables. A shared table makes cross-module queries simple. It also couples every module to one schema, and its insert-heavy tail and indexes can become a contention point. Per-module tables keep ownership clear, but cross-module questions then need a union view.

Immutability vs erasure. Don't update entries to correct them or delete them for erasure. Append a correcting entry that references the original instead. Keep personal data in a separate store keyed by subject, or encrypt it with a per-subject key. Erasure then means deleting that key, and the trail itself stays intact.

When should you avoid full audit logging, and what does it cost to run?

When lighter options are enough

Skip full auditing when nobody will ever be held accountable for a change. Internal tools with no compliance or dispute exposure are one example. Another is data where a change-history table or application logs already answer the questions people actually ask. High-churn tables such as counters, session state and sync cursors are poor candidates too: each write produces a second write that nobody reads.

What it costs

Every audited mutation does extra work inside its transaction: a diff, a serialized payload and an insert into an indexed table. That adds latency to every write. The audit table also grows faster than the data it describes, because rows in the source table are updated in place while the audit table accumulates one entry per change.

Illustrative estimate (assumed numbers, not a benchmark):

  • Assumed: 2,000,000 audited mutations per day, an average of 1.5 KB per audit row (before/after JSON plus actor and request metadata), and 365 days of retention.
  • Formula: mutations/day × bytes/row × retention days
  • Result: 2,000,000 × 1.5 KB × 365 ≈ 1.1 TB before indexes, regardless of how small the live tables are.

There is also ongoing engineering work. Every new module, bulk job and migration has to be checked for coverage.

What it saves

Incident investigation starts from a query instead of log archaeology. Engineers stop writing one-off forensic SQL against backups. Support and compliance teams can answer "who changed this, and when?" from the admin view without opening a ticket.

How do you test that every write path is audited?

That payoff only holds if the trail is complete, and completeness is easy to lose. Treat the audit path like business logic, because a missing audit row is a defect.

Assert the event, not just the side effect

For every state-changing use case, the test should check that exactly one audit event was written in the same transaction, and that it has the expected actor, entity type, entity ID and action. "Exactly one" matters. Zero means a silent gap. Two usually means a helper and a handler both emit, which will mislead anyone reconstructing a timeline later. Also assert that a rolled-back operation leaves no audit row. That confirms the event really shares the business transaction.

Fail the build when a new write path appears

Per-use-case tests only cover the paths someone remembered to test. Add a guard that catches the ones nobody thought of. There are two practical forms:

  • Trigger-only comparison. Run the integration suite, then compare trigger-captured rows against application audit rows. If a trigger row has no matching application event, some code path wrote to the table without auditing.
  • Structural check. Enumerate repositories, mutation handlers or command classes, and fail if any of them isn't registered with the audit mechanism or explicitly marked as exempt with a stated reason.

Review low-context trigger rows on a schedule

In production, trigger rows without an application actor show where coverage is thin. They come from migrations, admin scripts and forgotten batch jobs. Review them periodically, find their source, and either route that source through the application or document it. You want to find these gaps yourself, before an incident or an external audit finds them for you.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to audit log implementation, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.