Software engineering, data and AI · Headquartered in Scotland, delivering internationally| Start a project →
← All insights
Tutorials

Hash-chained audit logs in Django

AMAyoolumi Melehon 10 November 2026 11 min read

A tamper-evident audit pattern we use on every AANDA Labs engagement. Three models, two signal handlers, and a periodic off-site anchor.

Every regulated UK organisation eventually confronts the same realisation: "we need to know who changed this, and when, and what the previous value was, and nobody built that in." Usually the realisation arrives three days before a CQC visit, a trustee meeting, or an investor data room. This is a field note on the pattern we use to answer that question before it is asked.

The problem, stated precisely

An organisation stores records that matter. Someone edits one. Later — months later, possibly years later — someone needs to know three things: who edited it, when, and what the original value was. In the worst case, they also need cryptographic proof that nobody has tampered with the history itself. This last part is the interesting one; the rest is bookkeeping.

The naive answer is to log everything to a text file. This fails as soon as anyone with write access to the file can rewrite it. A database table is better, but still fails if a database administrator can issue an UPDATE or a DELETE. A WORM-style append-only store is better again, but adds operational complexity most organisations will not sustain.

The pattern we reach for in Django is a hash-chained audit log. It is cheap to implement, cheap to operate, and provides tamper-evidence without requiring special infrastructure. It will not stop a determined adversary with full database access from rewriting history, but it will make rewriting history detectable, which is what regulators and auditors actually want.

The pattern, in three models

First, an `AuditableMixin` marker on any model whose changes we want logged. It is empty; it exists so that Django signals can filter on `isinstance(sender, AuditableMixin)` rather than registering every concrete model individually. Any model that inherits it becomes auditable automatically.

Second, an `AuditLog` table with the obvious columns — timestamp, actor, action (create / update / delete), app label, model name, primary key, snapshot of the record at the time of the event — plus two columns that make the chain work: `previous_hash` and `entry_hash`.

Third, two Django signal handlers — `post_save` and `post_delete` — that create an AuditLog row whenever an auditable model is saved or deleted. The handlers are registered in the audit app's `ready()` method so they are wired up automatically at startup.

The handlers are intentionally trivial. They do not try to detect which specific fields changed (that is a richer feature, built on top); they just capture a complete snapshot of the row at that moment. Snapshots are cheap to store and expensive-to-impossible to misinterpret later.

The hash chain, specifically

When a new AuditLog row is saved, it looks at the most recent prior row and copies its `entry_hash` into the new row's `previous_hash`. Then it computes its own `entry_hash` as `sha256(canonical_json({timestamp, actor, ip, app, model, pk, action, snapshot, previous_hash}))`.

Two properties follow.

One: altering any historical row invalidates that row's entry_hash. A one-line integrity check — recompute each entry_hash from its stored payload and compare — will catch it immediately.

Two: altering any historical row also invalidates every subsequent row's entry_hash, because each one depends transitively on the altered row's hash. A single bad row cascades. You cannot quietly amend just one record.

This gives you tamper-evidence, not tamper-proof-ness. An adversary with full write access to the AuditLog table can rewrite the whole chain from a given point forward — recomputing every entry_hash as they go — and the chain will look internally consistent again. What they cannot do is quietly amend a single record and get away with it, because fixing the cascade is laborious, and because off-site periodic snapshots of the most recent entry_hash break even the full-rewrite attack.

Off-site anchor points

The cheap and effective enhancement is periodic off-site anchoring. Once a day, your application posts the most recent entry_hash to somewhere outside the application's trust boundary — an internal email to the directors, a Slack message, a committee minute, a text file in the finance team's shared drive. The posted hash has no meaning to the recipient; it is a claim, witnessed and dated.

If anyone later rewrites the AuditLog, the chain will no longer reach back to a previously-witnessed hash for a date before the rewrite. The rewrite is now detectable not just internally, but against external witnesses. For most organisations this is as much tamper-evidence as the use case warrants; the properly paranoid can anchor into a blockchain, a notary service, or the UK Government's DfE audit infrastructure, at diminishing marginal returns.

The operational realities

A few things worth saying out loud before you ship this pattern.

The AuditLog table will grow without bound. That is the point; it is a permanent record. Plan for it. Partition by month if your write volume is high; a modest 50k writes per month will fit comfortably in a single PostgreSQL table for years, so most teams never need partitioning.

The hash chain cannot tolerate out-of-order writes. If two processes race to write an AuditLog row, one will compute `previous_hash` based on a state that the other has already moved past. In practice we address this with a database-level serialisation point: a tiny SELECT ... FOR UPDATE of the latest row before inserting, inside a transaction. The write throughput is bounded by this lock; for most line-of-business applications this is not a problem.

The snapshot captures everything, including PII. If you encrypt PII fields at rest with `django-encrypted-model-fields`, the snapshot will capture the encrypted string, which is correct behaviour but worth being explicit about. Decryption happens at read time, with the field encryption key, and the read path is itself logged.

The signals must not raise. A failure in audit logging should never propagate into user-visible breakage. We wrap the signal handler bodies in a broad try-except that logs errors to Sentry but allows the primary write to succeed. The alternative — a system that refuses to save data when audit logging fails — is almost always worse than a system that saves the data and raises a visible alarm about the audit gap.

What this is not

This pattern does not replace access control. It records who did something, after they did it; it does not prevent someone from doing it in the first place. Role-based access control sits in front of the audit log, not behind it.

This pattern does not replace backups. The audit log tells you what changed; a backup lets you restore to a point in time. You want both.

This pattern does not replace a proper SIEM for security investigations. If your threat model includes sophisticated adversaries with lateral access, you need log forwarding to a dedicated security platform. The hash chain is a complement to that, not a substitute.

What you gain

In return for maybe three hundred lines of code, you get a general-purpose audit facility that applies automatically to every new model your team adds. Every create, every update, every delete, across the whole application, is captured without any per-feature effort. Six months from now, when the first inspector asks "can you tell me who approved this?", the answer is yes and the evidence is a database query away.

For regulated organisations the pattern is table stakes. For unregulated organisations it is cheap insurance. Either way, the cost of building it on day one is trivial compared to the cost of retrofitting it to a production system after the fact.

The AANDA Labs commercial site runs this pattern against every customer-facing model. The source for the audit app is in the public repository at github.com/ayoolumi/aanda-labs. We are also packaging it as a standalone Django app under an MIT licence for teams that want to add this to an existing project without rolling their own.

Facing this in your organisation?
Talk it through with the engineer who wrote this.
Get in touch →