How-To Guide

How to Implement Data Retention and Archiving

Design data retention: set policies per data class, archive before deleting, enforce retention automatically, and prove compliance with tests.

On this page

  1. Introduction
  2. Classify data by retention and disposal
  3. Archive before deleting when it is reversible
  4. Automate enforcement and watch for lag
  5. Handle legal holds and exceptions
  6. Test that the policy holds
  7. Common pitfalls
  8. Conclusion

Introduction

Data accumulates, and not all of it should live forever in the primary database. A retention policy says how long each class of data is kept and how it is disposed of, driven by legal requirements, product needs, and cost. Without an automated policy, old data lingers, bloats tables, slows queries, and may violate a regulation that required it to be gone. Retention is the discipline of removing data on a schedule instead of at the limit of storage.

This tutorial covers how to classify data by retention, how to archive before deleting so removal is reversible, how to automate the enforcement, and how to prove the policy with tests. The examples build on partitioning and batched deletes, and the reasoning applies whether data is removed by dropping partitions or by row deletes.

Classify data by retention and disposal

Start by assigning each table or data class a retention period and a disposal method. Some data, such as audit logs, must be kept for years; some, such as session tokens, should expire in days; some, such as temporary uploads, in hours. The period comes from the strictest applicable requirement: a legal mandate, a contract, or a product need, whichever demands the longest or shortest.

The disposal method is as important as the period. Some data must be erased, meaning gone from every copy, which forbids archiving it in a readable form. Other data may be archived for analytics and kept longer than the operational store. Record the policy in one place, with a period and a method per class, so a scheduled job can enforce it and an auditor can review it without reading code.

-- a small registry of retention policy, so enforcement is data-driven
CREATE TABLE retention_policy (
  data_class     text PRIMARY KEY,   -- e.g. 'session', 'audit', 'event'
  retain_days    integer NOT NULL,
  disposal       text NOT NULL CHECK (disposal IN ('delete', 'archive-delete')),
  archive_target text
);

Archive before deleting when it is reversible

For data that might be needed again, move rows to an archive before removing them from the primary store. The archive can be compressed files in object storage, keyed by date, or a separate archive table on cold storage. Copy then delete, in that order, with a grace window in which a mistake can be undone. A delete-first policy has no recovery if the policy is later found to be wrong.

The archive does not need the primary database’s indexes or query speed; it needs durability and a documented retrieval path. For a range of data, export the partition’s contents to files and then drop the partition, which is far cheaper than copying rows out of a large live table. Record what was archived and when, so a retrieval request can find the right file rather than guessing.

# export the oldest month, then drop it
psql -d app -c "\\copy (SELECT * FROM events WHERE created_at >= '2025-01-01' AND created_at < '2025-02-01') TO PROGRAM 'gzip > /archive/events_2025_01.csv.gz'"
psql -d app -c "ALTER TABLE events DETACH PARTITION events_2025_01 CONCURRENTLY; DROP TABLE events_2025_01;"

Automate enforcement and watch for lag

A retention policy that relies on someone remembering to run a script is not a policy. Schedule a job that reads the retention table, computes each class’s cutoff, and archives and deletes accordingly. Run it often enough that the per-run volume is bounded, and make it idempotent so a retry after a failure does not double-delete or double-archive.

Alert on lag. If the job has not completed for a class, or the oldest row exceeds the retention plus a margin, the policy is being violated. Surface the current age of the oldest row per class as a metric so a stalled job or a new class with no policy is visible. A class with no retention row should fail the job loudly rather than silently retaining data forever.

async function enforceRetention(db, policy) {
  for (const p of policy) {
    const cutoff = new Date(Date.now() - p.retain_days * 86400000);
    if (p.disposal === 'archive-delete') {
      await archiveClass(db, p.data_class, cutoff);   // copy to cold storage first
    }
    await deleteOlderThan(db, p.data_class, cutoff);  // batched deletes
    await recordRun(db, p.data_class, cutoff);        // for auditability
  }
}

A retention policy must be able to pause for exceptional cases. A legal hold, an open investigation, or a customer dispute means the relevant data must not be deleted even though it is past its retention. Implement holds as a flag on the affected rows or a scope, and have the enforcement job skip held data, so a routine run does not destroy evidence.

Some data is subject to a stricter erasure rule that requires removal on request, faster than the routine policy. Support an explicit erase path that removes a subject’s data across the stores that hold it, including the archive if the rule covers it. Reconcile the routine policy and the on-request erase so neither defeats the other, and log every erase for the audit trail.

Test that the policy holds

Seed rows on both sides of each class’s cutoff. Run the enforcement job and assert that rows older than the cutoff are gone from the primary store and present in the archive when the method is archive-delete. Assert that rows younger than the cutoff are untouched. Assert that a held row past its cutoff is retained while its neighbors are removed. These tests prove the period, the method, and the exception handling.

psql -d app <<'SQL'
SELECT count(*) FROM sessions WHERE last_seen < now() - interval '30 days';   -- expect 0 after job
SELECT count(*) FROM sessions WHERE last_seen > now() - interval '30 days';   -- expect unchanged
SELECT count(*) FROM audit_log WHERE id = 42;                                 -- held row still present
SQL

Common pitfalls

Deleting before archiving so a wrong policy is irreversible, relying on a manual job, keeping an archive that violates a strict erasure rule, leaving a new data class without a policy so it is retained forever, and ignoring legal holds are the recurring mistakes. Archive-first for reversible data, a scheduled data-driven job, auditable runs, a loud failure for unclassified data, and hold support address them.

Conclusion

Retention is a policy with a period and a method per data class, enforced automatically. Classify data, archive before deleting when removal is reversible, schedule an idempotent job, expose the age of the oldest row as a metric, support holds and erasure, and test both sides of each cutoff. Self-check by asserting old rows are gone from the primary and present in the archive while young rows and held rows remain. Data then leaves on schedule instead of at the edge of the disk.

Sources: PostgreSQL: Partitioning for retention, PostgreSQL: DELETE and VACUUM, NIST: Guide to data retention and disposal.

FAQ

Archive and delete, or just delete?
Archive first when the data has any chance of being needed later, for analytics, an audit, or a legal hold. If the policy is a hard erasure requirement, archive only in a form that satisfies the same erasure, or skip the archive and delete.
Where should the archive live?
In cheaper, slower storage than the primary database: object storage as compressed files, or a separate archive table on cold storage. The archive does not need the primary's indexes or query speed, only durability and a documented retrieval path.

Related Examples