Immutable Data

Difficulty: Advanced

Question

What is an append-only (immutable) data pattern, and when should you use it instead of updating rows in place?

Answer

In an append-only design you never UPDATE or DELETE existing rows; every change is recorded by inserting a new row (a new version or an event) with a timestamp. The current state is derived from the latest version or by replaying the events. This gives a complete audit trail and the ability to see the data as it was at any point in time, at the cost of more storage and more complex reads.

Two common forms

  • Versioned rows: each change inserts a full new version of the entity, for example product_prices(product_id, price_paise, valid_from). The current price is the latest row. Data warehouses call this Slowly Changing Dimension Type 2, often with valid_from and valid_to columns.
  • Event log: store the facts that happened rather than resulting state, for example AccountOpened, MoneyDeposited, MoneyWithdrawn. The balance is computed by folding events. Taken to an architectural level, this is event sourcing.

A double-entry accounting ledger is the classic append-only system. You never edit a posted entry; a mistake is fixed by a new reversing entry. Payment systems such as wallets and UPI settlement ledgers follow the same rule.

Why teams choose it

  • Audit and compliance: who changed what and when is built into the data, not bolted on with triggers.
  • Time travel: answer "what was this user's plan on 1 March?" or reproduce a report exactly as it ran.
  • Debugging: you can see the full sequence that produced a bad state.
  • Simpler concurrency: inserts do not conflict the way concurrent updates to one row do.
  • Downstream feeds: change streams for analytics, caches and search indexes fall out naturally.

The costs

ConcernImpactMitigation
Storage growthEvery change adds a rowPartitioning, archiving old versions
Read complexityNeed "latest version" queriesViews, DISTINCT ON, a current-state projection table
Replay cost (event sourcing)Rebuilding state from many events is slowPeriodic snapshots
CorrectionsCannot just fix a wrong rowCompensating or reversing entries
Right to erasurePersonal data cannot simply be deletedStore PII separately, or crypto-shredding (delete the encryption key)

The last row matters under privacy laws like the EU GDPR and India's DPDP Act 2023: an immutable log must still support deleting personal data on request.

Enforcing immutability

  • Revoke UPDATE and DELETE privileges from the application role on the log table.
  • Add a trigger that raises an error on update or delete.
  • Use a ledger or temporal feature: SQL Server system-versioned temporal tables and ledger tables, MariaDB system-versioned tables, or AWS QLDB-style ledgers (note that QLDB itself has been discontinued by AWS).
  • Pair the log with a mutable projection table for fast current-state reads, kept up to date in the same transaction or by a consumer.
Append-only ledger to current balance. Events are only ever inserted; the balance is a derived view of them.
  1. Command: pay 250 rupees: Application validates the request.
  2. INSERT ledger entry: New immutable row, never updated later.
  3. Ledger history: Full ordered record of every change.
  4. Projection or SUM query: Current balance derived from entries.
  5. Audit and time-travel reads: Any past state can be reconstructed.

Code examples

Append-only wallet ledger in PostgreSQL

CREATE TABLE wallet_ledger (
  id           BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  wallet_id    BIGINT      NOT NULL,
  entry_type   TEXT        NOT NULL CHECK (entry_type IN ('CREDIT','DEBIT','REVERSAL')),
  amount_paise BIGINT      NOT NULL,          -- signed: credits +, debits -
  reference_id TEXT        NOT NULL UNIQUE,   -- idempotency key
  created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Block edits at the database level
CREATE FUNCTION forbid_change() RETURNS trigger AS $
BEGIN RAISE EXCEPTION 'wallet_ledger is append-only'; END $ LANGUAGE plpgsql;

CREATE TRIGGER ledger_immutable BEFORE UPDATE OR DELETE ON wallet_ledger
FOR EACH ROW EXECUTE FUNCTION forbid_change();

-- Current balance and balance as of a past date
SELECT sum(amount_paise) FROM wallet_ledger WHERE wallet_id = 7;
SELECT sum(amount_paise) FROM wallet_ledger
WHERE wallet_id = 7 AND created_at < '2026-03-01';

The trigger rejects updates and deletes, mistakes are fixed with REVERSAL entries, and point-in-time balances come from filtering on created_at.

Latest version per product with DISTINCT ON

SELECT DISTINCT ON (product_id)
       product_id, price_paise, valid_from
FROM product_prices
ORDER BY product_id, valid_from DESC;

DISTINCT ON keeps the newest version per product, a common way to read current state from versioned rows in PostgreSQL.

Key points

  • Append-only: insert new versions or events instead of updating or deleting rows.
  • Gives a complete audit trail and point-in-time reconstruction.
  • Costs: storage growth, more complex reads, and corrections via compensating entries.
  • Financial ledgers are the classic example; never edit a posted entry.
  • Plan for privacy deletion with separate PII storage or crypto-shredding.

Common follow-up questions

  • How is event sourcing different from simply keeping an audit log table?
  • How do you read the current state efficiently from an append-only table?
  • How would you handle a GDPR or DPDP deletion request in an immutable log?
  • What are snapshots in event sourcing and why are they needed?

Interview tips

  • Use a ledger example; it makes the "fix with a reversing entry" idea obvious.
  • Discuss the trade-offs honestly, especially storage and read complexity.
  • Mention how you would enforce immutability (permissions or triggers), not just the idea.

Concepts covered

Append-Only, Immutable Data, Event Sourcing, Audit Trail, Ledger

More Database Design questions