Data Archiving

Difficulty: Intermediate

Question

How do you handle very large tables containing years of old, rarely accessed data?

Answer

Separate hot data from cold data. Keep recent rows in the main table, move older rows to an archive table, cheaper storage or object storage like S3 in a columnar format such as Parquet, and delete what you are no longer required to keep. The cleanest way to do this in PostgreSQL or MySQL is time-based partitioning, where archiving becomes detaching or dropping a whole partition instead of deleting millions of rows.

Why huge tables hurt

  • Indexes grow beyond memory, so lookups touch disk more often.
  • Maintenance gets slower: VACUUM, index rebuilds, backups, restores and replica rebuilds all scale with table size.
  • Schema changes take longer, and some lock the table for the duration.
  • Storage cost: years of payment logs on fast SSD-backed database storage are expensive compared to object storage.

Most applications only query recent data. An order history page shows the last few months; older data is needed for audits, tax or analytics.

Approach 1: time-based partitioning

Partition the table by month or quarter (for example PARTITION BY RANGE (created_at) in PostgreSQL). Then:

  • Queries filtering on created_at only touch relevant partitions (partition pruning).
  • Archiving an old month is ALTER TABLE ... DETACH PARTITION (with CONCURRENTLY since PostgreSQL 14), followed by export and DROP TABLE.
  • Dropping a partition is nearly instant and leaves no dead rows, unlike DELETE.
  • Tools like pg_partman create future partitions and retire old ones automatically.

Approach 2: move rows in batches

If partitioning is not an option, move old rows with a background job:

  1. Copy a batch (say 5,000 rows older than the cutoff) into orders_archive or export it.
  2. Delete the same batch from the main table, in the same transaction.
  3. Sleep briefly, repeat. Small batches avoid long locks, replica lag and huge WAL bursts.

Large deletes leave dead tuples in PostgreSQL, so autovacuum must keep up; partitioning avoids that problem entirely.

Where archived data goes

DestinationGood forAccess
Archive table in the same databaseOccasional lookups by support teamsPlain SQL, slower is fine
Separate archive databaseKeeps primary small, still SQLCross-database queries
S3 or GCS as ParquetCheap long-term retention and analyticsAthena, BigQuery, Spark, DuckDB
Glacier-class storageCompliance copies rarely readHours to restore

Things to decide before archiving

  • Retention rules: financial and tax records often have legal minimum retention periods, while privacy laws such as India's DPDP Act push you to delete personal data once its purpose is served. Agree on rules with legal and finance.
  • Access path: how will support staff or auditors read archived data? Document it.
  • Referential integrity: child rows must be archived together with parents, or foreign keys break.
  • Restore test: practice bringing archived data back before you need it.

TTL features are an alternative for data that can simply expire: DynamoDB TTL and MongoDB TTL indexes delete items automatically after a timestamp.

Hot, warm and cold data tiers. Data moves down the tiers as it ages and is accessed less.
  1. Hot: current partitions in the main DB: Last few months, fully indexed, fast SSD.
  2. Warm: archive table or archive DB: Older data, fewer indexes, occasional queries.
  3. Cold: Parquet files in object storage: Years of history for audits and analytics.
  4. Deleted after retention expires: Removed once legal and business needs end.

Code examples

Monthly partitions and archiving in PostgreSQL

CREATE TABLE payments (
  id           BIGINT GENERATED ALWAYS AS IDENTITY,
  merchant_id  BIGINT      NOT NULL,
  amount_paise BIGINT      NOT NULL,
  created_at   TIMESTAMPTZ NOT NULL,
  PRIMARY KEY (id, created_at)          -- partition key must be in the PK
) PARTITION BY RANGE (created_at);

CREATE TABLE payments_2026_10 PARTITION OF payments
  FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');

-- Archive an old month: detach without blocking queries (PG 14+)
ALTER TABLE payments DETACH PARTITION payments_2023_10 CONCURRENTLY;
-- export payments_2023_10 to Parquet/S3, verify, then:
DROP TABLE payments_2023_10;

Detaching and dropping a partition replaces a slow, bloating DELETE of millions of rows with a near-instant metadata operation.

Batched move when partitioning is not available

-- Run in a loop from a job until 0 rows are moved
WITH moved AS (
  DELETE FROM orders
  WHERE id IN (
    SELECT id FROM orders
    WHERE created_at < now() - interval '2 years'
    LIMIT 5000
  )
  RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;

The writable CTE deletes and archives the same batch atomically, keeping each transaction short.

Key points

  • Separate hot recent data from cold historical data to keep the main table fast.
  • Time-based partitioning makes archiving a detach or drop instead of a mass DELETE.
  • Without partitioning, move rows in small batches to avoid locks, bloat and replica lag.
  • Cold data can live as Parquet in object storage and still be queried with Athena or DuckDB.
  • Agree on retention rules with legal and finance, and test restores.

Common follow-up questions

  • Why is DROP PARTITION better than DELETE for removing old data?
  • How does partition pruning work, and when does it fail?
  • How would you let support staff query a three-year-old order after archiving?
  • How do you archive data that has foreign keys pointing at it?

Interview tips

  • Lead with partitioning; it is the answer interviewers expect for time-series style growth.
  • Mention retention and compliance; it shows you think beyond pure performance.
  • Explain why mass DELETEs are harmful (locks, bloat, WAL, replica lag) rather than just saying they are slow.

Concepts covered

Data Archiving, Table Partitioning, Cold Storage, Data Retention, Batch Deletes

More Database Design questions