BBackend CourseLeroy Labs
0/0
Search the course

Soft delete, triggers & append-only tables

is_deleted vs real deletes, retention purges, PL/pgSQL triggers that make posted journals immutable, and append-only audit logs that even a DBA cannot edit by accident.

● advancedReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

Soft delete

Instead of DELETE, mark the row:

@MappedSuperclass
public abstract class BaseEntity {
    @Column(name = "is_deleted") private boolean deleted;
    @Column(name = "deleted_at") private Instant deletedAt;
}

// Hibernate 6.4+: transparent filtering
@SoftDelete(columnName = "is_deleted")
@Entity class Account { /* ... */ }
// or older: @SQLDelete(sql = "UPDATE accounts SET is_deleted = true WHERE id = ?") + @SQLRestriction("is_deleted = false")

Pros: you can undo, keep history, preserve FK integrity and see who deleted what.

Cons:

  • Every query must filter it out (it’s easy to forget in native SQL).
  • Unique constraints break: a deleted user’s email blocks re-registration, so use a partial unique index WHERE is_deleted = false.
  • Tables grow forever.
  • It can conflict with GDPR “right to erasure”.

Retention purge

Soft-deleted rows should eventually be hard deleted, in batches:

@Scheduled(cron = "0 0 3 * * *")
void purge() {
    int n;
    do { n = repo.hardDeleteBatch(Instant.now().minus(Period.ofMonths(12)), 500); }
    while (n == 500);              // small batches = short locks
}

Triggers

A trigger runs database code automatically on INSERT, UPDATE, DELETE or TRUNCATE. Triggers enforce rules that no application code path can bypass.

CREATE FUNCTION journal_entries_guard() RETURNS trigger AS $$
BEGIN
  IF OLD.status = 'POSTED' THEN
    RAISE EXCEPTION 'journal entry % is posted and cannot be changed', OLD.id;
  END IF;
  RETURN NEW;
END $$ LANGUAGE plpgsql;

CREATE TRIGGER trg_journal_entries_guard
  BEFORE UPDATE OR DELETE ON journal_entries
  FOR EACH ROW EXECUTE FUNCTION journal_entries_guard();

In your projects

Report-Manager-2shared/domain/BaseEntity.java · SoftDeletePurgeScheduler

is_deleted and deleted_at on about 27 entities, plus a 12-month purge in batches. The audit log has its own 24-month retention, and export jobs keep 60 days.

IR3D (Kontentt)AccountLifecycleJob · deletion-grace: P30D

User deletion is a lifecycle: a request starts a 30-day grace period, during which the user can cancel, and then the account is purged. Apple Sign-In tokens are revoked on deletion, as Apple requires.

SperoTek (in dev)scripts/009-ledger.sql · 002-audit-logs.sql · SoftDeletableEntity

SperoTek’s immutability triggers:

  • journal_entries_guard() and journal_lines_guard() block any change to a POSTED entry.
  • ledger_no_truncate() blocks TRUNCATE on ledger tables.
  • audit_logs has a BEFORE UPDATE OR DELETE trigger that rejects every change, which makes it append-only. AuditLogAppendOnlyIT tests it.

Mistakes are never edited. They are fixed with reversal entries (Module 6).

Alternatives

Approach Trade-off
Soft-delete flag (RM) Simple; must filter everywhere
Archive table (move rows on delete) Main table stays clean; restoring is harder
Temporal tables / history (Hibernate Envers) Full version history automatically
Event sourcing Never delete; state is derived from events (bonus module)
Triggers vs application checks Triggers can’t be bypassed but are hidden from Java developers, so document and test them
DB permissions (REVOKE UPDATE, DELETE ON audit_logs FROM app_user) Even stronger: the app user simply can’t modify the table
  • @SQLRestriction (formerly @Where) for automatic filtering.
  • Unique + soft delete requires a partial unique index.
  • GDPR. Soft delete isn’t erasure. You may need to anonymise PII while keeping financial records.
  • Trigger costs. Triggers run per row, so they slow bulk loads, and their logic is invisible in a stack trace.

Check yourself

1. User with email a@x.com is soft-deleted; they re-register. Plain UNIQUE(email) will…
2. Why does SperoTek use DB triggers for posted journals?