How-To Guide

How to Design Soft Deletes

Add deleted_at with partial unique indexes, enforce default filtering in one place, and plan restore conflicts and eventual purging.

On this page

  1. Introduction
  2. Decide what deletion means
  3. Model the marker
  4. Filter in exactly one layer
  5. Restore and its conflicts
  6. Purge on a schedule
  7. Test ghosts out of existence
  8. Common pitfalls
  9. Conclusion

Introduction

Soft deletes answer a real operational fear: a mistaken DELETE, or an angry user, or a buggy script, and the data is gone unless someone restored a backup overnight. The mechanism, an UPDATE setting a deleted_at timestamp instead of removal, buys recoverability at the cost of correctness obligations that naive implementations ignore: unique constraints that collide with deleted rows, queries that forget the filter and resurrect ghosts, joins that re-attach deleted children, tables that grow forever because nothing ever really leaves, and compliance confusion where a soft-deleted row still holds the personal data an erasure request asked to remove. Deciding whether soft deletes are right at all is the first step, because some deletions are exactly that, regulatory erasures and append-only history want different machinery. This tutorial makes the decision, models the marker so integrity survives, concentrates filtering in one layer, and handles restore and eventual purge, which is where most implementations quietly rot.

Decide what deletion means

Three meanings of deletion demand three mechanisms, and conflating them is the root mistake. Recoverable mistakes: an operator deletes the wrong customer, a user rage-quits and returns; recovery within days has real value, and soft delete serves exactly this. Audit-required history: financial records, medical entries, legal documents must never disappear, and the correct pattern is append-only records with correction entries, event-sourced or ledger-style, not a mutable deleted flag on mutable state. Regulatory erasure: GDPR and cousins demand the data actually leave, and a soft-deleted row violates the request as thoroughly as an undeleted one; the correct pattern is real deletion plus, where referential integrity requires, anonymizing tombstones that retain keys but scrub attributes. Applying soft delete to all three, the common reflex, gives erasure that does not erase and history that does not protect, while paying its filtering tax on every table. Scope it deliberately: soft delete belongs on the entities whose accidental loss is operationally plausible and whose recovery window is bounded.

Model the marker

The marker itself has a correct shape: a nullable timestamptz column, deleted_at, null meaning live. A nullable timestamp beats a boolean because it records when, which recovery, auditing, and purge scheduling all need, and it composes with partial indexes that read the null as live. The integrity consequence is the part that bites: a unique constraint on users(email) sees soft-deleted rows, so re-registering a deleted email collides with a ghost. Partial unique indexes restore the intended semantics.

ALTER TABLE users ADD COLUMN deleted_at timestamptz;

CREATE UNIQUE INDEX users_email_live
 ON users (email)
 WHERE deleted_at IS NULL;

-- deletion is an update
UPDATE users SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL;

Foreign keys need the same honesty: child rows referencing a soft-deleted parent should either soft-delete in the same transaction, cascading recoverability, or the join layer must filter children by the parent’s aliveness, or queries resurrect deleted subtrees. Composite and per-tenant uniqueness get the same partial treatment, and the partial predicate must match the query’s liveness filter exactly, or the planner cannot use the index and the semantics drift apart.

Filter in exactly one layer

Every query against a soft-deleted table must decide about liveness, and if that decision is spread across application code, some query forgets, and a deleted record surfaces in production, the classic ghost bug. The defense is architectural: the filter lives in one place and is opt-out, not opt-in. In an ORM, a default scope on the model, with an explicit unscoped escape hatch used only by recovery and purge code. In hand-rolled SQL, repository functions that compose the predicate into every generated WHERE, with a documented raw path for the admin jobs.

export class UserRepository {
 async active(id: number) {
  return db.one(
   'SELECT * FROM users WHERE id = $1 AND deleted_at IS NULL', id);
 }
 async includingDeleted(id: number) {
  return db.one('SELECT * FROM users WHERE id = $1', id);
 }
}

The audit is mechanical and worth automating: grep the codebase for the table name in raw SQL, and every occurrence outside the repository module is a review finding. Joins are the leak point that unit tests catch late: a query joining orders to users through the active filter but reading a deleted user’s denormalized name from a column needs the join’s other side filtered too, or the ghost appears in a field nobody thought to check. Counter queries, aggregates, and count(*) for pagination all inherit the same default, because a list page whose total counts ghosts disagrees with its own contents.

Restore and its conflicts

Restore is where soft deletes earn their keep, and it is not a simple UPDATE deleted_at = NULL. Conflict: the unique partial index that correctly allowed a new row with the same email while the old one was dead now rejects reactivating the old row, and restore must resolve the collision explicitly, merge the histories, refuse with a clear error, or rename one side. Cascades: if deletion cascaded to children, restore must decide whether children revive too, and a naive restore that revives the parent but leaves children dead creates a half-alive subtree that passes parent checks and fails child listings. State drift: the world moved while the row was dead, external references were created, subscription state changed at the provider, and restore is a business process, not a flag flip. A restore implemented as a deliberate flow, validate conflicts, restore dependents in dependency order, notify downstream systems, leaves an audit trail; a restore implemented as one UPDATE leaves incidents. Design the restore path when designing the delete path, because the second is only ever as good as the first.

BEGIN;
UPDATE users SET deleted_at = NULL WHERE id = $1;
UPDATE api_keys SET deleted_at = NULL
WHERE user_id = $1 AND deleted_at > $2; -- only those deleted with the user
COMMIT;

Purge on a schedule

Soft-deleted rows past their recovery horizon are dead weight: they bloat tables, slow scans, backfill partial indexes, and, for personal data, they are a standing compliance exposure. The purge job physically deletes rows whose deleted_at is older than the horizon, thirty or ninety days by policy, in bounded batches to avoid long locks and replication spikes, and it handles dependents in order or relies on ON DELETE CASCADE for the true removal path. Purge and restore coordinate through the horizon: nothing past the horizon is recoverable, so restore tooling refuses rather than races the job. The compliance dimension deserves a separate sentence in the design doc: if the table carries personal data, the purge job is also the erasure mechanism, its schedule is the retention policy, and its logging is the evidence that deletion actually happens, three properties that make the job operational infrastructure rather than housekeeping. Size batches by lock tolerance, run during low traffic, and export purge counts as telemetry, because a purge job that silently stops leaves the company accumulating exactly the data it promised to forget.

Test ghosts out of existence

The failure modes are specific and testable. Ghost reads: soft-delete a row, then run every list, get, search, and count path in the test suite, and assert the row appears nowhere outside the explicit including-deleted paths. Uniqueness after deletion: delete a user, create a new one with the same unique key, assert success, then restore the old one and assert the conflict surfaces as a designed error. Cascade round-trip: delete a parent with children, assert children die, restore, assert children revive exactly, no more, no fewer. Purge: advance the clock past the horizon, run the job, assert physical removal and that restore refuses afterwards. Filter drift: the grep audit as a CI check, raw table references outside the repository module fail the build. These are cheap tests to write once the repository layer concentrates the filter, and they encode the two promises of soft delete, deleted things stay hidden, and hidden things come back whole, as executable facts rather than conventions.

await users.delete(userId);
expect(await users.find(email)).toBeNull();
expect(await search.indexContains(userId)).toBe(false);
await users.restore(userId);
expect((await users.find(email)).id).toBe(userId);

Common pitfalls

  • Soft deletes everywhere. Growth tables and join tables pay the filter tax forever for recovery they never use; scope by real operational risk.
  • Plain unique constraints. Ghosts collide with new rows; partial unique indexes over live rows only.
  • Filters spread through application code. Some query forgets; concentrate in one opt-out layer.
  • Restore as flag flip. Conflicts, cascades, and state drift make it a business flow, not an UPDATE.
  • Purge that never runs. Tables bloat, partial indexes backfill, personal data accumulates past its promise.
  • Soft delete as erasure. The data is still there; compliance removal needs real deletion or anonymized tombstones.

Conclusion

Soft delete is recovery plumbing for operationally plausible mistakes, and it earns its place only where that is the real requirement, not where audit history or regulatory erasure is. Model it as a nullable deleted_at with partial unique indexes so live-row integrity survives deletion. Concentrate the liveness filter in one opt-out layer, repository scopes or ORM defaults, and audit raw-SQL drift mechanically, because a single forgotten filter is the ghost bug. Design restore as a deliberate flow that resolves unique conflicts and cascades dependents, and schedule physical purge past the recovery horizon, treating the job as retention policy and compliance evidence when personal data is involved. Tested from the ghost angle, deleted things stay hidden and hidden things return whole, soft deletes deliver their promise without taxing every query forever.

Sources: PostgreSQL: partial indexes, PostgreSQL: table constraints, PostgreSQL: UPDATE.

FAQ

Do soft deletes satisfy GDPR erasure requests?
No. A row with deleted_at set still contains the personal data, so an erasure request requires overwriting or removing the data. Soft delete is recovery plumbing, not a compliance mechanism; plan a real purge path.
Why does my unique constraint fail after soft deletes?
The unique index still sees the soft-deleted row. Create it as a partial unique index with WHERE deleted_at IS NULL so only live rows participate in uniqueness.
Should every table get soft deletes?
No. Tables that grow unboundedly, high-churn join tables, and append-only event tables pay the filtering tax forever for recovery value they rarely use. Apply it where mistaken deletion is a real operational risk.

Related Examples