Short answer: Soft delete vs hard delete determines whether you mark data as deleted or physically remove it, and the right choice depends on recovery needs, compliance, and system complexity. Use soft delete when you must support undo, audits, or references you cannot immediately repair. Use hard delete when privacy rules or business policy require irreversible removal, especially for user accounts and sensitive content. Most MVPs start with a vibecoded is_deleted flag and regret the edge cases later; production-ready apps pair clear retention windows with background purge and strict constraints. We harden deletes by defining semantics first, then implementing data, search, cache, and blob cleanup as one atomic story.

Key takeaways

  • Soft delete offers fast recovery and auditability, but it increases query complexity and the risk of data leaks if filters are missed.
  • Hard delete satisfies irreversible removal and privacy mandates, but it demands careful cascades, purge workflows, and blob cleanup.
  • Production-ready delete semantics require a documented retention policy, background purge jobs, and explicit events for downstream systems.
  • Partial unique indexes, foreign key strategies, and scoped queries prevent common soft delete bugs such as uniqueness collisions and orphaned children.
  • Migrating delete behavior in production should follow expand-and-contract steps, versioned APIs, and dual-write audit to avoid breaking clients.

What is soft delete vs hard delete?

Soft delete marks a record as deleted without removing it from storage, typically by setting a deleted_at timestamp or an is_deleted flag. Hard delete physically removes the record and its dependents from the database and related systems. Soft delete optimizes for reversibility and auditability at the cost of ongoing filtering and storage. Hard delete optimizes for privacy and finality at the cost of more careful cascades and fewer recovery options.

Soft delete building blocks

  • Marker: deleted_at TIMESTAMP or is_deleted BOOLEAN; we prefer timestamps for retention math.
  • Default scopes: ORM or query helpers that automatically exclude deleted rows.
  • Partial uniqueness: Unique indexes on active rows only (for example, WHERE deleted_at IS NULL).
  • Tombstones: Minimal metadata retained post-purge to prevent accidental resurrection (for example, reserved usernames).

Hard delete building blocks

  • Cascades: Explicit ON DELETE CASCADE/RESTRICT choices that reflect domain rules.
  • Purge workers: Batched deletes to keep locks small and maintain availability.
  • Proof of deletion: Audit events or receipts recording who deleted, when, and what.
  • Blob cleanup: Removal of attached files and cache entries that reference deleted entities.

When should a production MVP choose soft delete?

Choose soft delete when the business needs reversibility or forensic visibility. Production systems that support customer support recovery, chargebacks, or fraud investigations benefit from preserved state with clear recovery paths.

  • Human-facing undo: Users expect a recycle bin or provisional deletion period for content drafts, projects, or messages.
  • Audit and disputes: Sales, billing, and content moderation flows often require retaining evidence for a defined period.
  • Complex references: If other services or downstream warehouses still point at the record, a grace period avoids broken links while you backfill or migrate.
  • Operational safety: When delete commands might be misfired (scripts, bulk ops), soft delete gives you a fast rollback lever.

Set a time-boxed retention window to convert soft deletes into final purges. A common pattern is a cooling-off period (for example, 7–90 days) with visible status in backoffice tools and automated purge after expiry.

When is hard delete mandatory?

Choose hard delete when you must remove data irreversibly or when retention poses more risk than value. Production-grade compliance and privacy often require hard deletion for specific entities or attributes.

  • Privacy laws: Right-to-be-forgotten requests typically require full removal of personal data beyond a strict legal basis for retention.
  • Security incidents: Compromised content or malware must be eradicated, not hidden.
  • Cost control: High-churn data (temp uploads, transient sessions) can bloat storage and degrade performance if never purged.
  • Irreversible lifecycle: Entries like ephemeral tokens or expired invites are safer and simpler to delete permanently.

Hard delete does not mean chaotic drop statements. Production hard delete means targeted cascades, controlled batch sizes, and observable outcomes with receipts.

How do we implement soft delete correctly?

Implement soft delete with clear semantics, strict query hygiene, and an automated purge path that prevents drift. The goal is recoverability without quietly leaking deleted state back into user flows or analytics.

  1. Define policy and states: Enumerate allowed states: active, soft_deleted (with timestamp), purged. Document retention per entity type.
  2. Add a deleted_at column: Prefer timestamps over booleans. They model retention math and avoid tri-state ambiguity.
  3. Scope every query by default: Configure your ORM to exclude deleted_at IS NOT NULL by default. Provide explicit withDeleted() accessors for admin and analytics.
  4. Use partial unique indexes: Enforce uniqueness only among active rows (for example, unique on (tenant_id, slug) WHERE deleted_at IS NULL).
  5. Protect children: For dependent tables, pick one: prevent soft delete if children exist (RESTRICT), soft delete children in the same transaction, or detach children safely.
  6. Emit domain events: Publish entity.deleted with the record key and timestamp so search, cache, and other services can react.
  7. Schedule purge: A background job scans soft-deleted rows past retention and purges them in small batches with retries and metrics.
  8. Expose restore: Backoffice tools must list soft-deleted items and allow restore within retention window, with conflict checks.

Don’t forget the edges

  • Search and indexing: Remove from search indices on soft delete to avoid resurfacing hidden content.
  • Cache invalidation: Evict keys derived from the entity identifier immediately after marking deleted.
  • Blob references: If files are tied to the record, mark them for later purge, then actually delete during final purge. For durable patterns, see orphaned blob cleanup for MVPs.
  • Analytics: Mark events with deleted_at to avoid counting deleted content while preserving historical aggregates.

How do we implement hard delete safely?

Implement hard delete as a controlled operation with visibility, authorization, and bounded impact. The key risks are accidental cascades, lock contention, and forgetting non-database assets.

  1. Authorize the actor: Restrict hard delete to privileged roles or automated purge workers; record who, what, and why.
  2. Choose cascade strategy: Use explicit foreign key policies: RESTRICT for critical entities to force deliberate cleanup; CASCADE when children have no meaning without the parent.
  3. Batch and retry: Delete in small pages to avoid long-running transactions. Instrument latency, rows affected, and error rates.
  4. Clean non-DB assets: Remove attached files, cache entries, and search documents in the same workflow. Ensure idempotency.
  5. Emit deletion events: Publish entity.purged for downstream consumers to finalize cleanup.
  6. Produce a deletion receipt: Store minimal, non-personal metadata proving deletion occurred (for example, a hash or internal reference).

For entities exposed via public APIs, changing from soft to hard delete (or vice versa) is a breaking change. Plan the transition with explicit versioning; see our notes on an API versioning strategy for MVPs that need to scale.

What pitfalls should we avoid?

Most delete bugs stem from inconsistent semantics across queries, uniqueness, and relationships. Production systems make these rules machine-enforceable.

  • Missed filters: Without default scopes, deleted rows reappear in UI lists. Fix with ORM defaults and lints that forbid unscoped queries.
  • Broken uniqueness: Soft-deleted usernames still block reuse. Solve with partial unique indexes limited to deleted_at IS NULL, plus tombstones if names must remain reserved post-purge.
  • Orphaned children: Deleting a parent without handling dependents corrupts relational shape. Enforce with foreign keys and RESTRICT unless cascades are intentional.
  • Leaky analytics: BI dashboards include deleted items unless you mark and filter them. Add deleted_at to facts and dimensions and define canonical active filters.
  • Cache ghosts: Edge caches or in-memory layers serve deleted content. Publish invalidation events and expire keys eagerly on delete.
  • Index bloat: Soft delete keeps indexes hot with dead rows. Consider partial indexes and periodic VACUUM/compaction.

How do we handle blobs and external systems?

Deletes rarely stop at the database boundary. Production-ready semantics coordinate files, caches, search, and integrations.

  • Files and blobs: Track blob ownership via a join table; soft delete the link first, then purge the object if no remaining references. For a deeper pattern, see our write-up on orphaned blob cleanup for MVPs.
  • Search indices: On soft delete, either delete the search document or set a is_hidden flag and filter; on hard delete, remove the document entirely.
  • Downstream caches and replicas: Send explicit invalidation events rather than relying on TTLs for correctness.
  • Third-party integrations: If partners store your IDs, emit webhooks or callbacks to direct them to remove references.

What does a good purge pipeline look like?

A good purge pipeline is idempotent, observable, and bounded. We treat purge as a first-class workflow with clear inputs and measurable outputs.

  1. Selector: Query candidates based on deleted_at < now() - retention with stable ordering and a limit.
  2. Plan: Gather dependent keys: child rows, blob IDs, cache keys, search documents.
  3. Execute: Hard delete in small batches; perform blob deletions and cache evictions; handle retries with backoff.
  4. Emit: Publish entity.purged with minimal metadata for audit and downstream cleanup.
  5. Measure: Emit metrics (rows purged, latency, errors), and maintain a run log for support.

We prefer transactional handoffs for delete events so state changes and event delivery remain consistent. If your system uses an event bus, decouple publishing from row deletion with a durable buffer.

How do we migrate delete semantics in production?

Migrating from soft to hard delete, or vice versa, is doable without downtime if you separate state, behavior, and API shape. The safest approach is expand-and-contract with dual behavior and clear cutovers.

  1. Define the new contract: Document which entities change, the new retention rules, and expected responses and events.
  2. Expand: Add new columns/indexes (for example, deleted_at), publish new events, and support both paths behind a feature flag.
  3. Dual-write: For a window, write both soft flags and hard-deleted tombstones to ensure restore logic or name reservations keep working.
  4. Version the API: If delete responses or lifecycles differ, ship a new version and maintain old semantics until clients migrate. Our notes on an API versioning strategy cover safe deprecation.
  5. Backfill: Populate deleted_at for previously hidden rows or, conversely, purge old soft-deleted records consistent with the new policy.
  6. Contract tests: Assert that deleted rows never surface in active endpoints and that uniqueness works under both models during the transition.
  7. Cutover and contract: Remove legacy paths, drop obsolete columns or triggers, and lock the new semantics with lints and tests.

How Moai Team approaches this

We start by writing down delete semantics as a decision record: entities involved, legal basis, retention windows, user-visible behavior, and audit needs. We audit the codebase for unscoped queries, missing foreign keys, weak unique constraints, and any place deleted state could leak back into user flows. We then implement the chosen model end to end: schema changes, partial indexes, default scopes, background purge, cache and search invalidation, deletion events, and blob cleanup. We add runbooks and dashboards that show deletions per hour, purge lag, and error rates so operators can see and correct drift. As forward-deployed engineers, we embed in the client’s repo and release train, ship the model behind flags, and pair with the team on migrations and backfills until deletes hold up under real traffic.

Frequently Asked Questions

Is soft delete the same as archiving?

No. Soft delete marks a record as deleted while leaving it in the primary store and queries. Archiving moves data to a separate, often cheaper store where it remains queryable for history or compliance. You can soft delete and archive, but they solve different problems.

Does hard delete violate audit requirements?

Hard delete removes personal or domain data but you can retain a minimal, non-personal audit receipt that a deletion occurred. Many audits care that you can prove an action happened and when, not that you retain the deleted content. Align receipts with your privacy policy and legal basis.

Should we soft delete user accounts?

Often you should not, because privacy expectations and regulations favor irreversible removal once retention obligations end. A pragmatic model is to schedule a grace period for account recovery, then hard delete personal data and keep only a minimal tombstone that does not identify the user. If you must retain elements for fraud or compliance, document the legal basis and limit scope.

How long should our retention window be?

Set retention per entity based on user experience, dispute horizons, and legal requirements. Pick a number you can defend and automate, then enforce it with background purge and metrics. Shorter windows reduce risk and cost but may reduce recovery options; longer windows improve support at the cost of exposure.

Can we mix soft and hard delete in one system?

Yes. Mature systems use soft delete for content and operational data that benefits from recovery, and hard delete for personal data or ephemeral artifacts. The key is to write down the policy per entity, make it machine-enforceable, and keep events and purge workflows consistent.

How do we prevent deleted usernames from being re-used improperly?

Reserve names with tombstones or use partial unique indexes that apply to active rows and a small registry of permanently reserved values. This preserves safety without keeping full personal data. Handle name reservation as a separate concern from account data retention.

If you need forward-deployed engineers to make your delete semantics hold in production, contact Moai Team at moaiteam.com/contacts.