Audit Trail Design for Payment Platforms
Last Updated: 2026-12-01 Status: Complete
An audit trail is an append-only record of who did what, to which object, when, from where, and whether it worked. This page shows how to design one for a PayFac platform: what events to capture, a schema that satisfies PCI DSS Requirement 10, how to make the log append-only and tamper-evident, how long to keep it, and how to keep sensitive values out of it. By the end you should be able to answer "who viewed this merchant's bank details in the last 30 days?" with a single indexed query.
PCI DSS requirement numbers and retention values below follow PCI DSS v4.0.1 — all future-dated requirements mandatory since 31 March 2025. Values are tracked on Key Numbers. Confirm how Requirement 10 applies to your systems with your QSA.
Quick Reference
| Topic | Rule of thumb |
|---|---|
| Retention (CDE systems) | At least 12 months of audit log history, with the most recent three months immediately available for analysis |
| Other records | Keep per the longest applicable duty. BSA: Five years (31 CFR 1010.430(d)); bank CIP identifying information five years after the account is closed (31 CFR 1020.220(a)(3)(ii)) where it applies to you (check your sponsor bank agreement) |
| Write path | INSERT-only grants, separate store, shipped off the application host quickly (Req 10.3.3) |
| Tamper evidence | Hash chain plus periodic external anchoring and a verification job |
| PII | Store reference ids and masked diffs, never raw sensitive values |
| Reads | Log reads of sensitive data, not only writes |
| Clock | Synchronized time source on every system (Req 10.6) |
Why Does a Payment Platform Need an Audit Trail?
- PCI DSS Requirement 10 expects logging and monitoring for systems in the cardholder data environment (CDE). Background: PCI DSS Requirements.
- Sponsor bank and regulator inquiries. Your sponsor bank will ask who approved a merchant, who changed a payout destination and when.
- Merchant disputes about who changed what. "Our bank account was changed" is a classic fraud and support case.
- Internal investigations after an account takeover, insider abuse or a bad deployment.
If you suspect an actual breach, stop here and follow Incident Response. The audit trail is the evidence you will rely on, so it must survive the incident.
Audit Log vs Application Log vs Ledger
These three are often confused. They have different purposes, consumers and retention, so keep them in different stores.
| Audit log | Application log | Ledger | |
|---|---|---|---|
| Question answered | Who did what to which object? | Why did the code behave this way? | Where is the money? |
| Written by | A dedicated audit service | Every service, freely | The posting service, transactionally |
| Content | Structured, curated, stable schema | Free-form, debug detail | Balanced journal entries |
| Mutability | Append-only, tamper-evident | Rotated, may be sampled | Append-only, corrected by reversing entries |
| Audience | Security, compliance, support, auditors | Engineers | Finance, reconciliation, auditors |
| Retention | Compliance-driven (see below) | Short, cost-driven | Financial-record retention |
| Sensitive data | References and masked diffs only | Never PAN, SAD or PII | Amounts and account ids only |
The ledger records money movement; it is not a record of who clicked what. See Double-Entry Ledger.
What Should You Log?
PCI DSS 10.2.1 Events
Requirement 10.2.1.1 to 10.2.1.7 lists the events that must be captured for in-scope systems:
| Req | Event |
|---|---|
| 10.2.1.1 | Individual user access to cardholder data |
| 10.2.1.2 | All actions taken by anyone with administrative access |
| 10.2.1.3 | Access to audit logs |
| 10.2.1.4 | Invalid logical access attempts |
| 10.2.1.5 | Changes to identification and authentication credentials, including new accounts and privilege elevation |
| 10.2.1.6 | Initialization, starting, stopping or pausing of the audit logs |
| 10.2.1.7 | Creation and deletion of system-level objects |
Business Events a PayFac Adds
PCI does not tell you which business actions matter. Your merchants, sponsor bank and fraud team do.
| Category | Examples |
|---|---|
| Money destination | Bank account added or changed, payout destination changed, payout schedule changed |
| Commercial terms | Pricing plan assigned, fee override, reserve percentage or hold changed |
| Money movement | Payout approved or released manually, manual ledger adjustment, refund above a limit |
| Identity and access | Role granted or revoked, user invited, MFA reset, API key created or revoked |
| Support | Impersonation session started and ended, every action taken inside it |
| Lifecycle | Merchant approved, suspended, terminated, underwriting decision overridden |
| Reads of sensitive data | Bank details viewed, KYC document opened, full application exported |
Why Log Reads?
Writes tell you what changed. Reads tell you who looked. Insider snooping, scraped merchant data and a compromised support account all show up as reads, so Requirement 10.2.1.1 (individual access to cardholder data) and your own PII policy point the same way. Log a read when the data is sensitive and the read is a deliberate act (opening a bank-details panel, downloading a document). Do not log every list-page row render; log the explicit reveal, with the target and the reason if you collect one.
How Should the Audit Event Schema Look?
PCI DSS 10.2.2 says each entry records six elements. Design the schema so each has a column.
| Req 10.2.2 element | Column(s) |
|---|---|
| User identification | actor_type, actor_id, on_behalf_of |
| Type of event | action |
| Date and time | occurred_at (UTC, synchronized clock) |
| Success or failure | outcome |
| Origination of event | source_ip, user_agent, request_id, trace_id |
| Identity of the affected data, component or resource | target_type, target_id, tenant_id |
CREATE TABLE audit_event (
event_id uuid NOT NULL,
chain_id text NOT NULL, -- e.g. tenant id, one hash chain per tenant
chain_seq bigint NOT NULL, -- assigned by the sealing worker
occurred_at timestamptz NOT NULL, -- NTP-synchronized clock (Req 10.6)
recorded_at timestamptz NOT NULL DEFAULT now(),
actor_type text NOT NULL
CHECK (actor_type IN ('user','api_key','system_job','support_impersonation')),
actor_id text NOT NULL,
on_behalf_of text, -- merchant user or platform acting for a connected account
tenant_id uuid NOT NULL,
action text NOT NULL, -- 'payout_destination.update', 'bank_details.read'
target_type text NOT NULL,
target_id text NOT NULL,
outcome text NOT NULL CHECK (outcome IN ('success','failure','denied')),
source_ip inet,
user_agent text,
request_id text,
trace_id text, -- W3C traceparent trace id
diff jsonb, -- before/after, sensitive fields redacted
prev_hash bytea,
record_hash bytea NOT NULL,
PRIMARY KEY (event_id, occurred_at), -- partition key must be in the key
UNIQUE (chain_id, chain_seq, occurred_at) -- see note: does not make chain_seq unique by itself
) PARTITION BY RANGE (occurred_at);
CREATE INDEX audit_event_target_idx ON audit_event (tenant_id, target_type, target_id, occurred_at DESC);
CREATE INDEX audit_event_tenant_idx ON audit_event (tenant_id, occurred_at DESC);
CREATE INDEX audit_event_actor_idx ON audit_event (tenant_id, actor_id, occurred_at DESC);
-- Unpartitioned, one row per chain; updated in the same transaction as every insert
CREATE TABLE audit_chain_head (
chain_id text PRIMARY KEY,
last_seq bigint NOT NULL,
last_hash bytea NOT NULL
);
PostgreSQL cannot enforce uniqueness on (chain_id, chain_seq) alone in a table partitioned by time, because a unique constraint on a partitioned table must include the partition key. The constraint above therefore allows two rows with the same chain_seq and different timestamps. Enforce sequence integrity with audit_chain_head: the sealing worker locks the chain's head row, checks that the new chain_seq is last_seq + 1, inserts the event with prev_hash = last_hash, and updates the head row, all in one transaction. The row lock also serializes writers per chain. The database role that updates audit_chain_head is the same restricted writer role, and the verification job cross-checks the head against the latest event.
export type ActorType = 'user' | 'api_key' | 'system_job' | 'support_impersonation';
export interface AuditEvent {
eventId: string; // UUID generated by the caller
occurredAt: Date; // UTC
actorType: ActorType;
actorId: string; // user id, API key id (never the secret), job name
onBehalfOf?: string; // e.g. the merchant user being impersonated
tenantId: string;
action: string; // stable, dotted verb: 'api_key.create'
targetType: string;
targetId: string; // reference id, never a raw value
outcome: 'success' | 'failure' | 'denied';
sourceIp?: string;
userAgent?: string;
requestId?: string;
traceId?: string;
diff?: Record<string, { before?: unknown; after?: unknown }>; // pre-redacted
}
When support impersonates a merchant user, record the support agent as actor_id, support_impersonation as actor_type and the merchant user as on_behalf_of. Never record the merchant user as the actor, or the trail will blame the wrong person.
How Do You Make the Log Append-Only?
Layer the controls so that no single compromised credential can rewrite history (Req 10.3.2: protect logs from modification).
- INSERT-only grants. The audit writer role gets
INSERTand nothing else. Application roles get no access to the table; readers use a separateSELECT-only role. - Triggers rejecting change. A defence in depth against a grant mistake.
- A separate account and store. The log pipeline runs in its own cloud account or database cluster with its own administrators, so application admins cannot alter it.
- Write-once object storage. Archive to storage with a retention lock. AWS S3 Object Lock, for example, provides write-once-read-many storage in governance or compliance modes (see References).
- Prompt shipping. Send events to a secure, central, internal log store or other hard-to-modify media as they occur (Req 10.3.3), not in a nightly batch.
- Change detection. Apply file-integrity monitoring or change-detection to the logs (Req 10.3.4). The hash chain below also detects changes.
REVOKE ALL ON audit_event FROM PUBLIC;
GRANT INSERT ON audit_event TO audit_writer;
GRANT SELECT ON audit_event TO audit_reader;
CREATE FUNCTION audit_event_reject_change() RETURNS trigger AS $$
BEGIN
RAISE EXCEPTION 'audit_event is append-only';
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER audit_event_no_update_delete
BEFORE UPDATE OR DELETE ON audit_event
FOR EACH ROW EXECUTE FUNCTION audit_event_reject_change();
Dropping old partitions is a schema operation, not a row delete. Restrict who can run it, log it (Req 10.2.1.7 covers deletion of system-level objects) and only do it after the data is safely in the cold tier.
How Do You Make the Log Tamper-Evident?
Append-only controls prevent changes. Tamper evidence proves nothing changed even if someone with enough privilege bypassed them.
Hash chaining. Each record stores the hash of the previous record in the same chain. Altering or removing any record breaks every hash after it.
import { createHash } from 'crypto';
function sealRecord(prevHash: Buffer | null, canonicalEvent: string): Buffer {
return createHash('sha256')
.update(prevHash ?? Buffer.alloc(0))
.update(canonicalEvent) // deterministic JSON: sorted keys, UTC ISO timestamps
.digest();
}
// record_hash = sealRecord(prev_hash, canonicalize(event fields incl. chain_id, chain_seq))
Anchoring. A chain proves internal consistency, but an attacker who can rewrite the whole table can recompute every hash. So periodically (for example hourly) take the latest chain head, sign it with a key held in a KMS or HSM, and write it to a separate write-once store or an external timestamping service. The verification job then recomputes the chain from the last anchor and alerts on any mismatch.
Trade-offs:
| Decision | Consequence |
|---|---|
| One global chain | Strong ordering, but a single sequential writer bottleneck |
| One chain per tenant (or per shard) | Parallel writers, easier per-tenant export and verification; cross-tenant ordering relies on timestamps |
Sealing worker assigns chain_seq | Hash computed off the request path, so the audit write never blocks a payment; events appear slightly after they occur |
| Verification cost | Grows with chain length; verify incrementally from the last anchor |
Do not block a payment on a synchronous audit write unless policy demands it for a specific action (for example a payout approval). For those, write the audit event in the same transaction as the business change, using the pattern in Event-Driven Architecture, and fail closed.
How Long Do You Keep Audit Data?
| Data | Retention driver |
|---|---|
| Audit logs for CDE systems | At least 12 months of audit log history, with the most recent three months immediately available for analysis |
| Records subject to the Bank Secrecy Act | Five years (31 CFR 1010.430(d)); bank CIP identifying information five years after the account is closed (31 CFR 1020.220(a)(3)(ii)) Check your sponsor bank agreement for what flows down to you |
| ACH authorization records | Two years from the termination or revocation of the authorization |
| Transaction and sub-merchant records | Set by your sponsor bank agreement and network rules; confirm with legal |
Many teams keep audit events for the longest applicable period rather than tracking dozens of schedules, then delete by partition. Keep three rules in mind:
- Legal holds suspend deletion for the affected tenant or target, whatever the schedule says. Model a hold as a flag your retention job checks.
- Hot vs cold tiers. Keep the recent window in the queryable database (retention rule: At least 12 months of audit log history, with the most recent three months immediately available for analysis) and move older partitions to write-once object storage in a columnar format that a query engine can scan.
- Retention is a policy decision, not an engineering default. Confirm with legal counsel and your QSA.
How Do You Answer "Every Action on Merchant X in the Last Two Years"?
Partition by month on occurred_at, index by (tenant_id, target_type, target_id, occurred_at DESC) and use audit_event_tenant_idx (tenant_id, occurred_at DESC) for everything recorded under that merchant's tenant_id, whatever the target. A query then prunes to 24 partitions and uses the index in each. For the cold tier, store the same columns in partitioned object-storage files (path prefixed by tenant and month) so a query touches only that merchant's files. Test the "two years of one merchant" query with production-sized data before you need it in an inquiry.
SELECT occurred_at, actor_type, actor_id, action, target_type, target_id, outcome
FROM audit_event
WHERE tenant_id = $1
AND occurred_at >= now() - interval '2 years'
ORDER BY occurred_at DESC;
-- "Who viewed this merchant's bank details in the last 30 days?"
SELECT occurred_at, actor_id, on_behalf_of, source_ip
FROM audit_event
WHERE tenant_id = $1 AND target_type = 'bank_account' AND action = 'bank_details.read'
AND occurred_at >= now() - interval '30 days';
How Do You Keep PII Out of Audit Logs?
Audit logs live long and are widely read, so they are a classic place for PII to leak and then outlive a deletion request.
- Reference ids, not values. Log
bank_account_id: ba_[redacted], not the account number. - Masked diffs. For sensitive fields, record that the field changed, not its value:
{"bank_account": {"before": "changed", "after": "changed"}}, or a masked form such as the last four digits where policy allows. - Allowlist what is diffed. Only fields on an explicit per-entity allowlist enter
diff. A new column does not silently start leaking. - Never place PAN, SAD, SSNs or full bank numbers in
diff,user_agentfree text or error messages. See Handling PII and Card Data. - Deletion requests: audit rows still contain actor identifiers and IP addresses, which are personal data. Keep them only under a documented basis and confirm with legal counsel.
Reviewing Logs and Alerting
Requirement 10.4 requires log review: 10.4.1 covers daily review of security events and 10.4.1.1 expects automated mechanisms to do it. In practice, alert on:
- Role grants to admin roles, MFA resets, new API keys with write scopes
- Payout destination changes followed by a payout within a short window (set the window from your own risk appetite)
- Bursts of
bank_details.reador document reads by one actor, measured against that actor's baseline - Failed access attempts (10.2.1.4) clustered by IP or account
- Any change to audit configuration (10.2.1.6) or access to the logs (10.2.1.3)
Wire these to your security team's alert path, and see Observability for alert design. Alerting on audit events also addresses OWASP's security logging and alerting failures category (OWASP Top 10:2025 for web applications; OWASP API Security Top 10:2023 for APIs).
NestJS Example: An Audit Service and Interceptor
The service never receives raw sensitive values: callers pass reference ids and a pre-redacted diff.
@Injectable()
export class AuditService {
constructor(@Inject(AUDIT_SINK) private readonly sink: AuditSink) {}
async record(event: Omit<AuditEvent, 'eventId' | 'occurredAt'>): Promise<void> {
await this.sink.enqueue({
...event,
eventId: randomUUID(),
occurredAt: new Date(), // host clock must be NTP-synchronized
});
}
}
export const Audited = (action: string, targetType: string) =>
SetMetadata('audit', { action, targetType });
@Injectable()
export class AuditInterceptor implements NestInterceptor {
constructor(private readonly reflector: Reflector, private readonly audit: AuditService) {}
intercept(ctx: ExecutionContext, next: CallHandler): Observable<unknown> {
const meta = this.reflector.get<{ action: string; targetType: string }>('audit', ctx.getHandler());
if (!meta) return next.handle();
const req = ctx.switchToHttp().getRequest();
const base = {
actorType: req.user.type, actorId: req.user.id, onBehalfOf: req.user.onBehalfOf, // req.user: set by the JWT and API-key guards
tenantId: req.tenantId, action: meta.action, targetType: meta.targetType,
targetId: req.params.id, sourceIp: req.ip,
userAgent: req.headers['user-agent'], requestId: req.id,
};
return next.handle().pipe(
tap(() => void this.audit.record({ ...base, outcome: 'success' }).catch((e) => this.alertAuditFailure(e))),
catchError((err) => {
const denied = err instanceof ForbiddenException;
void this.audit.record({ ...base, outcome: denied ? 'denied' : 'failure' })
.catch((e) => this.alertAuditFailure(e)); // a lost audit event must page someone
return throwError(() => err);
}),
);
}
}
In NestJS, guards execute before interceptors, so a request rejected by an authentication or roles guard never reaches AuditInterceptor. Invalid logical access attempts (Req 10.2.1.4) must therefore be recorded from a global exception filter or inside the guards themselves, with outcome denied or failure. Use alertAuditFailure (omitted here) to raise an alert if the audit pipeline rejects a write.
Usage: @Audited('bank_details.read', 'bank_account') on the controller method that reveals bank details. The interceptor deliberately does not read the request or response body, so it cannot leak sensitive values. Handlers that need a diff build it from an allowlisted, redacted structure and call AuditService.record themselves. For high-risk actions, write the audit event in the same database transaction as the change instead of fire-and-forget.
Common Mistakes
- Letting the application database role own, update or delete audit rows
- Using the application server clock without synchronization, which makes event ordering unreliable across hosts
- Logging only writes, so insider reads are invisible
- Storing raw before/after values that include bank numbers or document contents
- Treating the application log as the audit trail because it is "already there"
- Never running the chain verification job, so tampering is never detected
- Deleting audit partitions without checking legal holds
Related Topics
- Handling PII and Card Data: what must never appear in an audit diff
- Access Control for Payment APIs: the actors, roles and impersonation you are recording
- Double-Entry Ledger: the financial record that complements the audit trail
- Event-Driven Architecture: reliable event delivery to the audit pipeline
- PCI DSS Requirements: Requirement 10 in context
- Check your understanding: Security Quiz
References
- PCI DSS v4.0.1 and supporting documents: PCI Security Standards Council (Requirements 10.2 to 10.6)
- eCFR: 31 CFR 1010.430, Nature of records and retention period: U.S. Government
- OWASP Top 10:2025: OWASP Foundation, 2025
- Locking objects with Object Lock: Amazon Web Services documentation (vendor)
- W3C Trace Context: W3C Recommendation