📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Design an audit logging system for a financial services platform: every change to customer records and every access to sensitive data must be recorded, the log must be tamper-evident so even an administrator can't quietly alter it, investigators must be able to search years of history quickly, and the main application must not slow down. Walk me through capture, storage, integrity, search and retention.

A full audit logging design: requirements and event-volume estimates, what an audit event contains, reliable capture with an outbox or SaveChanges interceptor, an append-only store with hash chaining and immutable (WORM) storage or SQL Server ledger tables, a separate search index, access control on the audit log itself, and retention under Australian obligations, on Azure with .NET.

Senior SystemDesign Advanced audit-logging compliance immutable-storage ledger-tables system-design tamper-evidence

🎯 Key points

  • Clarify: what must be audited (writes, reads of sensitive data, admin actions), retention (often 7 years), who searches, latency to searchable
  • Audit event: who (user, on-behalf-of), what (action, entity, before/after or diff), when (UTC), where (IP, service), why (reason, correlation id)
  • Capture reliably: audit row in the same transaction (outbox or EF Core SaveChanges interceptor), not a fire-and-forget log line
  • Append-only store: no UPDATE or DELETE permissions; hash chain per stream (each record holds the hash of the previous one)
  • Tamper evidence: SQL Server/Azure SQL ledger tables with database digests stored in immutable Blob storage, or periodic signed checkpoints
  • Immutable (WORM) Blob storage with time-based retention policies for the long-term archive
  • Separate search index (Azure Data Explorer or Azure AI Search) fed asynchronously; the index is not the source of truth
  • Audit the audit log: separate access role, every query of it is itself audited; no PII in the clear beyond what's needed

⏱ 30-second answer

An audit log is evidence, so it must be complete, append-only and tamper-evident. I capture the audit event in the same transaction as the business change (an outbox or an EF Core SaveChanges interceptor), so a change can't happen without its record. Events go to an append-only store: no update or delete rights, each record chained by hash to the previous one, and integrity proven with Azure SQL ledger tables and digests kept in immutable (WORM) Blob storage. The long-term archive is WORM storage with a retention policy, typically seven years. Search runs on a separate index such as Azure Data Explorer, fed asynchronously so the main app isn't slowed. Access to the audit log is itself restricted and audited. The trade-off: stronger tamper evidence costs storage and operational complexity, so match it to the regulatory need.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd start with what counts as an auditable event and why: for a [lending] platform that's every create, update and delete of customer and loan records, every view of sensitive data like identity documents or bank details, every admin and permission change, and every sign-in. Retention is usually [seven years], investigators need to answer questions like 'who viewed this customer's file in March 2024' in seconds, and the audit must survive a malicious insider, including a DBA.

Capture is the part people get wrong. Writing audit entries to the normal application log isn't enough, because logs are sampled, dropped under load and can be deleted. I write the audit event in the same transaction as the change: an EF Core SaveChangesInterceptor records before and after values for audited entities, and read-access events go through an outbox too. That makes the audit as reliable as the data. A relay then ships events to the audit store asynchronously, so the request only pays for one extra insert.

For example, at [company] we [relied on Application Insights logs for audit], and [during an investigation we found gaps from sampling]; [moving to transactional capture with a ledger table] [gave complete records and passed the next external audit without findings].

The store is append-only. The audit service's identity has insert permission only, each record includes the hash of the previous record in its stream, and I use Azure SQL ledger tables, which keep a cryptographic history and let you generate database digests. Those digests go to immutable Blob storage, so verification can prove nothing was altered. Older data is archived to WORM Blob storage with a time-based retention policy. For search, Azure Data Explorer indexes the same events; if the index is wrong, I can rebuild it from the store.

The mistake I see is making the audit log editable by the same admins it's meant to watch. Separation of duties is the point."


Requirements

Type Requirement Assumption
Functional Record writes, sensitive reads, admin actions, sign-ins Defined list of audited entities and actions
Functional Search by user, entity, time range, action Results in seconds over years
Non-functional Complete: no change without an audit record Same-transaction capture
Non-functional Tamper-evident, even to admins Ledger, hash chain, WORM
Non-functional Retention 7 years, then provable deletion Lifecycle with legal hold
Non-functional < 5 ms added to a request Async shipping

Capacity estimate

Quantity Arithmetic Result
Business writes 2M/day 2M audit events
Sensitive reads 3M/day 3M audit events
Total 5M/day ≈ 58/s avg, peak ×5 ≈ 290/s
Size ~1.5 KB/event (diff, context) ≈ 7.5 GB/day ≈ 2.7 TB/year
7 years 2.7 TB × 7 ≈ 19 TB raw (compresses ~5–10× in ADX/Parquet)

High-level design

App services ── same transaction ──► Business DB + AuditOutbox
                                         │ relay (at-least-once, event id dedup)
                                         ▼
                         Audit Ingest service (insert-only identity)
                                 │                          │
                                 ▼                          ▼
               Audit store: Azure SQL ledger table      Azure Data Explorer (search, analytics)
               (append-only, hash-chained)                  ▲ rebuilt from store if needed
                                 │ digests every N min       │
                                 ▼                          │
               Immutable Blob (WORM): digests + monthly archives (7-year retention)
Investigator UI ─► Audit Query API (separate role, every query audited) ─► ADX

Integrity options

Technique Detects Cost Notes
Insert-only permissions Casual edits None Admins can still change grants
Hash chain per stream Edits, deletions, reordering Small CPU, sequential writes per stream Verify by recomputing
Azure SQL ledger tables + digests in WORM Tampering by DBAs Storage for history Built-in verification procedure
WORM Blob (time-based retention) Deletion or overwrite during retention Storage Locked policy can't be shortened
External signed checkpoints Wholesale replacement Key management Sign digests with a Key Vault key

Production example

A lending platform recording [5M] audit events a day moved from log-based audit to transactional capture into a ledger table with digests in immutable storage and Azure Data Explorer for search: investigator queries over [three years] returned in [under 3 seconds], the request overhead was [about 2 ms], and the external auditor accepted the integrity verification report in place of manual sampling.

🔍 What the interviewer is checking

Checks that the candidate treats the audit log as evidence: complete transactional capture, append-only and tamper-evident storage, separation of duties, a derived search index and deliberate retention.

Green flags

  • Audit capture in the same transaction as the change
  • Append-only store, hash chains or ledger tables, digests in immutable storage
  • Separate, audited access to the audit log
  • Derived search index and WORM retention with legal hold

Red flags

  • Application logs used as the audit trail
  • Fire-and-forget audit writes
  • Admins able to edit or delete audit records
  • Full PII copied into the audit log

📚 Learn in depth

1. Audit log vs application log

Application log Audit log
Purpose Diagnose behaviour Evidence of who did what
Completeness Sampling and loss acceptable Must be complete
Mutability Rotated, deleted Append-only, retained for years
Readers Engineers Investigators, auditors, compliance

2. The event shape

{ "eventId": "...", "occurredAt": "2026-03-14T02:11:09Z", "actor": { "userId": "u-123", "onBehalfOf": null, "ip": "203.0.113.7" },
  "action": "Customer.Update", "entity": { "type": "Customer", "id": "c-889" },
  "changes": [{ "field": "Email", "old": "***", "new": "***" }], "reason": "Customer request #4521",
  "correlationId": "00-4bf9...", "service": "customer-api", "prevHash": "9f2c...", "hash": "a71e..." }

Mask or tokenise sensitive values: the audit should prove a field changed without becoming a second copy of all PII.

3. Capture

  • Writes: a SaveChangesInterceptor reads ChangeTracker entries for entities marked [Audited] and adds audit outbox rows before saving, so they commit together.
  • Reads: the handler that returns sensitive data writes an access event to the outbox (a read has no other transaction, so it is a small write).
  • Out-of-band changes (DBAs, scripts): SQL Server Audit or ledger history catches changes that bypass the app.

4. Hash chaining

Each record's hash = SHA-256(previous hash + canonical serialisation of the record). Changing or deleting a record breaks every later hash. Chains per stream (per tenant or per partition) avoid a global serial bottleneck; verification walks each chain.

5. Ledger tables

Azure SQL and SQL Server 2022+ ledger tables keep a cryptographic history of rows. An append-only ledger table blocks UPDATE and DELETE entirely. Database digests (the hash of the latest block) can be stored automatically in immutable Azure Blob storage, and sys.sp_verify_database_ledger checks the data against the digests. This makes tampering detectable even by someone with full database rights.

6. Search

Azure Data Explorer is designed for large append-only event data: fast time-range and filter queries, high compression and retention policies. Azure AI Search fits free-text search over smaller volumes. Either way the index is derived; the ledger and archive are the source of truth.

7. Retention and deletion

Time-based retention on WORM containers prevents deletion during the retention period; a locked policy can't be shortened. Legal holds suspend deletion for investigations. After retention, deletion is itself recorded. Australian context: records-keeping obligations such as AML/CTF and Corporations Act requirements commonly drive seven-year retention, and the Privacy Act (APP 11) requires destroying personal information you no longer need, so retention must be deliberate in both directions.

8. AWS mapping

Amazon QLDB was the managed ledger option but AWS has ended it; on AWS you'd use Aurora/RDS with a hash chain, S3 Object Lock (compliance mode) for WORM, and OpenSearch or Athena for search.

Try it yourself

  1. Create an append-only ledger table in Azure SQL and try an UPDATE.
  2. Generate a database digest, tamper with data via a restored copy, and run the verification procedure.
  3. Write a SaveChangesInterceptor that audits a changed property and test that a failed save writes no audit row.
  4. Implement a hash chain and write a verifier that reports the first broken record.
  5. Load a month of synthetic audit events into Azure Data Explorer and time a query by user and date range.

💻 Code

An EF Core interceptor that writes hash-chained audit rows in the same transaction as the change, and an append-only ledger table.

using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace Audit;

[AttributeUsage(AttributeTargets.Class)] public sealed class AuditedAttribute : Attribute;

public sealed record AuditRecord(Guid Id, string Stream, DateTimeOffset OccurredAt, string ActorId,
    string Action, string EntityType, string EntityId, string ChangesJson, string PrevHash, string Hash);

public interface ICurrentActor { string UserId { get; } }

public sealed class AuditInterceptor(ICurrentActor actor, TimeProvider clock) : SaveChangesInterceptor
{
    public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData e, InterceptionResult<int> result, CancellationToken ct = default)
    {
        var db = e.Context!;
        var entries = db.ChangeTracker.Entries()
            .Where(x => x.Entity.GetType().IsDefined(typeof(AuditedAttribute), false)
                     && x.State is EntityState.Added or EntityState.Modified or EntityState.Deleted)
            .ToList();

        foreach (var entry in entries)
        {
            var changes = entry.Properties
                .Where(p => entry.State != EntityState.Modified || p.IsModified)
                .Select(p => new { field = p.Metadata.Name, changed = true }); // values masked; store tokens if needed
            var stream = entry.Metadata.ClrType.Name; // one chain per entity type avoids a global bottleneck

            // Read the stream's last hash (with UPDLOCK in SQL in real code so chains don't fork under concurrency).
            var prev = await db.Set<AuditRecord>().Where(a => a.Stream == stream)
                .OrderByDescending(a => a.OccurredAt).Select(a => a.Hash).FirstOrDefaultAsync(ct) ?? "GENESIS";

            var rec = new AuditRecord(Guid.NewGuid(), stream, clock.GetUtcNow(), actor.UserId,
                $"{stream}.{entry.State}", stream, entry.Properties.First(p => p.Metadata.IsPrimaryKey()).CurrentValue!.ToString()!,
                JsonSerializer.Serialize(changes), prev, "");
            db.Set<AuditRecord>().Add(rec with { Hash = ComputeHash(rec) }); // saved in the same transaction
        }
        return result;
    }

    public static string ComputeHash(AuditRecord r)
    {
        var canonical = $"{r.PrevHash}|{r.Id}|{r.Stream}|{r.OccurredAt:O}|{r.ActorId}|{r.Action}|{r.EntityId}|{r.ChangesJson}";
        return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonical)));
    }
}
-- Append-only ledger table: UPDATE and DELETE are rejected; history is cryptographically verifiable.
CREATE TABLE audit.AuditRecords (
    Id uniqueidentifier NOT NULL PRIMARY KEY,
    Stream nvarchar(100) NOT NULL,
    OccurredAt datetimeoffset NOT NULL,
    ActorId nvarchar(100) NOT NULL,
    Action nvarchar(200) NOT NULL,
    EntityType nvarchar(100) NOT NULL,
    EntityId nvarchar(100) NOT NULL,
    ChangesJson nvarchar(max) NOT NULL,
    PrevHash char(64) NOT NULL,
    Hash char(64) NOT NULL
) WITH (LEDGER = ON (APPEND_ONLY = ON));

CREATE INDEX IX_Audit_Entity ON audit.AuditRecords (EntityType, EntityId, OccurredAt);

-- The ingest identity can only insert.
GRANT INSERT, SELECT ON audit.AuditRecords TO audit_writer;

-- Verify against digests stored in immutable storage (run on a schedule, alert on failure).
EXEC sys.sp_verify_database_ledger_from_digest_storage;

⚠ Common mistakes

  • Mistake: Using the application log (Serilog, Application Insights) as the audit log. Why it is wrong: sampling, retention limits and deletion make it incomplete and alterable. Instead: a dedicated audit pipeline with transactional capture.
  • Mistake: Writing audit records after the business transaction, fire-and-forget. Why it is wrong: a crash leaves changes without records. Instead: audit rows in the same transaction (interceptor or outbox).
  • Mistake: Giving the audit store the same admins and permissions as the app database. Why it is wrong: the people being audited can edit the evidence. Instead: separate identities, insert-only grants, ledger tables and WORM storage.
  • Mistake: Storing full before/after values of sensitive fields. Why it is wrong: the audit log becomes a second, long-lived copy of PII and a breach target. Instead: mask, tokenise or record that a field changed.
  • Mistake: Relying on separation of duties alone to protect audit content. Why it is wrong: backups, exports and the search index are copies too, and a stolen backup exposes everything. Instead: encryption at rest everywhere (TDE with customer-managed keys in Key Vault for the store, encryption on Blob archives and the ADX cluster), private endpoints, and Always Encrypted or tokenisation for any sensitive value you must keep.
  • Mistake: Searching directly in the ledger store. Why it is wrong: years of data and ad hoc queries slow the store and the app. Instead: a derived search index like Azure Data Explorer.
  • Mistake: A single global hash chain. Why it is wrong: every write serialises on the previous hash. Instead: chains per stream or partition, verified independently.
  • Mistake: Forgetting reads of sensitive data. Why it is wrong: most investigations ask who looked at a record, not who changed it. Instead: audit access events for sensitive data.
  • Mistake: Keeping audit data forever by default. Why it is wrong: APP 11 requires destroying personal information you no longer need. Instead: deliberate retention with legal holds and recorded deletion.

🏛 Senior insight: trade-offs

Tamper evidence is a spectrum, and I pick the level from a short risk assessment: who could want to alter the record (a careless developer, a fraudulent employee, a DBA, an outside attacker), and what the regulator expects. For an Australian lender or bank that usually means: AML/CTF record-keeping rules (records generally kept for seven years), APRA CPS 234 for regulated entities (information security controls and the ability to detect and respond to incidents), and the Privacy Act's APP 11 (protect personal information, and destroy it when no longer needed) and the NDB scheme (you must be able to assess who accessed what). Those push toward ledger tables with external digests, WORM archives and audited access. An internal HR tool might only need insert-only permissions and a hash chain.

Each step adds cost: ledger history storage, verification jobs, an extra index to secure, and locked retention policies that can't be undone. I also separate the write path (transactional, about one extra insert per request) from the read path (indexed, derived, rebuildable), which keeps the business app fast; the performance cost of strong capture is small, while the business cost of a gap found during an investigation is large.

Option When it fits Cost When not to
Ledger tables + digests in WORM Regulated data, insider threat History storage, verification jobs Low-risk internal tools
Hash chain in your own store Any database, portable You build and verify it When a built-in ledger exists
WORM Blob archive Long retention, deletion protection Storage; locked policy is irreversible Data you may need to erase early
ADX / AI Search index Fast investigation queries Extra copy to secure Tiny volumes (query the store)

I measure capture completeness (audit events vs business writes, reconciled daily), ingest lag, verification results, query latency for investigators, and who queried the audit log.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions investigations or breaches Why: Checks using audit evidence in a Notifiable Data Breach assessment
    How to answer

    I'd need a timeline (pushed, detected, rotated), who could access the secret (collaborators, forks, visibility), and resource logs for the exposure window showing every use of the credential came from our own workloads: SQL audit logins by principal and client IP, Storage logs filtered on account-key authentication, Activity Log for key listing. Alongside that, an assessment of what data the credential could reach and how sensitive it is, because that drives the serious-harm test. All of this should be captured through the organisation's data breach response plan, which defines who assesses, who decides and who talks to the OAIC. Without logs, we can't positively show there was no access, so the privacy officer has to weigh the likelihood of access against the data's sensitivity, often more conservatively. The fix is SQL auditing and Storage diagnostic logs everywhere with retention well beyond the 30-day assessment window, and removing the credential type altogether.

  2. When: Candidate mentions capturing changes made outside the application Why: Checks database-level change capture options for out-of-band changes
    How to answer

    Change tracking records which primary keys changed since a version number, synchronously and cheaply, but keeps no old values or history of intermediate changes; you re-read the current row. CDC reads the transaction log asynchronously and writes change tables with before and after values for every change, so it suits feeding a warehouse or an event stream. Change tracking fits "sync what changed" (mobile sync, cache refresh); CDC fits auditing column values or streaming to Kafka or Fabric. CDC costs more storage and on Azure SQL needs S3+ or vCore.

  3. When: Candidate mentions writing audit events in the same transaction Why: Checks reliable capture with the outbox pattern
    How to answer

    The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.

    The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.

    A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.

🛠 Real-world problems: how you handle them

Gaps in a log-based audit trail found during an investigation
Situation
A [consumer lending] platform with [400,000] customers; audit relied on structured logs sent to Application Insights with [adaptive sampling] and [90-day] retention.
Signals
A [privacy complaint] asked who had viewed a customer's file; the logs showed some accesses but not others, and anything older than [90 days] was gone. The external auditor raised a finding.
Investigation
Compared application request telemetry with the audit log entries for the same period and found [about 12%] missing due to sampling; confirmed DBAs could also edit the separate audit table.
Resolution
Immediate: disabled sampling for audit events and extended retention while the new design was built. Long term: transactional capture via a SaveChanges interceptor and outbox, an append-only Azure SQL ledger table with digests in immutable Blob storage, Azure Data Explorer for search and seven-year WORM archives.
Prevention
Daily reconciliation of business writes against audit events, scheduled ledger verification with alerts, a separate audit-reader role whose queries are audited, and an ADR documenting retention.

How to tell it (STAR)

**S:** At [company] a [privacy complaint] asked who had viewed a customer's file, and our log-based audit trail had gaps. **T:** I had to make the audit complete and defensible to an external auditor. **A:** I showed that sampling had dropped about [12%] of events and that DBAs could edit the audit table. I moved capture into the same transaction as each change, stored events in an append-only ledger table with digests in immutable storage, added Azure Data Explorer for investigators, and set up daily reconciliation. **R:** The next audit closed the finding with [no new issues], and investigators answered access questions over [three years] in [seconds].

More in Systems to Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me