SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • Three Pillars of Observability
  • Logging Best Practices
  • Log Aggregation
  • Metrics and Instrumentation
  • Distributed Tracing
  • Alerts and Monitoring
  • Dashboards and Runbooks
  • SLOs and Error Budgets
  • Incident Management and Postmortems
  • Profiling
  • Audit Logs
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Observability

Audit Logs

A tamper-resistant record of who did what and when, for security, compliance and investigations.

⏱ 11 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An audit log is a record of who did what, to which thing, and when, kept so that people can check the facts later. It is for security, compliance and investigations, not for debugging code.

  • Each entry answers: who (actor), what (action), on what (resource), when, from where, and did it work (result).
  • It must be hard to change. Append-only, write-once storage, and hash chaining make tampering visible.
  • It must not leak. Record that a password changed, never the password itself.

02Concept: What is it?

An application log helps a developer fix a bug: stack traces, debug messages, timings. An audit log helps an auditor, a security team or a lawyer answer questions like "who gave Bob admin rights?" or "who exported the payroll file last Tuesday?". The audience is different, so the rules are different.

What makes a log an audit log

Application logAudit log
PurposeDebug and operate the systemProve who did what
ReaderDevelopers and on-call engineersSecurity, compliance, auditors, legal
ContentFree text, errors, timingsStructured: actor, action, resource, result
CompletenessSampling and dropping is fineMust not lose events
RetentionDays or weeksMonths or years, by policy
TamperingNot a concernMust be prevented or detected
One audit entry, in plain words
πŸ‘€Whoalice (user id 42)
⚑Did whatgrant admin
🎯To whatuser bob
πŸ•’When2026-12-04 09:03:11Z
🌍From whereIP, device, request id
βœ…Resultok or denied
Seven questions. If you cannot answer one of them later, the log is weaker than it looks.
🧠Failed attempts count too
Denied logins and refused requests are often the most useful entries. A pattern of denials is how you notice someone knocking on doors.

03Real-Life Example

🍡The Bank Vault Sign-In Book
A bank vault has a bound book at the door. Everyone who enters signs in ink with the time, their name and the reason. Pages are numbered and cannot be torn out without a gap showing. The book is kept by a different person from the one who guards the vault. If cash goes missing, the manager opens the book instead of asking everybody to remember.
Vault book
Audit log
Name, time, reason
Actor, timestamp, action
Signed in ink
Written once, never edited (append-only)
Numbered pages, no torn-out pages
Hash chain: a missing or changed entry shows
Kept by someone else
Separate account, write-only for the app
Copy kept in another building
Off-site, write-once copy
Checked when cash goes missing
Queried in an investigation
Keep the book for seven years
Retention policy

04Why Do We Need It?

πŸ•΅οΈInvestigations
After a breach or a mistake, the audit log is the evidence of what happened.
πŸ“‹Compliance
Rules and standards such as SOC 2, PCI DSS and HIPAA expect you to record access to sensitive data.
🚨Detection
Odd patterns (an admin created at 3 am, mass exports) can raise an alert.
βš–οΈAccountability
People behave differently when they know actions are recorded.
🧾Disputes
Prove that a customer changed their own settings, or that support did.
πŸ”§Change tracking
Know who changed a config or a permission before the outage started.
Logs for developers answer "what broke?". Audit logs answer "who did it, and can we prove it?"

05Where Do We Use It?

☁️Cloud accounts
Every API call to create, change or delete a resource is recorded by the cloud provider.
πŸ—„οΈDatabases
Who read or changed sensitive tables, and which admin ran which command.
🏒Admin consoles
Permission changes, user creation, impersonation, config edits.
πŸ’³Payments
Refunds, limit changes and manual overrides need a trail.
πŸ₯Health and finance
Access to patient or account records, including who looked.
πŸ”Identity systems
Logins, MFA changes, password resets, token and key use.

06Types / Parts / How It Works

What to record, and what to keep out

Record theseNever put these in the log
Logins, logouts, failed logins, MFA changesPasswords, even wrong ones
Permission and role changesAPI keys, session tokens, private keys
Access to sensitive records (who read what)Full card numbers or full personal records
Admin actions, impersonation, config changesWhole request bodies by default
Data exports and deletionsAnything you could not show to an auditor
Changes to the audit settings themselvesFree-text that may contain personal data

Log the fact and an id ("password changed for user 42"), not the secret. For a data change you can keep the old and new values of a non-sensitive field, or a pointer to a version.

How to make it tamper-evident

A hash chain
1️⃣Entry 1hash H1 = h(0 + e1)
→↓H1
2️⃣Entry 2H2 = h(H1 + e2)
→↓H2
3️⃣Entry 3H3 = h(H2 + e3)
Each entry stores a hash of the one before it. Change or remove one entry and every hash after it stops matching.

Layers of protection

Defence in depth for the log itself
Write path
βž•Append-onlyno update, no delete
πŸ”‘Write-only accountthe app cannot read or erase
Storage
🧱WORM storagewrite once, read many
🌍Off-site copyanother account or region
Checks
πŸ”—Hash chaindetect edits and gaps
πŸ•’Trusted timesynced clocks
Prevent Store safely Detect
VisualizerTamper with a log, chained and plainEdit or delete any entry. In the plain log nothing complains. Switch to the hash-chained log and try again: verification points at the first entry that no longer matches.
Kind of log
#TimeWhoActionResourceResultChain hashActions
109:01aliceloginconsoleok224519
209:03alicegrant adminuser boboka7f42f
309:12bobreadpayroll.csvoke0e318
409:15bobexportpayroll.csvoka2288c
509:20carolloginconsoledenied299cec
609:41bobdeleteaudit-configdeniedaa5010
710:02alicerevoke adminuser bobokec0246
810:30davereadcustomersok667c14
Entries
8 / 8
First bad entry
none
from verification
Tampering
none
The log is intact. Pick an entry and edit or delete it, as an attacker or a careless admin might.

Each chain hash is hash(previous hash + this entry). Here a small teaching hash (FNV-1a, 6 hex characters) stands in so the page needs no libraries. A real audit log uses a cryptographic hash such as SHA-256, plus write-once storage and an off-site copy, because an attacker who can rewrite the whole log can also recompute the whole chain.

07How to Use It / Steps / Implementation

Building an audit log

  1. 1
    Decide what must be audited
    Start with authentication, permission changes, access to sensitive data, admin actions and config changes. Ask your compliance team too.
  2. 2
    Define one structured shape
    The same fields for every event, in JSON, so you can search and alert on them.
  3. 3
    Record at the service, not the client
    A client can lie or be skipped. Write the entry on the server, next to the authorisation check.
  4. 4
    Write it reliably
    A lost audit event is a gap. Write it in the same database transaction as the change, or with an outbox, and publish it asynchronously.
  5. 5
    Ship it to a separate place
    Send the entries to a different account or system that the application and its admins cannot edit.
  6. 6
    Make it tamper-evident
    Use write-once storage, and add hash chaining or signed checkpoints so a change can be detected.
  7. 7
    Set retention and access
    Keep for as long as policy says. Limit who can read the log, and log that access too.
  8. 8
    Alert and review
    Alert on risky patterns, and review access regularly. A log nobody reads protects nobody.
An example entry (JSON)
{
  "time": "2026-12-04T09:03:11Z",
  "actor": { "id": "u_42", "type": "user" },
  "action": "role.grant",
  "resource": { "type": "user", "id": "u_77" },
  "details": { "role": "admin" },
  "result": "success",
  "source_ip": "203.0.113.9",
  "request_id": "req_8f2c",
  "prev_hash": "a41c09..."
}
πŸ’‘Do not slow the user down
Writing the entry must not make the request slow. Put it on a queue or use the outbox pattern, but never drop it silently if the queue is down.

08Key Terms to Know

TermMeaning in easy words
Audit logA tamper-resistant record of who did what, to what, and when
ActorThe user, service or admin who performed the action
Append-onlyNew entries can be added, but old ones cannot be changed or removed
WORMWrite once, read many: storage that refuses edits after writing
Hash chainEach entry includes the hash of the previous one, so edits break the chain
Tamper-evidentA change cannot be prevented, but it can be detected
Non-repudiationThe actor cannot credibly deny having done the action
RetentionHow long the log must be kept
Legal holdAn order to keep certain records even beyond normal retention
Separation of dutiesThe people who run a system cannot edit its audit trail
Request IDA value that ties an audit entry to the logs and traces of the same request
SIEMA security tool that collects logs and raises alerts

09Pros, Cons and Trade-offs

βœ… Pros
  • Evidence for investigations and disputes
  • Helps meet compliance expectations
  • Deters misuse, and helps detect it
  • Shows exactly what changed
  • Builds customer and auditor trust
⚠️ Cons
  • Storage grows quickly and costs money
  • Needs careful design to avoid leaking data
  • Reliable writes add complexity
  • Long retention conflicts with privacy rules unless handled
  • A log nobody reviews gives false comfort

Trade-offs

ChoiceWe gainWe lose
Log every readFull visibility of data accessHuge volume and cost
Log only writes and admin actionsSmaller and simplerNo record of who looked
Synchronous writeNo lost entriesSlower requests
Async via queue or outboxFast requestsMore parts to run, brief delay
Hash chain onlyCheap tamper detectionAn attacker with full write access can rebuild it
WORM plus off-site copyStrong protectionCost and harder to correct mistakes

10Common Problems and Mistakes

Common mistakes

  1. Mixing audit and debug logs. Debug logs get sampled, rotated and edited. Audit logs must not.
  2. Logging secrets or full personal data. The audit log becomes the most sensitive file you own.
  3. Letting admins edit it. The people being audited must not control the evidence.
  4. Missing failures. Only logging successes hides probing and attacks.
  5. Unsynced clocks. Entries from different servers cannot be put in order.
  6. No retention plan. Either the log is deleted too early, or it is kept forever and becomes a liability.
  7. Never reading it. No alerts and no reviews means the first reader is the investigator.

Things to watch

πŸ•’Clock trust
Use synced time (NTP) and a server-side timestamp, never the client’s.
🧹Right to erasure
Privacy laws may ask you to delete personal data. Store ids, not names, and plan how to handle requests.
πŸ“¦Volume
Reads of sensitive data can be very frequent. Decide what to log and what to sample elsewhere.
πŸ”„Rewriting the whole chain
An attacker with full control can recompute a chain. Keep a copy elsewhere, or sign checkpoints.

11Real-World Examples

☁️Cloud audit trails
AWS CloudTrail, Google Cloud Audit Logs and Azure Activity Log record API calls in your account.
πŸ—„οΈDatabase auditing
PostgreSQL extensions such as pgaudit and similar features in other databases record statements and access.
πŸ™Source hosting
Git hosts keep an audit log of organisation changes: members, permissions, tokens, settings.
πŸ”—Certificate Transparency
A public, append-only log of issued certificates, built on Merkle trees.
🧾Ledger databases
Some databases keep a cryptographically verifiable history of every change.
πŸ›°οΈSIEM tools
Collect audit logs from everywhere, and alert on suspicious sequences.
πŸ“Note
Compliance standards name expectations, not exact designs. Ask your own compliance or legal team what applies to you.
Mini case: who exported the payroll?
πŸ§‘β€πŸ’Όbob exports payroll.csvrequest req_8f2c
→↓audit entry
🧱Write-once storehash-chained
→↓rule: large export
🚨Alert to securityreviewed within the hour
Request ids tie the audit entry to the traces and application logs for the same call.

12Related Topics to Read Next

Logging Best Practices→

What to log in general, and what never to write.

Merkle Trees→

Hash trees for proving a log was not changed.

Outbox Pattern→

Write the audit event safely with the change itself.

Event Sourcing→

Stores every change as an event, which is naturally an audit trail.

NTP: Network Time Protocol→

Why audit timestamps need synced clocks.

RBAC→

The permission changes that audit logs must capture.

Secrets Management→

Why secrets must stay out of the log.

Data Privacy and GDPR Basics→

Balance retention against the right to erasure.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Entry: who, what, on what, when, from where, result, request id.
  • βœ”Different from debug logs: structured, complete, long-lived, protected.
  • βœ”Record: auth events, permission changes, sensitive access, admin and config changes.
  • βœ”Never record: passwords, keys, tokens, full personal data.
  • βœ”Protect: append-only, write-only account, WORM storage, off-site copy.
  • βœ”Detect: hash chain or signed checkpoints.
  • βœ”Write safely: same transaction or outbox, then async.
  • βœ”One line: β€œA bound book that nobody can tear a page out of without it showing.”
← Previous
Profiling
Next β†’
SSL/TLS