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.
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
shared/domain/BaseEntity.java · SoftDeletePurgeScheduleris_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.
AccountLifecycleJob · deletion-grace: P30DUser 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.
scripts/009-ledger.sql · 002-audit-logs.sql · SoftDeletableEntitySperoTek’s immutability triggers:
journal_entries_guard()andjournal_lines_guard()block any change to a POSTED entry.ledger_no_truncate()blocksTRUNCATEon ledger tables.audit_logshas aBEFORE UPDATE OR DELETEtrigger that rejects every change, which makes it append-only.AuditLogAppendOnlyITtests 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 |
Related concepts you must know
@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.