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.
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.
"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
SaveChangesInterceptorrecords 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."
| 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 |
| 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) |
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
| 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 |
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.
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
Red flags
| 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 |
{ "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.
SaveChangesInterceptor reads ChangeTracker entries for entities marked [Audited] and adds audit outbox rows before saving, so they commit together.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.
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.
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.
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.
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.
SaveChangesInterceptor that audits a changed property and test that a failed save writes no audit row.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;
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.
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.
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.
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.
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].
Last updated 23 Nov 2026.