TL;DR: A PostgreSQL trigger can record every
INSERT,UPDATEandDELETEon the tables you choose, including changes made outside your Node.js application. It cannot make those records impossible to tamper with: a superuser or table owner can disable triggers withALTER TABLE ... DISABLE TRIGGER, and a superuser can skip them withSET session_replication_role = replica. This guide builds a tamper-evident design instead: row-level audit triggers adapted from the PostgreSQL wiki "Audit trigger 91plus", a SHA-256 hash chain computed inside the trigger, a separate owner role for the audit schema, pgaudit for DDL and role changes, and periodic copies to S3 with Object Lock. You also learn how to pass the Node.js user ID into each transaction safely when using a connection pool. All SQL in this post was run against PostgreSQL 17; it uses features available since PostgreSQL 11.
Key Takeaways
- SOC2 does not prescribe database triggers. A database audit trail is one control that supports the AICPA Trust Services Criteria for monitoring (CC7.2) and evaluating security events (CC7.3). Your auditor tests whether your controls work, not whether you used a specific technique.
- Triggers are bypassable by privileged roles. Aim for tamper-evident, meaning tampering is detectable, rather than claiming tamper-proof.
- Put the audit schema under a dedicated
NOLOGINowner role. Do not grantINSERTon the audit table to the application role, or a compromised application can forge audit rows directly. - Chain each audit row to the previous one with
sha256(prev_hash || row_payload). Editing or deleting a row in the middle of the chain breaks verification. - A chain stored only in the same database can be rewritten by a superuser. Copy rows and their hashes to write-once storage (S3 Object Lock in compliance mode) so there is an external reference point.
- Use pgaudit with
pgaudit.log = 'ddl, role, misc_set'so that disabling a trigger, changing grants or switching roles appears in the server log. - Use
set_config('app.current_user_id', $1, true)inside a transaction so pooled connections never leak one user's identity into another request, and read it back withNULLIF(current_setting('app.current_user_id', true), ''). - Statement-level triggers on a partitioned table do not fire for statements that target a partition directly, so the append-only guard must also be attached to every partition.
You are preparing for a SOC2 Type II audit, and the auditor asks: "How would you know if someone with database access changed this customer's financial record outside the application?"
If your audit trail lives only in Node.js code, the honest answer is that you would not. Logging from Express controllers or ORM lifecycle hooks only sees writes that pass through that code. Manual SQL fixes, one-off scripts, batch jobs and other services that share the database write to the same tables without leaving a record. Application logging is still useful (it captures intent, request IDs and business context), but it is not a complete record of data changes.
Moving change capture into PostgreSQL closes that gap for the tables you attach triggers to. It does not close every gap. This post is explicit about which threats each layer handles and which it does not, because an audit trail that overstates its guarantees is worse than one that states them precisely.
When architecting custom backend development and API services for compliance-bound products, a layered design like the one below is a reasonable starting point. Adapt the retention periods, roles and alerting to the commitments in your own security policies.
What SOC2 Actually Asks For
SOC2 reports are built on the AICPA 2017 Trust Services Criteria (with revised points of focus, 2022). The criteria describe outcomes, not implementations. Two common criteria are relevant here:
- CC7.2 covers monitoring system components and their operation for anomalies that indicate malicious acts, natural disasters or errors, and analyzing those anomalies to decide whether they are security events.
- CC7.3 covers evaluating security events to determine whether they could or did cause a failure to meet the entity's objectives, and responding when they do.
An audit trail of data changes is evidence for these criteria: it shows that changes to sensitive records are recorded, attributable and reviewable. It is not, by itself, "SOC2 compliance". Access reviews, change management, alerting, incident response and many other controls sit alongside it. In a Type II engagement the auditor also tests that the control operated throughout the review period, so a verification job that runs every day and leaves its own evidence matters as much as the schema.
Terminology used in this guide
| Term | Meaning in this post |
|---|---|
| Audit trail | Append-only table of row changes: who, when, which table, before and after values |
| Tamper-proof | Modification is impossible. Not achievable inside a database that a superuser controls |
| Tamper-evident | Modification is possible but detectable by verification against an independent reference |
| Hash chain | Each row stores the hash of the previous row, so changing any row invalidates every later link |
| WORM storage | Write once, read many. Objects cannot be overwritten or deleted until their retention period ends |
| Application user | The end user your API authenticated, passed in by Node.js. Asserted by the application, not by PostgreSQL |
| Session user | The PostgreSQL role that opened the connection. Asserted by PostgreSQL authentication |
Threat Model: Who Can Bypass What
Before writing SQL, be clear about the actors. The table below assumes the design in this post is fully applied.
| Actor | What they can do | What detects it |
|---|---|---|
Application role (app_role) | Change business rows; cannot write to audit directly; can claim any app.current_user_id | Trigger records the change and the real session_user |
| Developer with a normal login role | Same as the application role, depending on grants | Trigger records the change under their own session_user |
| Owner of an audited table | ALTER TABLE ... DISABLE TRIGGER or DROP TRIGGER on that table, then write unaudited changes | pgaudit ddl entry in the server log; gaps in expected activity |
| Owner of the audit schema | Disable the append-only guard and edit audit rows | Hash chain verification; WORM copies |
| Superuser | Everything above, plus SET session_replication_role = replica, changing pgaudit settings, rewriting the whole chain | Hash comparison against WORM copies; off-host server logs; cloud provider audit logs |
Two conclusions follow. First, you reduce risk mainly by keeping the number of people who hold table ownership or superuser small, using separate roles for migrations, the application, and the audit schema. Second, the last line of defence is a copy of the evidence that nobody in the database can change.
Architecture Overview
The design has five layers, each small and independently testable:
- Capture: a generic
AFTER INSERT OR UPDATE OR DELETE ... FOR EACH ROWtrigger writes the old and new row asJSONBintoaudit.logged_actions. - Context: Node.js sets
app.current_user_idwithset_config(..., true)at the start of each transaction, and the trigger reads it. - Integrity: the trigger takes a row lock on a single-row
audit.chain_headtable, computesrow_hash = sha256(prev_hash || payload)and advances the head. - Privileged change logging: pgaudit records DDL, grants and
SETcommands in the PostgreSQL server log, which is shipped off the host. - External anchor: a shipper process with read-only access copies new audit rows, including their hashes, to an S3 bucket with Object Lock in compliance mode.
Think of it as a pipeline: business table, then trigger, then audit table with hash chain, then WORM archive. The verification job reads from both ends and compares.
Schema, Roles and Ownership
The table and trigger function in this guide are adapted from the Audit trigger 91plus design on the PostgreSQL wiki, whose maintained version lives in the 2ndQuadrant/audit-trigger repository. The wiki version stores row data as hstore, records more connection metadata (client address, application name, transaction ID) and also audits TRUNCATE with a statement-level trigger. This post uses JSONB, adds an application user column and hash chain columns, and trims the column list to keep the examples readable. If you need the extra columns, start from the original.
Ownership is the most important decision in this section. The audit objects belong to a dedicated NOLOGIN role, so nobody can connect as it, and neither the application nor the migration tooling owns them.
-- Roles. audit_owner owns the audit schema and cannot log in.
CREATE ROLE audit_owner NOLOGIN;
CREATE ROLE migration_role NOLOGIN; -- owns business tables, used by migrations
CREATE ROLE app_role LOGIN; -- the Node.js service
CREATE ROLE audit_reader NOLOGIN; -- reporting and the WORM shipper
CREATE SCHEMA audit AUTHORIZATION audit_owner;
REVOKE ALL ON SCHEMA audit FROM PUBLIC;
SET ROLE audit_owner;
CREATE TABLE audit.logged_actions (
event_id BIGSERIAL PRIMARY KEY,
schema_name TEXT NOT NULL,
table_name TEXT NOT NULL,
relid OID NOT NULL,
session_user_name TEXT NOT NULL,
action_tstamp_tx TIMESTAMPTZ NOT NULL,
action TEXT NOT NULL CHECK (action IN ('I', 'D', 'U', 'T')),
application_user_id TEXT, -- asserted by Node.js
original_data JSONB,
changed_data JSONB,
statement_only BOOLEAN NOT NULL,
client_query TEXT,
prev_hash BYTEA, -- NULL only for the first row
row_hash BYTEA NOT NULL
);
CREATE INDEX logged_actions_relid_idx ON audit.logged_actions (relid);
CREATE INDEX logged_actions_action_tstamp_tx_idx ON audit.logged_actions (action_tstamp_tx);
CREATE INDEX logged_actions_app_user_idx ON audit.logged_actions (application_user_id);
-- Single-row table holding the latest hash in the chain.
CREATE TABLE audit.chain_head (
id INT PRIMARY KEY CHECK (id = 1),
last_hash BYTEA
);
INSERT INTO audit.chain_head (id, last_hash) VALUES (1, NULL);
Notes on the important lines:
session_user_nameis recorded by PostgreSQL from authentication.application_user_idis whatever the application says. A compromised application can lie about the latter but not the former, so investigations should look at both.relidis useful for joins againstpg_class, but OIDs change after a dump and restore. That is why the hash below uses schema and table names instead.- If you expect high write volume, create
audit.logged_actionsas a partitioned table from day one (see the partitioning section). Converting a large unpartitioned table later means copying all its rows.
Production note:
client_querystores the text of the top-level statement fromcurrent_query(). With parameterized queries in node-postgres, the text contains placeholders such as$1and the values travel separately, so they do not end up in this column. String-concatenated SQL would copy raw values, including personal data, into the audit table.
Adding a Hash Chain
A hash chain turns silent edits into detectable ones. Each row's hash covers its own content plus the previous row's hash. Change one row and its stored hash no longer matches a recomputation; recompute that hash too and the next row's prev_hash no longer matches.
The digest function must be deterministic, so both the trigger and the verifier produce the same bytes for the same row:
CREATE OR REPLACE FUNCTION audit.row_digest(prev_hash BYTEA, r audit.logged_actions)
RETURNS BYTEA
LANGUAGE sql
SET search_path = pg_catalog, pg_temp
AS $$
SELECT sha256(
coalesce(prev_hash, '\x'::bytea) ||
convert_to(
jsonb_build_object(
'event_id', r.event_id,
'schema_name', r.schema_name,
'table_name', r.table_name,
'session_user_name', r.session_user_name,
'action_tstamp_utc', r.action_tstamp_tx AT TIME ZONE 'UTC',
'action', r.action,
'application_user_id', r.application_user_id,
'original_data', r.original_data,
'changed_data', r.changed_data,
'statement_only', r.statement_only,
'client_query', r.client_query
)::text,
'UTF8'
)
)
$$;
Why it is built this way:
sha256(bytea)is a built-in PostgreSQL function (version 11 and later), so no extension such aspgcryptois needed.jsonbnormalizes key order and whitespace, so::textgives a stable serialization for equal values.- A
timestamptzserialized to JSON includes the session's time zone offset, which would make the hash depend on theTimeZonesetting of whoever runs the verifier. Converting withAT TIME ZONE 'UTC'removes that dependency. relid,prev_hashandrow_hashare excluded from the payload. The previous hash is mixed in explicitly at the front.
A hash chain is not a signature. Anyone who can write to the table and knows the algorithm can recompute every hash after an edit. The chain only becomes strong evidence when its hashes are also stored somewhere that person cannot write, which is the job of the WORM archive later in this guide.
Writing the Audit Trigger Function
The trigger function runs after each row change. It skips updates that changed nothing, locks the chain head, fills the audit row, computes its hash, inserts it and advances the head.
CREATE OR REPLACE FUNCTION audit.if_modified_func()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $body$
DECLARE
audit_row audit.logged_actions;
BEGIN
-- Skip updates that did not change any value.
IF TG_OP = 'UPDATE' AND to_jsonb(OLD.*) = to_jsonb(NEW.*) THEN
RETURN NEW;
END IF;
-- Serialize chain appends. The row lock is held until COMMIT or ROLLBACK.
SELECT last_hash INTO audit_row.prev_hash
FROM audit.chain_head
WHERE id = 1
FOR UPDATE;
audit_row.event_id := nextval('audit.logged_actions_event_id_seq');
audit_row.schema_name := TG_TABLE_SCHEMA;
audit_row.table_name := TG_TABLE_NAME;
audit_row.relid := TG_RELID;
audit_row.session_user_name := session_user;
audit_row.action_tstamp_tx := transaction_timestamp();
audit_row.action := substr(TG_OP, 1, 1);
audit_row.application_user_id := NULLIF(current_setting('app.current_user_id', true), '');
audit_row.statement_only := false;
audit_row.client_query := current_query();
IF TG_OP IN ('UPDATE', 'DELETE') THEN
audit_row.original_data := to_jsonb(OLD.*);
END IF;
IF TG_OP IN ('UPDATE', 'INSERT') THEN
audit_row.changed_data := to_jsonb(NEW.*);
END IF;
audit_row.row_hash := audit.row_digest(audit_row.prev_hash, audit_row);
INSERT INTO audit.logged_actions VALUES (audit_row.*);
UPDATE audit.chain_head SET last_hash = audit_row.row_hash WHERE id = 1;
IF TG_OP = 'DELETE' THEN
RETURN OLD;
END IF;
RETURN NEW;
END;
$body$;
REVOKE ALL ON FUNCTION audit.if_modified_func() FROM PUBLIC;
Key decisions in this function:
SECURITY DEFINERowned byaudit_owner. The function runs with the owner's privileges, so it can insert into the audit table even though the role that fired the trigger cannot. This is what makes the next section's "no direct grants" rule possible.SET search_path = pg_catalog, pg_temp. The PostgreSQL documentation on writingSECURITY DEFINERfunctions safely recommends excluding schemas that untrusted users can write to and placingpg_templast, so a temporary object cannot shadow a trusted one. Every audit object is schema-qualified, sopublicis not needed at all.current_setting('app.current_user_id', true). The second argument (missing_ok) returns NULL instead of raising an error when the setting was never defined in the session. Once a session has used a transaction-local setting, later transactions read an empty string rather than NULL, soNULLIF(..., '')normalizes both cases. No exception block is needed, which also avoids the subtransaction cost ofBEGIN ... EXCEPTIONin PL/pgSQL.- Lock before
nextval. Becauseevent_idis assigned while holding the chain lock, and the lock is held until commit, committed rows appear inevent_idorder with no later commit receiving a smaller ID. That property keeps both the verifier and the shipper simple. Rolled-back transactions leave gaps inevent_id, which is normal.
The cost of this design is that every audited write in the database serializes on one row lock until its transaction commits. For many business applications that is acceptable; for high write throughput it is not. See the performance section for alternatives.
Attaching Triggers to Business Tables
The owner of each business table attaches the trigger, so that role needs EXECUTE on the function and USAGE on the schema. It does not need any privilege on the audit table itself.
-- As audit_owner (or a superuser)
GRANT USAGE ON SCHEMA audit TO migration_role;
GRANT EXECUTE ON FUNCTION audit.if_modified_func() TO migration_role;
-- As migration_role, the owner of public.users
CREATE TRIGGER audit_users_changes
AFTER INSERT OR UPDATE OR DELETE ON public.users
FOR EACH ROW EXECUTE FUNCTION audit.if_modified_func();
-- Fire even when a session sets session_replication_role = replica
ALTER TABLE public.users ENABLE ALWAYS TRIGGER audit_users_changes;
FOR EACH ROW means a bulk UPDATE touching 10,000 rows writes 10,000 audit rows. EXECUTE FUNCTION is the current syntax; older posts use EXECUTE PROCEDURE, which still works but is deprecated.
ENABLE ALWAYS deserves an explanation. By default, triggers fire only when session_replication_role is origin or local. A superuser (or a role granted SET on that parameter) can switch a session to replica, and default triggers then stop firing. Marking the trigger ALWAYS removes that silent bypass. The trade-off: if this database is a subscriber in logical replication, ALWAYS triggers also fire when replicated changes are applied, which would create duplicate audit rows on the subscriber. In that topology, audit on the publisher only.
ENABLE ALWAYS does not stop the table owner from running ALTER TABLE public.users DISABLE TRIGGER audit_users_changes. That command needs only table ownership for user triggers. Detecting it is the job of pgaudit, covered below.
Locking Down Privileges
A common mistake in published audit trigger examples is a grant like GRANT INSERT ON audit.logged_actions TO application_role. With a SECURITY DEFINER trigger function that grant is unnecessary, and it is harmful: anyone with the application's credentials can insert forged rows with any user ID, timestamp or payload. Grant nothing on the audit table to the application.
-- As audit_owner
REVOKE ALL ON audit.logged_actions FROM PUBLIC;
REVOKE ALL ON audit.chain_head FROM PUBLIC;
-- Read-only access for reporting and the WORM shipper
GRANT USAGE ON SCHEMA audit TO audit_reader;
GRANT SELECT ON audit.logged_actions TO audit_reader;
-- Application: privileges on business tables only
GRANT SELECT, INSERT, UPDATE, DELETE ON public.users TO app_role;
With this in place, running INSERT INTO audit.logged_actions ... as app_role fails with permission denied for schema audit, while the same role's UPDATE public.users ... is audited normally. Write a test that asserts both (see the testing section).
Keep three role families apart: the role that owns the audit schema, the roles that own business tables (migrations), and the roles that run the application. If the same role owns both business tables and the audit schema, a single compromised credential can disable capture and edit history.
Enforcing Append-Only Behaviour
Revoking privileges stops non-owners. For mistakes by the owner role, add a guard trigger that rejects UPDATE, DELETE and TRUNCATE on the audit table:
CREATE OR REPLACE FUNCTION audit.reject_mutation()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
RAISE EXCEPTION 'audit.logged_actions is append-only (% rejected)', TG_OP;
END;
$$;
CREATE TRIGGER enforce_append_only
BEFORE UPDATE OR DELETE OR TRUNCATE ON audit.logged_actions
FOR EACH STATEMENT EXECUTE FUNCTION audit.reject_mutation();
ALTER TABLE audit.logged_actions ENABLE ALWAYS TRIGGER enforce_append_only;
Be precise about what this buys you. It stops accidental DELETE statements, including ones run by the owner or a superuser who has not deliberately disabled it, and with ENABLE ALWAYS it is not skipped by session_replication_role = replica. It does not stop the owner or a superuser from running ALTER TABLE audit.logged_actions DISABLE TRIGGER enforce_append_only, editing rows and re-enabling it. PostgreSQL does not record that sequence anywhere unless statement logging or pgaudit is configured. In a test against PostgreSQL 17, exactly that sequence succeeded, and the hash chain verifier below flagged the edited row.
There is one more gap if you partition the audit table. In PostgreSQL, statement-level triggers on a partitioned table fire for statements that target the parent, but not for statements that target a partition directly. Running DELETE FROM audit.logged_actions_y2026m10 as the owner bypasses the parent's guard. Create the same enforce_append_only trigger on every partition when you create it.
Logging Privileged Changes with pgaudit
The remaining bypasses are DDL and session settings: disabling a trigger, dropping one, altering grants, switching roles. PostgreSQL's built-in log_statement = 'ddl' covers part of this, and the pgaudit extension gives structured, classified entries. Current pgaudit releases support PostgreSQL 14 and later, with one major version per PostgreSQL release.
# postgresql.conf (or your managed service's parameter group)
shared_preload_libraries = 'pgaudit'
pgaudit.log = 'ddl, role, misc_set'
log_line_prefix = '%m [%p] %q%u@%d '
-- After a restart, in each database you want audited
CREATE EXTENSION pgaudit;
What each class captures, per the pgaudit README:
| Class | Covers | Why it matters here |
|---|---|---|
ddl | All DDL not in the role class, including ALTER TABLE and DROP TRIGGER | Disabling or dropping audit triggers becomes visible |
role | GRANT, REVOKE, CREATE/ALTER/DROP ROLE | Privilege escalation toward the audit schema is visible |
misc_set | Miscellaneous SET commands such as SET ROLE | Role switching is visible |
write | INSERT, UPDATE, DELETE, TRUNCATE, COPY into a relation | Usually too noisy globally; consider object auditing |
pgaudit writes to the standard PostgreSQL log, so its value depends on getting that log off the database host quickly (CloudWatch, a SIEM, or any log pipeline the database administrators cannot edit). A superuser can change pgaudit settings or call set_config through a SELECT, which the misc_set class does not classify as a SET command. Treat pgaudit as a strong signal for routine administrative changes, and the WORM comparison as the backstop for a determined superuser. Alerting on any ddl entry that touches audit. objects or audited tables outside a change window is a concrete detection rule that maps well to CC7.2.
Injecting Node.js Context into PostgreSQL Transactions
PostgreSQL knows the database role, not the end user behind an HTTP request. The application passes that identity in with set_config inside the same transaction as the writes.
With connection pooling (node-postgres Pool, PgBouncer in transaction mode, or an ORM's pool), connections are reused across requests. A session-level setting would stay attached to the connection and mislabel the next request. Passing true as the third argument to set_config makes the setting transaction-local: it ends at COMMIT or ROLLBACK. Because the setting lives entirely inside one transaction, it also works with PgBouncer's transaction pooling mode.
// node-postgres (pg) 8.x
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
/**
* Runs queryFunc inside a transaction with the application user ID
* available to audit triggers as app.current_user_id.
*/
async function executeWithAuditContext(userId, queryFunc) {
if (typeof userId !== 'string' || userId.length === 0) {
throw new Error('executeWithAuditContext requires a non-empty userId');
}
const client = await pool.connect();
try {
await client.query('BEGIN');
// Third argument true = is_local: the value is discarded at COMMIT or ROLLBACK.
await client.query("SELECT set_config('app.current_user_id', $1, true)", [userId]);
const result = await queryFunc(client);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
// Express route
app.post('/api/users/:id/status', authenticate, async (req, res) => {
try {
await executeWithAuditContext(req.user.id, (client) =>
client.query('UPDATE users SET status = $1 WHERE id = $2', [req.body.status, req.params.id]),
);
res.json({ success: true });
} catch (err) {
req.log.error({ err }, 'status update failed');
res.status(500).json({ error: 'Update failed' });
}
});
Details that matter:
set_configtakes the value as a bind parameter, so a user ID cannot inject SQL.SET LOCALdoes not accept bind parameters, which is why the function form is used.- The setting must be applied on the same client that runs the writes. Calling
pool.queryfor theset_configand thenpool.queryagain for the update may use two different connections. - ORMs that offer interactive transactions can run the same
SELECT set_config(...)as the first statement inside the transaction callback. Verify with a test that the audit row carries the expected user ID, because some ORM batching modes do not guarantee a single connection. - Validate
req.body.statusagainst an allowed list before writing. The audit trail records bad data faithfully; it does not prevent it.
Warning: Never run
SET app.current_user_id = '...'(withoutLOCAL) orset_config(..., false)on a pooled connection. The value persists for the life of the connection and subsequent requests from other users will be audited under the wrong identity.
Shipping Audit Rows to WORM Storage
The hash chain detects edits only if you can compare against hashes stored where the editor cannot reach. Amazon S3 Object Lock provides that: in compliance mode, a locked object version cannot be overwritten or deleted by any user, including the AWS account root user, until its retention date passes. In governance mode, users with s3:BypassGovernanceRetention can still remove it, which is useful for testing but weaker as evidence. Object Lock requires a bucket with versioning enabled, and uploads that set a retention period must carry a Content-MD5 or x-amz-sdk-checksum-algorithm header.
The shipper below runs as audit_reader (read-only on the audit table) and uses AWS SDK for JavaScript v3:
// pg 8.x, @aws-sdk/client-s3 3.x, Node.js 20+
const { Pool } = require('pg');
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const pool = new Pool({ connectionString: process.env.AUDIT_READER_DATABASE_URL });
const s3 = new S3Client({});
const BUCKET = requireEnv('AUDIT_ARCHIVE_BUCKET');
const RETENTION_DAYS = Number(requireEnv('AUDIT_RETENTION_DAYS'));
function requireEnv(name) {
const value = process.env[name];
if (!value) throw new Error(`Missing required environment variable ${name}`);
return value;
}
/** Ships rows after `afterEventId` and returns the last shipped event_id. */
async function shipBatch(afterEventId, limit = 5000) {
const { rows } = await pool.query(
`SELECT event_id, schema_name, table_name, session_user_name, action_tstamp_tx,
action, application_user_id, original_data, changed_data,
statement_only, client_query,
encode(prev_hash, 'hex') AS prev_hash, encode(row_hash, 'hex') AS row_hash
FROM audit.logged_actions
WHERE event_id > $1
ORDER BY event_id
LIMIT $2`,
[afterEventId, limit],
);
if (rows.length === 0) return afterEventId;
const first = String(rows[0].event_id).padStart(20, '0');
const last = String(rows.at(-1).event_id).padStart(20, '0');
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: `audit/${first}-${last}.ndjson`,
Body: rows.map((row) => JSON.stringify(row)).join('\n') + '\n',
ContentType: 'application/x-ndjson',
ChecksumAlgorithm: 'SHA256',
ObjectLockMode: 'COMPLIANCE',
ObjectLockRetainUntilDate: new Date(Date.now() + RETENTION_DAYS * 86_400_000),
}),
);
return rows.at(-1).event_id;
}
module.exports = { shipBatch };
How it fits together:
- node-postgres returns
BIGINTcolumns as strings, which is whyevent_idis converted withString()and passed straight back as a parameter. - The cursor (the last shipped
event_id) can be recovered from the newest key in the bucket, because the zero-padded keys sort lexicographically. Run the shipper on a schedule frequent enough that the window in which recent rows exist only in PostgreSQL is acceptable to you, for example every few minutes. - Because
event_idvalues are assigned under the chain lock, a row with a smaller ID cannot commit after a row with a larger ID is visible, so the shipper does not skip rows from slow transactions. - Choose
AUDIT_RETENTION_DAYSfrom your written retention policy. Compliance-mode retention cannot be shortened later, so test with governance mode first. - Give the shipper's IAM role
s3:PutObjecton the prefix and nothing that can delete or change retention.
Verifying the Chain
Verification has two parts. The first checks internal consistency inside PostgreSQL:
-- Returns event_ids whose link or content does not verify. Expect zero rows.
SELECT event_id
FROM (
SELECT l.event_id,
l.prev_hash,
l.row_hash,
lag(l.row_hash) OVER (ORDER BY l.event_id) AS expected_prev,
audit.row_digest(l.prev_hash, l) AS recomputed
FROM audit.logged_actions AS l
) AS chain
WHERE prev_hash IS DISTINCT FROM expected_prev
OR row_hash <> recomputed;
IS DISTINCT FROM treats the first row (where both values are NULL) as valid. If you have dropped old partitions after archiving them, the first remaining row has a non-NULL prev_hash; filter on event_id and compare that first prev_hash against the last row_hash in the archive instead.
The second part compares the database against the WORM copies: for every archived (event_id, row_hash) pair, the database must hold the same hash. A superuser who edits a row and recomputes the entire chain passes the first check but fails the second for every row already archived. Rows written since the last shipment are only protected by the internal check, which is why the shipping interval matters.
Run both checks on a schedule, store the result (pass or the failing IDs) in your monitoring system, and alert on any failure. A Type II auditor will want to see evidence that the check ran during the period, not just that it exists.
Querying Revision History
Because each audit row stores the full before and after state as JSONB, field-level history is a query, not an application feature. To see when a user's email changed and who changed it:
SELECT
action_tstamp_tx AS changed_at,
application_user_id AS changed_by_app_user,
session_user_name AS changed_by_db_role,
original_data ->> 'email' AS old_email,
changed_data ->> 'email' AS new_email
FROM audit.logged_actions
WHERE schema_name = 'public'
AND table_name = 'users'
AND action = 'U'
AND changed_data ->> 'id' = '6f1c1d5e-4c2a-4b7e-9d55-2f0f6b0a9c11'
AND original_data ->> 'email' IS DISTINCT FROM changed_data ->> 'email'
ORDER BY action_tstamp_tx DESC;
Show both identity columns in any "revision history" screen used for investigations. A row where application_user_id is NULL and session_user_name is a human's login role is exactly the "manual change outside the application" your auditor asked about.
For frequent lookups by record ID, add an expression index such as CREATE INDEX ON audit.logged_actions ((changed_data ->> 'id')), or store the primary key in its own column. A GIN index on the whole JSONB column is usually larger than you need for this access pattern.
Managing Growth with Native Partitioning
Audit tables grow with write volume, and every audited row is stored twice (old and new) for updates. Range partitioning by time lets you detach and drop old months instead of running large DELETE statements, which the append-only guard would reject anyway. For a deeper treatment of partition management in Node.js, see scaling PostgreSQL for high-volume telemetry with native partitioning.
-- Create the audit table partitioned from the start.
-- A primary key on a partitioned table must include the partition key.
CREATE TABLE audit.logged_actions (
event_id BIGSERIAL,
schema_name TEXT NOT NULL,
table_name TEXT NOT NULL,
relid OID NOT NULL,
session_user_name TEXT NOT NULL,
action_tstamp_tx TIMESTAMPTZ NOT NULL,
action TEXT NOT NULL CHECK (action IN ('I', 'D', 'U', 'T')),
application_user_id TEXT,
original_data JSONB,
changed_data JSONB,
statement_only BOOLEAN NOT NULL,
client_query TEXT,
prev_hash BYTEA,
row_hash BYTEA NOT NULL,
PRIMARY KEY (event_id, action_tstamp_tx)
) PARTITION BY RANGE (action_tstamp_tx);
CREATE TABLE audit.logged_actions_y2026m10
PARTITION OF audit.logged_actions
FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
-- Statement triggers are not inherited by partitions: guard each one.
CREATE TRIGGER enforce_append_only
BEFORE UPDATE OR DELETE OR TRUNCATE ON audit.logged_actions_y2026m10
FOR EACH STATEMENT EXECUTE FUNCTION audit.reject_mutation();
ALTER TABLE audit.logged_actions_y2026m10 ENABLE ALWAYS TRIGGER enforce_append_only;
The trigger function and digest work unchanged with the partitioned table; the row type is the same. Create partitions ahead of time (a monthly job or pg_partman), because an insert whose timestamp has no matching partition fails, and in this design that failure aborts the business transaction that fired the trigger.
At the end of the retention period your policy defines, audit_owner can run ALTER TABLE audit.logged_actions DETACH PARTITION ... and drop the detached table. Confirm first that the shipper has archived every row in it and record the partition's last row_hash as the anchor for the next verification run. Note that detaching and dropping are owner actions that the append-only guard does not block, which is another reason the WORM copy, not the database, is the record of last resort.
Performance Considerations
This design trades throughput for simplicity. Measure on your own workload before relying on any of these estimates.
- Chain lock contention. Every audited write waits for the previous audited transaction to commit. Long transactions that touch audited tables block all other audited writes. Keep those transactions short.
- Write amplification. Each audited row change costs one extra insert, one update of
chain_head, three index updates and a SHA-256 computation.chain_headwill accumulate dead tuples quickly; autovacuum handles it, but watch its bloat. - Payload size.
to_jsonb(OLD.*)andto_jsonb(NEW.*)copy whole rows. Exclude wide or sensitive columns (the wiki version supports an excluded-columns list) or audit only the tables that need it.
If serialization becomes the bottleneck, common alternatives are: one chain per audited table (one chain_head row per table), chaining per batch in the shipper instead of per row in the trigger, or moving capture out of the transaction entirely with logical decoding (for example Debezium) into an append-only log. Each alternative changes the guarantees, so revisit the threat model when you switch.
| Approach | Captures out-of-app changes | Extra latency in the write path | Privileged bypass |
|---|---|---|---|
| Application or ORM hooks | No | Low | Any direct database write |
| Row triggers without chain | Yes, for audited tables | Moderate | Undetectable edits by owner or superuser |
| Row triggers with chain and WORM | Yes, for audited tables | Higher (serialized appends) | Detectable once rows are archived |
| Logical decoding (CDC) to a log | Yes, for published tables | Low (asynchronous) | Replication slot and publication changes |
pgaudit write class | Yes, statement text only | Low to moderate | Superuser can change settings |
Testing the Design
Turn the guarantees into automated tests that run against a real PostgreSQL instance (a container in CI is enough). Useful assertions:
- An update made through
executeWithAuditContextproduces one audit row with the expectedapplication_user_idandsession_user_name. - An update with no value changes produces no audit row.
- As
app_role,INSERT INTO audit.logged_actionsfails with a permission error. - As
audit_owner,DELETE,UPDATEandTRUNCATEonaudit.logged_actionsand on a partition all fail. - After
SET session_replication_role = replicaas a superuser, an update onpublic.usersstill produces an audit row. - The verification query returns zero rows on clean data, and returns the edited
event_idafter a test disables the guard trigger, edits a row and re-enables it. - Two concurrent transactions writing to audited tables both produce audit rows, and the chain still verifies.
Test 6 is the important one: it proves the evidence pipeline catches the bypass you cannot prevent.
Common Mistakes
- Granting
INSERTon the audit table to the application role. It lets a compromised service forge history. TheSECURITY DEFINERfunction is the only writer. - Calling it tamper-proof. Auditors and security reviewers know that superusers can disable triggers. Describe the control as tamper-evident and document the residual risk.
- Session-level
SETon pooled connections. User IDs leak across requests. search_pathincludingpublicin aSECURITY DEFINERfunction that also uses unqualified names. Schema-qualify everything and end withpg_temp.- Guarding only the partitioned parent. Direct statements against partitions skip the parent's statement triggers.
- Hashing a
timestamptzwithout normalizing the time zone, which makes verification depend on session settings. - Keeping the only copy in the same database, or archiving to a bucket the same administrators can delete from.
- Never running the verifier. An unverified chain provides no evidence.
Production Readiness Checklist
- Audit schema owned by a
NOLOGINrole distinct from migration and application roles - No privileges on
audit.logged_actionsfor the application role;SELECTonly for readers - Trigger function is
SECURITY DEFINERwithSET search_path = pg_catalog, pg_tempandEXECUTErevoked fromPUBLIC - Audit triggers attached to every table in scope and marked
ENABLE ALWAYS(unless the database is a logical replication subscriber) - Append-only guard on the parent table and every partition
- pgaudit loaded with at least
ddl, role, misc_set; server logs shipped off-host - Alerts on DDL affecting audited tables or the
auditschema - WORM bucket with versioning, Object Lock in compliance mode and a retention period from your policy
- Shipper running on a schedule with a least-privilege database role and IAM role
- Daily verification of the internal chain and of database hashes against archived hashes, with results retained
- Partition creation automated ahead of time; detaching and dropping only after archival is confirmed
- Superuser access limited, named and reviewed, with the residual risk written into your risk register
Sources
- PostgreSQL wiki: Audit trigger 91plus, the design this schema and trigger function are adapted from
- PostgreSQL documentation: ALTER TABLE (
DISABLE TRIGGER,ENABLE ALWAYS TRIGGER,session_replication_roleinteraction, ownership requirements) - PostgreSQL documentation: CREATE FUNCTION (writing
SECURITY DEFINERfunctions safely) - pgaudit README (log classes and supported versions)
- Amazon S3 User Guide: Locking objects with Object Lock
- AICPA 2017 Trust Services Criteria (revised points of focus, 2022)
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Does SOC2 require database-level audit logs?
No. The Trust Services Criteria describe outcomes, such as monitoring components for anomalies (CC7.2) and evaluating security events (CC7.3), and leave the implementation to you. A database audit trail is strong evidence for those criteria because it also records changes made outside the application, but it is one control among many.
Can a PostgreSQL superuser bypass audit triggers?
Yes. A table owner can disable user triggers with ALTER TABLE ... DISABLE TRIGGER, and a superuser can also set session_replication_role = replica to skip triggers that are not marked ENABLE ALWAYS. You cannot prevent this inside the database. You can detect it with pgaudit DDL logging, a hash chain over audit rows, and hash comparison against copies in write-once storage.
How does the audit trail record which user made a change?
The application calls set_config('app.current_user_id', $1, true) at the start of each transaction, and the trigger reads it with current_setting('app.current_user_id', true). The true flag makes the value transaction-local, so it is safe with connection pooling. PostgreSQL separately records the database role as session_user, which the application cannot forge.
Why not grant INSERT on the audit table to the application?
Because the trigger function is SECURITY DEFINER, it already inserts with the audit owner's privileges. A direct grant adds nothing for legitimate writes and lets anyone holding the application's credentials insert fabricated audit rows.
Will audit tables grow too large over time?
They grow with write volume, so partition the audit table by month. After rows are archived to WORM storage and the retention period in your policy has passed, old partitions can be detached and dropped without slow bulk deletes. Record the last hash of each dropped partition so verification can continue from it.
