Skip to content

Data Lifecycle, Tiering and Retention

Intermediate 24 min read Part 5 of 18

Manage data from creation to deletion: classification, hot-to-archive tiers, TTLs, downsampling, retention, legal hold, GDPR erasure, crypto-shredding.

Summary#

Data has a life. It's created, used heavily for a while, consulted less and less, and eventually becomes either a legal obligation to keep or a liability to get rid of. Data lifecycle management is the discipline of deciding, for every kind of data, where it lives at each age, how detailed it stays, how long it's kept, and how it's destroyed, and then automating those decisions so they actually happen.

The key ideas on this page:

  • Data classification: label data by sensitivity (public, internal, confidential, restricted, personal), business value and access pattern. Every later decision keys off these labels.
  • Storage tiers: hot (SSD, memory, primary databases), warm (cheaper disks, infrequent-access classes), cold (rarely read) and archive (Glacier-class storage with retrieval times from milliseconds to 48 hours). Cost per GB drops by roughly 20× from S3 Standard to Glacier Deep Archive.
  • Lifecycle rules and TTLs: declarative policies ("move to infrequent access after 30 days, to Deep Archive after 180, delete after 7 years") and per-record time-to-live in Redis, Cassandra, DynamoDB, MongoDB, Kafka and Elasticsearch.
  • Downsampling and compaction: keep 10-second metrics for a week, 1-minute rollups for a month, 1-hour rollups for years. Merge small files and compact logs, so old data costs a fraction of new data.
  • Retention policies and legal hold: minimum retention for regulations and audits, maximum retention for privacy (GDPR's storage limitation), and holds that freeze deletion during litigation, enforced with WORM (write once, read many) storage such as S3 Object Lock.
  • Deletion at scale: honouring the GDPR right to erasure across primary databases, replicas, caches, search indexes, warehouses, logs, event streams and backups, with crypto-shredding (destroying per-user encryption keys) for places where you can't delete bytes.
  • Storage cost math: model the bill as capacity × price + requests + retrieval + transitions + egress, and find the break-even point between tiers.
  • Lineage and catalogues: know what data exists, who owns it, how it's classified and where copies flow, so lifecycle rules and deletions reach every copy.

In system design interviews this shows up as the retention and storage-cost discussion in almost every data-heavy problem: metrics monitoring, logging, chat history, video storage, ad events, top-K. Saying "raw events are kept 7 days in Kafka, compacted into hourly rollups kept 2 years, raw Parquet in S3 moves to Glacier after 90 days, and user deletion is handled by a deletion service plus crypto-shredding" signals senior-level thinking.

Why It Exists#

Data grows without limit, but its value doesn't. A logging pipeline ingesting 5 TB per day accumulates 1.8 PB per year. A metrics system at 10 million samples per second writes 864 billion samples per day. If everything stays in the hot tier forever:

  1. Cost explodes. Hot storage (SSD-backed databases with replication) can cost 10–100× more per GB than archival object storage. Most old data is rarely or never read again. Facebook's f4 paper (OSDI 2014), for example, showed photo request rates dropping sharply in the weeks after upload. Logs and metrics follow the same pattern, because dashboards and debugging focus on the last hours or days. Keeping old data hot pays the premium for nothing.
  2. Performance degrades. Bigger tables mean deeper indexes, more cache misses, slower scans, longer backups, longer restores, slower schema migrations and larger compactions. A query that scans a table can't get fast by sharding alone: spreading N rows over M nodes only divides the work by M. Shrinking the hot working set, through partitioning by time, rollups and moving old data out, often helps more than adding hardware.
  3. Risk grows. Every stored record is something that can leak, be subpoenaed or be misused. Data you no longer need is pure liability. Breach impact, notification costs and regulatory fines scale with how much personal data you hold.
  4. Law requires both keeping and deleting.
    • Financial, healthcare, telecom and employment regulations require minimum retention, often years.
    • Privacy laws (GDPR in the EU, CCPA/CPRA in California, India's DPDP Act and many others) require purpose limitation, storage limitation (don't keep personal data longer than necessary) and erasure on request.
    • Litigation requires preserving relevant data (legal hold) even if policy says to delete it.
  5. Operations need predictability. Disks fill up. Kafka brokers run out of space. Elasticsearch clusters go red when shards outgrow nodes. Explicit retention is how you keep capacity planning bounded: storage = ingest rate × retention × replication.

Without lifecycle management, teams end up with the classic failure modes:

  • the "data swamp": petabytes nobody understands, owns or dares delete;
  • surprise cloud bills;
  • GDPR deletion requests that take weeks and still miss copies;
  • litigation holds that someone's cleanup job violated.

How It Works#

The stages of a data lifecycle#

Every dataset passes through roughly the same stages. A good design states, for each data class, what triggers each transition and which system enforces it.

  1. Creation and ingestion. Data enters, ideally already tagged with an owner, a classification and a retention class. Assigning these at write time is far cheaper than discovering them later.
  2. Active use (hot). Data is read and written frequently, with low-latency requirements. It lives in primary databases, caches, search indexes and recent Kafka segments.
  3. Aging (warm, then cold). Access frequency falls. Data moves to cheaper media or formats: an older table partition, an infrequent-access storage class, compressed columnar files. It's often summarised (downsampled), and the raw detail moves further out or is dropped.
  4. Archive. Data is kept for compliance, audits, rare investigations or ML retraining. It sits in the cheapest storage, with retrieval latency of minutes to days and per-GB retrieval fees.
  5. Deletion. Data is destroyed when its retention period ends, when a user exercises the right to erasure, or when its purpose ends. It must be removed from every copy, or rendered unreadable.
  6. Holds and exceptions. A legal hold freezes the lifecycle for specific data until the hold is released.

Data classification#

Classification is the step most teams skip, and it's the one everything else depends on. You can't set retention, choose a tier, encrypt correctly or honour erasure requests if you don't know what the data is.

Dimensions to classify on:

DimensionTypical valuesDrives
SensitivityPublic, Internal, Confidential, RestrictedEncryption, access control, masking, where it may be stored
Personal dataNone, personal (PII), sensitive personal (health, biometrics, religion, etc.), children's dataPrivacy obligations, erasure, consent, residency
Regulatory regimePCI DSS (card data), HIPAA (US health), SOX (financial reporting), GDPR, sector-specific record-keeping rulesMinimum and maximum retention, audit logging, WORM
Business criticalityTier 0 (business stops without it) to tier 3 (nice to have)Backup frequency, RPO and RTO, replication (Disaster Recovery and Backups)
Access temperatureHot, warm, cold, archiveStorage tier, format, indexing
ReproducibilitySource of truth vs derived (recomputable)Derived data can have short retention and needs no backup

Two practical points matter most:

  • Source of truth versus derived. Caches, search indexes, materialised views, feature stores and aggregates can be rebuilt from the source. They need short retention and no long-term backup, but they must still honour deletions. Raw source data is expensive to lose and expensive to keep.
  • Reproducibility is a cost lever. If you can regenerate a dataset from raw events in a day, you don't need to archive it for seven years.

How classification is applied in practice:

  1. Schema-level tags. Annotate columns and fields: email: PII, Confidential, card_number: PCI, Restricted. Data contracts and schema registries can carry these tags, so downstream consumers inherit them.
  2. Resource-level tags. Tag buckets, tables, topics and indexes with an owner, a classification and a retention class. Cloud lifecycle rules can then filter by tag.
  3. Automated discovery. Scan stores for patterns (emails, phone numbers, card numbers, national IDs) using tools like Amazon Macie, Google Cloud Sensitive Data Protection (formerly DLP) or Microsoft Purview, and catch untagged sensitive data in logs and data lakes.
  4. Default classes. Anything untagged is treated as Confidential with the shortest allowed retention, so a missing tag fails safe.
  5. Review. Owners periodically re-certify classifications as products change.

A retention schedule maps each class to its rules. For example:

Data classHotThenDelete afterNotes
Application debug logs7 days (search cluster)30 days in object storage30 daysStrip PII at ingest
Security and audit logs90 days (searchable)Archive1–7 years, by policyWORM storage; tamper-evident
MetricsRaw at 15 s for 15 days5 min for 90 days, 1 h for 2 years2 yearsDownsampled
Orders and invoices1 year in OLTP DBWarehouse, then archiveYears, as required by tax and accounting lawLegal minimum
User-generated contentWhile account is active—On deletion request plus grace periodErasure pipeline
Raw clickstream7 days in Kafka90 days of raw Parquet, then aggregates only13 monthsPseudonymise user ids
ML training snapshotsPer experimentArchive1–2 years, or when supersededMust honour erasure (retrain or filter)

The exact periods vary by jurisdiction and company. Legal and compliance teams set the minimums and maximums, and engineering makes them enforceable.

Hot, warm, cold and archive tiers#

A tier is a combination of media, format and service with a particular cost and performance profile:

TierTypical accessLatencyMedia and servicesRelative cost per GB-month
HotMany reads and writes per secondMicroseconds to a few msRAM (Redis), NVMe SSD (primary DBs, search), S3 Express One ZoneHighest: 10–100× archive
WarmReads per day to weekmsHDD-backed clusters, S3 Standard, Standard-IA, GCS Nearline, Azure CoolMedium
ColdReads per month to yearms to seconds, with retrieval feesS3 Glacier Instant Retrieval, GCS Coldline and Archive, Azure ColdLow
ArchiveRarely, for compliance or disaster recoveryMinutes to 48 hoursS3 Glacier Flexible Retrieval, Glacier Deep Archive, Azure Archive, tapeLowest

Amazon S3 storage classes, as an illustration. These are approximate US list prices at the time of writing, which change, so check current pricing. Every class except One Zone stores data redundantly across multiple Availability Zones.

ClassStorage $/GB-monthFirst-byte latencyMinimum storage durationRetrieval feeUse for
S3 Standard~0.023msnonenoneActive data
S3 Intelligent-TieringVaries by access tier, plus a small per-object monitoring feems for frequent and infrequent tiersnonenoneUnknown or changing access patterns
S3 Standard-IA~0.0125ms30 daysper GBRead about monthly; needs multi-AZ
S3 One Zone-IA~0.01ms30 daysper GBRe-creatable infrequent data
S3 Glacier Instant Retrieval~0.004ms90 dayshigher per GBRead about quarterly, but needs instant access
S3 Glacier Flexible Retrieval~0.0036Minutes to hours90 daysper GB plus per requestArchives, backups
S3 Glacier Deep Archive~0.00099Hours180 daysper GB plus per requestLong-term compliance archives

Hidden rules that bite:

  • Minimum storage duration. Deleting a Standard-IA object after 10 days still bills 30 days, and Deep Archive bills at least 180 days. Don't tier data that will be deleted soon.
  • Minimum billable object size. Standard-IA, One Zone-IA and Glacier Instant Retrieval bill each object as at least 128 KB. Millions of 2 KB objects in IA cost more than in Standard.
  • Per-object overhead in Glacier classes. Objects in Flexible Retrieval and Deep Archive carry about 40 KB of extra billed metadata each, part at the Standard rate. Archive bundles (tar or Parquet), not millions of tiny objects.
  • Transition request fees are charged per 1,000 objects moved. Transitioning 1 billion small objects can cost more than storing them for years.
  • Retrieval fees and egress. Reading 100 TB back from an archive costs both retrieval and possibly egress fees. Plan for restores.

Other clouds use the same model:

  • Google Cloud Storage: Standard, Nearline (30-day minimum), Coldline (90-day) and Archive (365-day). All classes have millisecond access, and the trade-off is purely price versus retrieval fees and minimum durations.
  • Azure Blob Storage: Hot, Cool (30-day), Cold (90-day) and Archive (180-day; offline, needing rehydration that takes up to about 15 hours at standard priority, or under an hour at high priority for smaller objects).

Archive retrieval times (S3, approximate):

ClassExpeditedStandardBulk
Glacier Instant Retrieval—Milliseconds—
Glacier Flexible Retrieval1–5 minutes3–5 hours5–12 hours
Glacier Deep Archive—Within 12 hoursWithin 48 hours

A restore creates a temporary readable copy for a number of days you choose, while the archived object stays in place. Plan restores as a workflow: request, poll or receive an event notification, process, then let the copy expire. Bulk restores of millions of objects should use S3 Batch Operations with a manifest.

Tiering inside databases and data systems. The same idea applies inside your stores:

  • Time-partitioned tables. Partition by day or month in PostgreSQL, MySQL or BigQuery. Then detach or drop old partitions: dropping a partition is a metadata operation that takes milliseconds, while DELETE FROM events WHERE ts < ... on billions of rows causes hours of I/O, bloat and replication lag (PostgreSQL in Practice).
  • TimescaleDB: hypertables are automatically chunked by time. Use compression policies (columnar compression of old chunks, often 90%+ smaller), retention policies (add_retention_policy drops chunks older than N days), continuous aggregates (incrementally maintained rollups) and tiered storage of old chunks to object storage in the managed service (Time-Series Databases).
  • Elasticsearch and OpenSearch index lifecycle management (ILM, or ISM in OpenSearch): indexes roll over by size or age and move through hot → warm → cold → frozen → delete phases. Along the way they shrink (fewer shards), force-merge (fewer segments), move to cheaper nodes, and in the frozen tier are mounted as searchable snapshots from object storage (Elasticsearch and Search Systems).
  • Kafka: time and size retention per topic (retention.ms, retention.bytes; the default is 7 days). Tiered storage (KIP-405) offloads closed log segments to object storage, so brokers keep only recent data locally while consumers can still read history (Apache Kafka in Practice).
  • ClickHouse: table-level TTL clauses can delete rows, move parts to a cheaper volume (TO VOLUME 'cold'), recompress with a heavier codec, or roll up (GROUP BY in TTL) as data ages.
  • Data lakes: recent partitions in S3 Standard, older ones transitioned by lifecycle rules. Table formats (Iceberg, Delta) expire snapshots and remove orphan files, so deleted data isn't retained in old versions forever.

Lifecycle rules and TTLs#

There are two complementary mechanisms:

  • Lifecycle rules operate on containers of data: buckets, prefixes, tables, partitions, indexes, topics. They say "objects matching this filter transition at age X and expire at age Y". They're declarative and evaluated by the storage service.
  • TTLs (time-to-live) operate on individual records. Each record carries an expiry time, after which the store treats it as gone and eventually reclaims it.

Object storage lifecycle rules. An S3 lifecycle configuration has:

  • a filter (prefix, object tags, object size range);
  • transitions (to a storage class after N days since creation);
  • expiration (delete after N days);
  • for versioned buckets, noncurrent version transitions and expiration;
  • abort incomplete multipart uploads after N days. This is a common hidden cost, because abandoned upload parts are billed invisibly.

S3 evaluates lifecycle rules asynchronously. Transitions and expirations happen some time after the eligible date, typically within a day or two, so don't use lifecycle expiration as a precise security control. Billing stops at the eligible date for expirations.

Record-level TTLs across common stores:

StoreHow TTL worksGotchas
RedisEXPIRE key seconds or SET ... EX. Keys expire lazily (checked on access) and actively (a background cycle samples keys with TTLs and deletes expired ones)Memory isn't freed instantly; under memory pressure, eviction policies like volatile-lru and allkeys-lru decide what goes (Redis in Practice)
CassandraPer-write USING TTL or a table default_time_to_live. Expired cells become tombstones, purged by compaction after gc_grace_seconds (default 10 days)Tombstone build-up slows reads. Use TimeWindowCompactionStrategy for time-series, so whole SSTables expire and drop at once (Apache Cassandra in Practice)
DynamoDBA designated TTL attribute (epoch seconds). A background process deletes expired items at no write cost, typically within a few days of expiryExpired items may still be returned until deleted, so filter on read. Deletions appear in DynamoDB Streams, flagged as TTL deletes, which is useful for archiving (Amazon DynamoDB in Practice)
MongoDBA TTL index on a date field (expireAfterSeconds). A background task runs about every 60 secondsDeletes are regular deletes that load the primary and replicate; large bursts cause lag
ElasticsearchNo per-document TTL. Use time-based indexes and ILM delete phasesDeleting documents individually is expensive (segment merges), so drop whole indexes
KafkaSegment-level retention by time or size per topic. Log compaction keeps the latest value per keyRetention deletes whole segments, so data can outlive retention.ms by up to a segment's age (segment.ms)
Bigtable and HBaseColumn-family garbage-collection policies (max age, max versions), applied during compactionData is invisible after expiry, but space is reclaimed only on compaction
PostgreSQL and MySQLNo native TTL. Use partitioning plus DROP PARTITION, or batched delete jobs (pg_cron, MySQL events)Row-by-row deletes cause bloat (Postgres VACUUM) and replication lag

Design rules for TTLs:

  • TTL is approximate. Every store reclaims lazily. If expiry has security or correctness meaning, such as a session token or an offer price, check expiry on read as well.
  • Prefer deleting big units. Drop partitions, indexes, SSTables and segments instead of individual rows. Bulk structural deletes are cheap, while row deletes generate tombstones, write amplification and replication traffic.
  • Jitter expirations for caches so millions of keys don't expire in the same second, which causes a stampede on the source.
  • Align TTL with retention class. Derive TTL values from the record's classification, not from a hard-coded number in one service.
  • Archive before expiry when needed. Use DynamoDB Streams TTL events, CDC or a pre-expiry export to copy data to cold storage before it disappears from the hot store (Change Data Capture and the Outbox Pattern).

Downsampling and compaction of old data#

Old data rarely needs full resolution. Downsampling replaces many fine-grained points with fewer coarse summaries. Compaction rewrites data into fewer, denser and better-organised units. Together they make old data cost a small fraction of new data.

Downsampling time-series. A typical retention ladder for metrics:

ResolutionKept forPoints stored per seriesUse
Raw, 10 s7 days60,480Incident debugging, alert evaluation
1 minute30 days43,200Recent dashboards
5 minutes90 days25,920Trends
1 hour2 years17,520Capacity planning, year-over-year

A dashboard showing 30 days at 1-minute resolution reads 43,200 points per series. Over raw 10-second data it would be 259,200 points, six times the work, for a chart that's only about 1,000 pixels wide. Long-range queries over weeks of data stay fast because they read rollup tables, not raw points. This is how metrics systems serve low-latency dashboards over long windows (Design a Metrics Monitoring and Alerting System).

What to store in a rollup. Storing only the average destroys information: you can't recover the max, and you can't correctly re-aggregate averages of different-sized groups. Store mergeable aggregates:

  • count and sum, so averages can be recomputed at any coarser level: avg = Σsum / Σcount;
  • min and max, because spikes matter for alerting and capacity;
  • for counters, the last value or the increase over the window, so rates survive;
  • for latency distributions, histograms or quantile sketches (t-digest, DDSketch, HDR histogram buckets). These merge across windows and hosts, whereas a stored p99 can't be averaged (Probabilistic Data Structures for Big Data).

Tools:

  • Thanos and Cortex/Mimir compactors downsample Prometheus blocks. Thanos creates 5-minute downsampled blocks for data older than 40 hours, and 1-hour blocks for data older than 10 days. You set separate retention for raw, 5-minute and 1-hour resolutions.
  • TimescaleDB continuous aggregates, InfluxDB tasks, ClickHouse materialised views or TTL GROUP BY, and Druid rollup at ingestion.
  • Top-K and leaderboards keep per-minute or per-hour counts with short retention, rolled up into hour, day and month tables with longer retention. This is the same ladder applied to a different query (Design Top-K / Trending (Top Videos, Leaderboards)).

Compaction of old data takes several forms:

  • Small-file compaction in data lakes merges thousands of small files from streaming writes into 256 MB–1 GB Parquet files. That improves scan speed and cuts per-object costs before data moves to colder tiers (Distributed File Systems: GFS, HDFS and Successors).
  • Columnar re-encoding. Rewrite row-oriented JSON logs into Parquet or ORC with dictionary encoding and ZSTD. A 5–10× size reduction is common for logs.
  • Heavier compression for older data. Use LZ4 or Snappy for hot data (fast to decode) and ZSTD at high levels for cold data (slower, smaller). ClickHouse's TTL ... RECOMPRESS and TimescaleDB compression do this automatically.
  • Kafka log compaction keeps only the latest record per key, so a topic of user profile updates holds one record per user, not every change. A record with a null value (a tombstone) deletes the key after delete.retention.ms. This is also how deletions propagate through compacted topics.
  • LSM compaction inside storage engines purges overwritten and expired data and tombstones (Storage Engines: B-Trees vs LSM Trees).
  • Dropping detail. Keep aggregates, and drop or pseudonymise raw identifiers after N days. For example, the raw clickstream with user ids is kept for 90 days, and anonymous aggregates are kept indefinitely. This cuts both storage and privacy risk.

Archival storage and retrieval#

Archive tiers trade access latency for very low storage cost. Designing for them means thinking about how data will come back, not just how it goes in.

Principles of a good archive:

  1. Archive in self-describing, open formats. Use Parquet or ORC for tables, with the schema embedded, and standard containers (tar, zip, WARC for web crawls) with manifests. In 10 years the service that wrote the data may not exist, and the archive must be readable without it.
  2. Bundle small items. Pack millions of small records into objects of 100 MB to a few GB. That avoids per-object fees, minimum-size billing, Glacier's per-object metadata overhead and slow per-object restores.
  3. Keep an index in a hot tier. Keep a catalogue of what is in each archive object (time range, tenant, ids, schema version) in a database or a table format's manifest. A restore can then fetch the 3 objects you need instead of 30,000.
  4. Encrypt with managed keys and record key ids with the data. Losing the key is losing the archive, which is exactly what crypto-shredding exploits on purpose.
  5. Verify integrity. Store checksums (S3 supports SHA-256 and CRC checksums per object) and periodically test-restore samples. An untested archive is a hope, not a backup.
  6. Replicate across regions if the data is irreplaceable: S3 Cross-Region Replication into a Glacier class in another region, or a separate account to guard against account compromise.
  7. Plan the restore path and its cost.
    • Restoring 50 TB from Deep Archive with bulk retrieval takes up to 48 hours, plus processing time.
    • Retrieval fees run from roughly $0.0025/GB (Deep Archive bulk; Flexible Retrieval's bulk tier is free) to $0.03/GB (Flexible expedited), plus request fees. Restoring 50 TB costs from about $125 to $1,500 in retrieval alone, before any egress.
    • Audits, legal discovery and ML retraining should be able to tolerate this. Incident response usually can't, so keep 30–90 days of operational data in an instant tier.

Tape is still alive. Large archives, at hyperscalers, research labs and media companies, still use LTO tape libraries. LTO-9 holds 18 TB native per cartridge. Tape has a very low cost per TB, is offline by nature (an "air gap" against ransomware) and lasts decades, but needs robot libraries and periodic migration to newer generations. Cloud archive tiers abstract this away. Their exact media isn't something to assume.

Archive vs backup. These are often confused:

  • A backup is a copy for recovery. It's short-to-medium retention (days to months), restored when something breaks, and rotated automatically.
  • An archive is the primary long-term home of data that's been removed from active systems, kept for its retention period, and retrieved for business, legal or research reasons.

A backup policy of "35 days of daily snapshots" is not a 7-year retention solution, and keeping 7 years of full backups is a very expensive archive that also makes erasure nearly impossible. See Disaster Recovery and Backups.

A retention policy states how long each data class is kept, why (the legal basis or business purpose), and what happens at the end (delete, anonymise or archive). There are two opposing pressures:

  • Minimum retention: you must keep it. Examples:
    • financial and accounting records for tax and audit (commonly around 5–10 years, depending on the country);
    • broker-dealer communications and records under US SEC rules;
    • healthcare records under national laws;
    • security audit logs for compliance frameworks (PCI DSS requires at least one year of audit log history, with three months immediately available);
    • telecom metadata in some jurisdictions.
  • Maximum retention: you must not keep it longer than needed. GDPR Article 5(1)(e), the "storage limitation" principle, says personal data must be kept in identifiable form no longer than necessary for its purposes. Other privacy laws have similar rules. Your privacy policy's stated periods become commitments.

When the two conflict (a user asks for erasure, but tax law requires keeping their invoices), legal obligation wins for that specific data. You keep the invoice, restrict its use to that purpose, and delete everything else.

Making retention enforceable:

  1. Encode the schedule as configuration. A central retention registry maps classes to periods. Lifecycle rules, TTLs and deletion jobs read from it, rather than each team picking numbers.
  2. Attach the class to the data: tags on buckets and objects, table properties, topic configs, column metadata.
  3. Automate expiry with lifecycle rules, TTLs, partition drops and scheduled jobs that report what they deleted.
  4. Audit. Periodic scans find data older than its class allows, and report violations to owners.
  5. Document exceptions with an owner, a justification and an expiry date for the exception itself.

Legal hold. When litigation, a regulatory investigation or an audit is reasonably anticipated, the organisation must preserve potentially relevant data, even data scheduled for deletion. Destroying it (spoliation) can lead to severe court sanctions. A legal hold:

  • is scoped to custodians (people), date ranges, systems and data types;
  • suspends all deletion for that scope: lifecycle rules, TTL jobs, user-initiated deletes, mailbox purges;
  • is tracked by legal with an audit trail, and released when the matter ends, after which normal retention resumes.

Engineering for legal hold:

  • Every deletion path (lifecycle jobs, TTL sweepers, erasure service, admin tools) must check for holds before deleting. This is easiest when deletion is centralised behind one service.
  • Storage-level holds make it tamper-proof:
    • S3 Object Lock supports retention periods in two modes:
      • Governance mode: users with special permission can override.
      • Compliance mode: nobody, including the root account, can delete or shorten retention until it expires.
    • It also supports an independent legal hold flag that prevents deletion until it's removed, regardless of retention dates. Object Lock was assessed for SEC 17a-4, CFTC and FINRA WORM requirements.
    • Azure Blob immutability policies (time-based retention and legal hold) and Google Cloud Storage bucket lock and object holds are equivalents.
  • Holds beat erasure requests in most legal frameworks: GDPR erasure doesn't apply where processing is necessary for the establishment, exercise or defence of legal claims. Record that an erasure was deferred because of a hold, and execute it when the hold is released.

Deletion at scale and the right to erasure#

GDPR Article 17, the "right to erasure" or "right to be forgotten", lets a person ask for their personal data to be erased when, among other grounds:

  • it's no longer necessary for its purpose;
  • they withdraw consent;
  • they object and there's no overriding legitimate ground;
  • it was processed unlawfully.

Exceptions include legal obligations (such as tax records), legal claims, public interest and freedom of expression. The controller must respond without undue delay and within one month, extendable by two further months for complex or numerous requests (Article 12(3)). California's CCPA/CPRA and many other laws grant similar deletion rights.

Why deletion is hard in distributed systems. One user's data is copied everywhere:

Where personal data hides:

  • Primary stores and their replicas. Deleting on the primary propagates through replication, but asynchronous replicas and other regions lag, and a failover to a stale replica can briefly resurrect data.
  • Caches (Redis, CDN, application caches). Explicitly purge, or keep TTLs short.
  • Derived stores: search indexes, recommendation features, feeds (copies of a user's posts in followers' timelines), counters, and analytics aggregates that contain user ids.
  • Data lakes and warehouses. Immutable Parquet files mean "delete one row" requires rewriting the file. Table formats support row-level deletes (Iceberg delete files, Delta deletion vectors), but you must then compact the files and expire old snapshots and time travel. Otherwise the row is still readable from history.
  • Event logs. Kafka topics with long retention, CDC streams, event-sourced stores (whose history is the system of record) and audit logs. These are immutable by design.
  • Logs and traces: application logs that captured emails, IPs or request bodies. Avoid this by scrubbing PII at ingest and keeping log retention short.
  • Backups and snapshots: database backups, volume snapshots, archive copies.
  • ML models and training data. A model trained on a user's data can memorise it. Common practice is to remove the user from training sets and retrain on a schedule. Machine unlearning is an active research area.
  • Third parties: email providers, analytics tools, payment processors, support desks, ad partners. Data processing agreements must include deletion obligations.
  • Copies made by people: spreadsheets, exports, laptops. Policy, tooling (DLP) and access controls matter here.

Architecture of a deletion pipeline:

  1. Intake and verification. Authenticate the requester. Record the request with a timestamp and an id, and start the SLA clock.
  2. Identity resolution. Find every identifier for the person: user id, email, phone, device ids, advertising ids, hashed ids in analytics. An identity graph or mapping table is essential. Without it, deletions miss data keyed by other ids.
  3. Hold and obligation checks. Check legal holds and minimum-retention obligations (see the flowchart above). Mark what must be kept, and why.
  4. Fan-out. Publish a deletion event. Every system that stores personal data registers a deletion handler and is accountable for completing it. Use durable messaging with retries, and make handlers idempotent, because deletion events will be redelivered (Idempotency and Safe Retries).
  5. Grace period, often 14–30 days. Soft-delete first (the account is disabled, data hidden but restorable), so users can change their mind and fraud or abuse cases can be investigated. Then hard-delete.
  6. Execution per store:
    • OLTP: delete rows, cascading through owned objects, such as the user's posts, comments, likes and edges.
    • LSM stores: the delete writes a tombstone, and data is physically gone only after compaction, which you may need to force for compliance-sensitive data.
    • Warehouses: batch deletes, for example daily DELETE ... WHERE user_id IN (deletion_batch) followed by compaction and snapshot expiry.
    • Compacted Kafka topics: produce a tombstone for the key.
    • Immutable logs and backups: crypto-shred, or let them age out.
  7. Verification and audit. Scan systems for the deleted identifiers. Record completion per system. Close the request and keep a minimal record (request id, date, systems completed, not the deleted data) as proof.

Meta's DELF ("DELF: Safeguarding Deletion Correctness in Online Social Networks", Cohn-Gordon et al., USENIX Security 2020) describes deletion at Facebook scale:

  • Developers annotate the data model, saying which edges imply ownership: deleting a user deletes their posts, and deleting a post deletes its comments.
  • A framework executes the cascading deletion across stores asynchronously and reliably, with checkpointing and retries.
  • Restoration logs allow recovery from mistaken deletions for a limited period.
  • Static and dynamic checks catch missing annotations, which would leave orphaned data, and over-eager ones, which would delete data that isn't owned.

The backup problem. You generally don't edit backups to remove one person. It's impractical, and it risks corrupting the backup. The widely accepted approach is to:

  1. Bound backup retention, for example 35 days, so deleted data ages out of backups within a known, documented period.
  2. Put backups beyond use in the meantime: access-controlled, encrypted, and used only for restores.
  3. Keep a deletion log (ids and timestamps of erasures), and re-apply it after any restore, so restored data doesn't resurrect deleted users.
  4. Crypto-shred where backups must be kept longer.

Document this in your privacy notice. Regulators have generally accepted it when it's done consistently.

Resurrection bugs to watch for:

  • Cassandra zombie data. If a replica is down for longer than gc_grace_seconds (default 10 days) and misses the tombstone, then after tombstones are purged it may reintroduce the deleted data during repair. Run repairs within gc_grace_seconds.
  • Async replica failover to a replica that hadn't applied the delete.
  • Restores from backup without replaying the deletion log.
  • Late-arriving events. A deleted user's offline device syncs old data after deletion. Reject writes for deleted identities.
  • Caches repopulated from a stale replica.

Crypto-shredding#

Crypto-shredding (also called cryptographic erasure) makes data unrecoverable by destroying the key it was encrypted with, instead of finding and deleting every copy of the bytes.

How it works:

  1. Envelope encryption. Each user (or tenant, or record set) gets its own data encryption key (DEK). Data is encrypted with the DEK, using AES-256-GCM for example. The DEK itself is encrypted (wrapped) by a key encryption key (KEK) held in a KMS or HSM (AWS KMS, Google Cloud KMS, Azure Key Vault, HashiCorp Vault).
  2. Storage. The encrypted data can be copied anywhere: replicas, logs, Kafka, the data lake, backups. Only the wrapped DEK needs to be in a key store.
  3. Read path. Fetch the wrapped DEK, have the KMS unwrap it (cached briefly in memory), and decrypt.
  4. Erasure. Delete the user's DEK, and every wrapped copy of it. Every ciphertext copy, including in backups, immutable logs and archives, becomes undecryptable noise.
encrypt(record, user):
  dek = keystore.get_or_create(user.id)          // per-user 256-bit key, wrapped by a KMS KEK
  return { key_id: user.id, nonce, ciphertext: AES_GCM(dek, nonce, record) }
 
erase(user):
  keystore.delete(user.id)                       // wrapped DEK gone from primary key store
  keystore_backups.schedule_purge(user.id)       // key-store backups expire within a short, bounded window
  audit.log("crypto-shredded", user.id, now())
  // all ciphertext copies (logs, lake, backups) are now unreadable

Where it shines:

  • Event-sourced systems and immutable logs, where history can't be rewritten. Encrypt the personal fields of each event with the subject's key.
  • Backups and archives that must be kept for years for other reasons.
  • Multi-tenant SaaS: a tenant leaves, you shred the tenant key, and all their data is gone everywhere at once (Multi-Tenant SaaS Architecture).
  • Kafka topics with long retention, and data lakes with many copies.

Caveats:

  • The key store becomes the system of record for erasure. It must be highly available (no key, no reads) and durable (losing keys loses data you didn't mean to lose). It must also have bounded-retention backups, or the "deleted" key lives on in a key-store backup. Keep key-store backups short-lived and separate.
  • Plaintext leaks defeat it. Decrypted copies in caches, search indexes, logs, analytics extracts or ML features aren't protected. Crypto-shredding complements deletion in those systems. It doesn't replace it.
  • Key granularity versus cost. Per-user keys for 1 billion users are 1 billion wrapped DEKs, about 100+ GB of key material: fine in a database, but KMS calls must be cached. Per-record keys are usually overkill. Per-tenant keys are coarse, but simple.
  • Aggregation and search. Encrypted fields can't be indexed or aggregated server-side. Encrypt only identifying fields (name, email, free text), and keep non-personal fields in plaintext.
  • Legal acceptance. Regulators and standards bodies (NIST SP 800-88 discusses cryptographic erase for media sanitisation) recognise cryptographic erasure when keys are strong and truly destroyed. Document the approach and its key-lifecycle controls.
  • Long horizons. Ciphertext kept for decades should use algorithms expected to remain secure: AES-256 is the common choice.

Storage cost math#

Storage bills have more terms than "GB × price". A useful model for object storage is:

monthly_cost =  Σ_tiers ( GB_in_tier × price_per_GB_month )
              + Σ_ops   ( requests / 1000 × price_per_1000 )   // PUT, GET, LIST, lifecycle transitions
              + retrieval_GB × retrieval_price                  // IA and Glacier classes
              + early_deletion_penalties                        // minimum storage duration
              + egress_GB × egress_price                        // to internet or other regions
              + monitoring fees (e.g. Intelligent-Tiering, per object)

For self-managed storage (databases, HDFS, Kafka, Elasticsearch), the equivalent is:

raw_capacity = logical_data × replication_factor (or EC overhead) × (1 + index/overhead) / target_fill
cost         = raw_capacity × $/GB of the node type   // SSD vs HDD nodes, plus compute you pay for alongside

Worked example: application logs. Ingest is 5 TB/day of raw JSON logs. The requirement is 14 days searchable, 1 year retrievable and 7 years for security-relevant logs. Prices are approximate.

Option A: keep everything in a search cluster for 1 year.

  • Logical data: 5 TB × 365 days = 1,825 TB.
  • Elasticsearch with 1 replica plus index overhead is about 2.2× logical, so about 4 PB of SSD-backed storage.
  • At an all-in $0.10 per GB-month for SSD nodes, that's **$400,000 per month**. And search over a 4 PB cluster is slow and operationally painful.

Option B: a lifecycle design.

StageData heldFormatTierApproximate monthly cost
Searchable, 14 days70 TB logical, about 154 TB with replica and overheadElasticsearch hot nodesSSD at ~$0.10/GB~$15,400
Raw archive, days 0–30150 TB, compressed about 8× to Parquet with ZSTD, so about 19 TBParquet in S3Standard at $0.023~$440
Days 30–365about 210 TB compressedParquetGlacier Instant Retrieval at $0.004~$840
Security subset, 10%, years 1–7about 140 TB compressed at steady stateParquetDeep Archive at $0.00099~$140
Total~$17,000 per month

That's about a 20× reduction, mostly from three moves:

  1. Short hot retention. Fourteen days in the expensive tier, not a year.
  2. Compression and columnar format. An 8× size reduction is typical for JSON logs converted to Parquet with ZSTD.
  3. Cold tiers for data nobody reads routinely.

Add Athena, Trino or Spark queries over Parquet for occasional investigations, which are paid per query (about $5 per TB scanned in Athena). Partition pruning keeps that cheap.

Break-even between tiers. S3 Standard-IA saves about $0.0105/GB-month over Standard, but charges about $0.01/GB retrieved. So IA wins if each byte is read less than about once per month. Glacier Instant Retrieval saves about $0.019/GB-month over Standard, and retrieval costs about $0.03/GB, so it wins if data is read less than about once every 1.5 months. Add the minimum storage duration: an object deleted before 30 or 90 days pays the remainder anyway. For data with unknown access patterns, S3 Intelligent-Tiering automates this:

  • objects not accessed for 30 days move to an infrequent tier;
  • after 90 days they move to an archive instant tier;
  • optional deeper archive tiers are available;
  • a small per-object monitoring fee applies, and objects under 128 KB are not monitored or moved.

Kafka retention sizing. Brokers need disk for write rate × retention × replication factor.

  • With 200 MB/s produced, 7 days of retention and RF 3, that's 200 MB × 604,800 s × 3 ≈ 363 TB of broker disk.
  • Cutting retention to 24 hours and enabling tiered storage for history keeps brokers at about 52 TB, with the rest in object storage at a fraction of the cost.

Small-object penalty, worked. Take 1 billion objects of 4 KB each, which is 4 TB.

  • In S3 Standard that's about $92 per month.
  • Moved to Standard-IA, each object is billed at 128 KB, so it becomes 128 TB billed, about $1,600 per month. That's 17× more.
  • The lifecycle transition requests themselves cost about $0.01 per 1,000, so about $10,000 one-time.

The lesson: bundle small objects before tiering, or exclude them with an object-size filter in the lifecycle rule.

Other cost levers:

  • Compression: ZSTD, delta encoding for time-series and Gorilla-style XOR compression for floats.
  • Deduplication: content-addressed chunks for files and backups.
  • Erasure coding instead of 3× replication for self-managed cold data.
  • Deleting what you don't need. The cheapest byte is the one you never store, so sample debug logs and drop verbose fields.
  • Watching egress. Cross-region replication and analytics in another cloud can cost more than the storage itself.

Data lineage and catalogues#

You can't manage the lifecycle of data you can't find. Data catalogues and lineage answer three questions: what data exists, what it means, and where it flows.

A data catalogue is a searchable inventory of datasets: tables, topics, buckets, dashboards, ML features. For each one it records:

  • technical metadata: schema, location, format, partitioning, size, freshness;
  • business metadata: description, owner and steward, domain, glossary terms;
  • governance metadata: classification tags (PII, PCI), retention class, legal holds, access policies, quality checks;
  • usage: who queries it, how often, and which jobs read it. That tells you whether it's still used, and whether it can move to a colder tier or be deleted.

Data lineage is the graph of how data moves and transforms. "Table daily_revenue is computed by job revenue_rollup from orders and refunds, which come from the payments Postgres via CDC into Kafka topic payments.orders." Lineage can be:

  • coarse, at the job and dataset level: which datasets feed which;
  • fine, at the column level: daily_revenue.amount derives from orders.total_cents minus refunds.amount_cents.

Why lineage matters for the lifecycle:

  1. Deletion propagation. When user 42's data is erased in users, lineage tells you every downstream table, feature store and export that derived data from it and must also be cleaned or recomputed.
  2. Classification inheritance. If a column is tagged PII, every column derived from it inherits the tag, unless a transformation (aggregation, anonymisation) explicitly removes it.
  3. Retention inheritance. Derived datasets shouldn't outlive the retention of the sensitive inputs they contain.
  4. Impact analysis. Before deleting or archiving a dataset, see what breaks: which dashboards, models and jobs read it.
  5. Debugging and trust. Trace a wrong number in a dashboard back to its source.
  6. Compliance evidence. GDPR's records of processing (Article 30), and audits, ask where personal data goes.

Tools:

  • OpenLineage: an open standard for emitting lineage events from jobs (Spark, Airflow, dbt, Flink), with Marquez as its reference backend.
  • DataHub (originally from LinkedIn), Amundsen (Lyft), Apache Atlas (Hadoop ecosystem) and OpenMetadata: open-source catalogues with lineage.
  • Cloud catalogues: AWS Glue Data Catalog with Lake Formation tags, Google Dataplex and Data Catalog, Microsoft Purview, Databricks Unity Catalog (with column-level lineage), and Snowflake's object tagging and access history.
  • dbt generates lineage graphs for SQL transformation projects.

Lineage capture approaches:

  • Parse SQL and query logs. This is automatic, but misses non-SQL code.
  • Instrument job frameworks (OpenLineage integrations). This is accurate for supported engines.
  • Developers declare lineage in data contracts. This works for custom services.

Most mature platforms combine all three, and treat lineage as part of the data platform, not an afterthought (Data Pipelines, Warehouses and Lakes).

When to Use It#

Every system that stores data needs a lifecycle policy. The question is how much machinery it deserves. Invest in explicit lifecycle management when:

  • Data volume grows quickly. Logs, metrics, events, media, IoT readings, chat history: anything with ingest above about 100 GB/day, where a year of hot storage would dominate your bill.
  • Access is strongly skewed by age. Recent data is hot and old data is rarely read. This describes nearly all event, log, metric and user-content workloads.
  • You hold personal data. GDPR, CCPA and similar laws require retention limits and erasure, so you need classification, a deletion pipeline and, often, crypto-shredding.
  • Regulations demand minimum retention or immutability: finance, healthcare, telecom, the public sector, or audit logs under security frameworks.
  • Your stores have hard capacity limits: Kafka broker disks, Elasticsearch node heaps and shard counts, Redis memory, a single Postgres primary's disk.
  • You run multi-tenant platforms, where tenants leave and expect their data destroyed, and where per-tenant retention differs by plan.

Pick something else instead when:

  • The dataset is small and stable, a few GB of configuration or reference data. A simple backup policy is enough, and tiering adds complexity for pennies.
  • Every record stays hot for its whole life: an account balance, a current product catalogue. Retention is "for as long as the entity exists", and deletion follows the entity.
  • The data is fully derived and recomputable. Give it a short TTL and rebuild it, rather than archiving it.

When NOT to Use It#

  • Don't archive data that will be deleted soon. Minimum storage durations (30–180 days) and transition fees make short-lived data cheaper in Standard.
  • Don't tier billions of tiny objects individually. Minimum billable sizes and per-object fees invert the savings. Bundle first.
  • Don't put data you need during incidents into an archive tier. A 12-hour restore is useless at 3 a.m. Keep an operational window in an instant tier.
  • Don't rely on TTL or lifecycle timing for security. Expiry is asynchronous, so enforce expiry on read for tokens and secrets.
  • Don't build a custom deletion framework before you have a data inventory. Without classification and lineage, you'll delete from the obvious tables and miss the copies.

How to Implement It#

  1. Inventory and classify. Build or adopt a catalogue. Tag every dataset with an owner, a sensitivity, personal-data status, a regulatory regime and a retention class. Run automated PII discovery on lakes and logs.
  2. Write the retention schedule with legal. Set the minimum and maximum per class, the end-of-life action (delete, anonymise or archive) and the hold process. Store it as configuration that systems read.
  3. Design tiers per data class. Choose the hot window (driven by query SLOs and incident needs), the warm and cold windows, the archive format and the restore SLA. Decide what gets downsampled and what raw detail is dropped.
  4. Implement the mechanics:
    • object-store lifecycle rules, filtered by prefix, tag and size;
    • time-partitioned tables with partition drops;
    • record TTLs where stores support them;
    • ILM for search, Kafka retention plus tiered storage;
    • rollup jobs or continuous aggregates;
    • compaction jobs for small files.
  5. Build the deletion service: intake, identity resolution, hold checks, event fan-out to registered handlers in every store, a grace period, verification, an audit trail and SLA tracking. Add deletion-log replay to restore procedures.
  6. Add crypto-shredding for immutable and long-lived copies (event logs, backups, archives): per-user or per-tenant DEKs in a key service backed by a KMS, with bounded key-store backups.
  7. Enforce holds and immutability: S3 Object Lock or equivalent for WORM data, and a hold check in every deletion path.
  8. Track lineage, using OpenLineage or catalogue integrations, so classification, retention and deletions propagate to derived datasets.
  9. Monitor and audit:
    • storage by tier and by class;
    • data older than its allowed retention;
    • deletion request latency (p50 and p99 against the one-month deadline);
    • failed deletion handlers;
    • lifecycle rule errors;
    • restore drill results;
    • cost per TB per month.
  10. Review quarterly. New data types appear, products change and laws change.

An S3 lifecycle configuration for a logs bucket, alongside a matching ClickHouse table TTL:

{
  "Rules": [
    {
      "ID": "app-logs-tiering",
      "Filter": { "And": { "Prefix": "logs/app/", "ObjectSizeGreaterThan": 131072 } },
      "Status": "Enabled",
      "Transitions": [
        { "Days": 30,  "StorageClass": "STANDARD_IA" },
        { "Days": 90,  "StorageClass": "GLACIER_IR" },
        { "Days": 180, "StorageClass": "DEEP_ARCHIVE" }
      ],
      "Expiration": { "Days": 400 },
      "NoncurrentVersionExpiration": { "NoncurrentDays": 7 },
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
    }
  ]
}
-- ClickHouse: hot on SSD, move to an HDD/S3 volume at 14 days, roll up raw rows, drop at 400 days
CREATE TABLE app_events (
  ts DateTime, tenant_id UInt32, user_id UInt64, event LowCardinality(String), latency_ms UInt32
) ENGINE = MergeTree
PARTITION BY toYYYYMM(ts) ORDER BY (tenant_id, event, ts)
TTL ts + INTERVAL 14 DAY TO VOLUME 'cold',
    ts + INTERVAL 90 DAY RECOMPRESS CODEC(ZSTD(9)),
    ts + INTERVAL 400 DAY DELETE
SETTINGS storage_policy = 'hot_to_cold';

The size filter (above 128 KB) keeps tiny objects in Standard, where they're cheaper. The 400-day expiration is set after Deep Archive's 180-day minimum, so no early-deletion penalty applies.

TechnologyFits when
S3 lifecycle rules, Intelligent-Tiering, Object LockAWS object data: tiering, expiry and WORM retention or legal hold
GCS lifecycle plus Autoclass, bucket lockGoogle Cloud objects; Autoclass for unknown access patterns
Azure Blob lifecycle management plus immutability policiesAzure objects, including the archive tier and legal hold
Partitioned PostgreSQL or MySQL plus pg_partman or cron jobsRelational time-series or event tables: drop old partitions cheaply
TimescaleDB compression, retention and continuous aggregatesTime-series in Postgres with rollups and automatic expiry
Thanos, Mimir, or VictoriaMetrics retention and downsamplingLong-term Prometheus metrics with multi-resolution retention
Elasticsearch ILM or OpenSearch ISM plus searchable snapshotsLogs and search data moving hot → warm → cold → frozen → delete
Kafka retention, compaction and tiered storageEvent streams: bounded broker disk with history in object storage
Cassandra TTL plus TimeWindowCompactionStrategyHigh-volume time-bucketed data that expires whole SSTables at once
Iceberg, Delta or Hudi plus snapshot expiry and compactionData lakes needing row-level deletes for GDPR and controlled history
AWS KMS, Cloud KMS, Key Vault or Vault plus a key serviceEnvelope encryption and crypto-shredding
DataHub, OpenMetadata, Unity Catalog, Purview, Dataplex, OpenLineageCatalogue, classification tags and lineage
Amazon Macie, Cloud Sensitive Data Protection, Purview scanningDiscovering untagged PII in buckets and lakes

Trade-offs#

OptionProsConsPick when
Keep everything hotSimple; every query is fastCost grows without limit; slower systems; maximum privacy riskSmall datasets only
Age-based tieringLarge savings; predictable; easy to reason aboutSome old data is still hot (popular items), and it pays retrieval costsStrong age-access correlation: logs, metrics, events
Access-based tiering (Intelligent-Tiering, Autoclass, LRU)Adapts to real access patternsMonitoring fees; less predictable bills; small objects excludedUnknown or mixed access patterns
Downsampling10–100× less data for long ranges; fast long-window queriesDetail lost forever; must pick the right aggregatesMetrics and analytics where trends matter more than individual points
Hard deletion everywhereData truly gone; clean compliance storyHard across replicas, lakes, logs and backups; risk of mistakesMutable stores with good lineage
Crypto-shreddingErases immutable copies and backups at onceKey service is critical; plaintext copies escape it; blocks server-side indexing of encrypted fieldsEvent sourcing, long-lived logs, backups, multi-tenant exits
Soft delete with grace periodUndo for mistakes; fraud investigation windowData still exists, which must be disclosed and boundedUser-facing account and content deletion
WORM, Object Lock compliance modeTamper-proof retention; meets regulator requirementsCan't delete even by mistake-fixing admins; erasure deferredRegulated records and audit logs

Common Pitfalls#

  • No owner, no classification. Data without an owner is never deleted, and data without a class gets the wrong retention.
  • Retention only in the primary database. Forgetting caches, search indexes, the warehouse, Kafka, logs, backups and third parties, which is where erasure audits fail.
  • Unbounded "temporary" data: scratch buckets, debug dumps, abandoned multipart uploads, old table snapshots, orphaned files after failed jobs.
  • Row-by-row deletes on huge tables, causing bloat, replication lag and locks. Partition by time and drop partitions.
  • Averages-only rollups. You can't recover max, percentiles or correct re-aggregations. Store count, sum, min, max and sketches.
  • Tiering small objects into IA or Glacier, and paying more than before.
  • Archives without an index or format documentation, so they can't be found or read years later.
  • Never testing restores. Discovering at audit time that the archive is unreadable, or that a restore takes 3 days.
  • Backups that outlive erasure promises, without deletion-log replay after restores.
  • Cleanup jobs that ignore legal holds, which can produce court sanctions.
  • Logging PII freely, which turns every log store into an erasure problem. Scrub at ingest.
  • Lifecycle rules that silently fail, through a wrong prefix, a missing tag or a version misconfiguration. Monitor storage by age and class.

Real-World Examples#

  • Facebook's photo storage moved from Haystack (hot, replicated) to f4 (warm, erasure-coded) as photos aged and their request rates fell, cutting the effective replication factor from 3.6 to 2.1 (Muralidhar et al., OSDI 2014).
  • Meta's DELF framework enforces cascading deletion correctness across Facebook's data stores (Cohn-Gordon et al., USENIX Security 2020).
  • Prometheus ecosystem. Thanos, Cortex and Mimir use object storage with compaction and downsampling (raw, 5 m, 1 h), so long-term metrics stay affordable.
  • Elastic's hot-warm-cold-frozen architecture, with searchable snapshots on object storage, is the standard pattern for large log clusters.
  • Kafka tiered storage (KIP-405) was developed by the Apache Kafka community, and it's offered by managed services such as Confluent Cloud and Amazon MSK. It lets clusters keep long history without huge broker disks.
  • AWS S3 Glacier Deep Archive (launched in 2019) is designed as a replacement for on-premises tape for long-term retention, at about $1 per TB-month.
  • The GDPR right to erasure applies to every company serving EU residents, which is why large platforms such as Google, Meta and Microsoft operate dedicated deletion and privacy infrastructure.

Case studies that use this pattern#

In the Interview#

Common follow-ups:

  • "How do you keep dashboards fast over a year of data?" Downsample into rollups (store count, sum, min, max and sketches), route long-range queries to coarse resolutions, and partition by time.
  • "A user deletes their account. Walk me through it." Soft-delete and hide immediately. After the grace period, a deletion event fans out to every store via handlers, then caches are purged, search docs removed, warehouse rows deleted and compacted, Kafka tombstones written, and immutable copies crypto-shredded. Backups expire within N days and restores replay the deletion log. Finally, verify and audit, all within one month.
  • "How do you cut the storage bill in half?" Shorten hot retention, compress and convert to columnar formats, tier by age with lifecycle rules (bundling small objects), erasure-code self-managed cold data, and delete unused datasets found through catalogue usage stats.
  • "What if legal needs data you've scheduled for deletion?" Legal hold: every deletion path checks holds, and WORM storage (Object Lock) prevents tampering. Deferred deletions execute when the hold is released.
Deep Dive: Deletion Correctness at ScaleShow

Deleting one row is easy. Proving that a person's data is gone from a system with hundreds of stores, thousands of tables and petabytes of backups is a distributed-systems problem. It has the same flavour as a distributed transaction, but it takes days and has no rollback.

Why deletion is hard: the graph problem. User data is not one record. It is a graph of objects: the account, its posts, comments on other people's posts, likes, messages, uploaded media, derived embeddings, and search-index entries. Each edge raises a question. If a user deletes their account, should their comment on a friend's post go too? Usually yes. Should the friend's reply to that comment go? Usually no, though it might be shown as "reply to a deleted comment". Meta's DELF paper (Cohn-Gordon et al., USENIX Security 2020) formalises this. Engineers annotate every edge type in the data model with a deletion semantic, for example "deep" (cascade into the target), "shallow" (remove only the edge) or "refcount" (delete the target when no owners remain). The framework then executes cascades from the annotations instead of hand-written code. Its key insight is that the annotations themselves can be wrong. DELF therefore also detects likely mistakes with static checks, for example an edge marked "shallow" whose target has no other path to an owner and would become orphaned. It surfaces these to engineers, and the paper reports finding many real bugs that way.

Making cascades reliable. A deletion for a heavy user can touch millions of objects (years of messages and photos). The pattern looks like a long-running saga:

  1. Persist the request durably before acting: a deletion job record with a state machine (requested → in grace → executing → verifying → done).
  2. Execute in idempotent batches. Each batch deletes N objects and records progress. A crash resumes from the last checkpoint, and re-deleting an already-deleted object is a no-op (Idempotency and Safe Retries).
  3. Fan out to stores through registered handlers: one per store or team, each acknowledging completion. The coordinator tracks acknowledgements and alerts on handlers that miss their SLA.
  4. Restore support. DELF logs deleted data to a restoration log for a short window, so an erroneous cascade (a bug in the annotations) can be undone. That log itself has strict retention and access control, a deliberate and time-bounded exception.

Verification. "We called delete" is not the same as "the data is gone". Mature systems add independent checks:

  • Post-deletion scans: query each registered store for the user's identifiers after the job finishes. Any hit becomes an incident.
  • Canary identities: synthetic test accounts with known data are created and deleted regularly, then every store is scanned to confirm complete removal. This is the deletion equivalent of a restore drill.
  • Orphan detection: periodic jobs look for objects whose owner no longer exists. That is evidence of a missed cascade.
  • Lineage-driven coverage: compare the list of datasets that lineage says hold personal data against the list of registered deletion handlers. Any dataset without a handler is a compliance gap.

Physical vs logical deletion. A DELETE in most databases doesn't remove the bytes immediately:

  • PostgreSQL marks tuples dead; space is reclaimed by VACUUM, and the bytes may persist in pages and WAL until overwritten.
  • LSM stores (Cassandra, RocksDB, HBase) write tombstones. The old value persists in older SSTables until compaction merges them. In Cassandra, tombstones must live at least gc_grace_seconds (default 10 days) so that repair can propagate them to replicas that were down. Otherwise a stale replica can resurrect the deleted data.
  • Lakes (Iceberg, Delta) with merge-on-read write delete files. The data files still contain the rows until compaction rewrites them and snapshot expiry removes the old files.
  • Kafka compacted topics need a tombstone (null value) for the key. The record disappears only after the log cleaner runs and delete.retention.ms passes.

A deletion SLA therefore has to include the physical reclamation lag: tombstone grace periods, compaction schedules, snapshot expiry and backup expiry. A common internal target is "logically deleted immediately, physically gone from online systems within about 30 days, gone from backups within about 90 days". Regulators generally accept that backups expire on their normal schedule, provided restored data has the deletion log replayed and isn't used in the meantime. Document this in the privacy policy.

Where ZippyDB-style shared stores fit. Large companies often run one multi-tenant key-value platform shared by many use cases (Meta's ZippyDB is an example). Deletion and TTL there become platform features: per-use-case TTL defaults, per-tenant quotas, and background compaction that drops expired keys. The access layer in front (connection pooling, request batching, coalescing of duplicate reads, and admission control with per-use-case bounded queues) protects the store from one tenant's mass-deletion job starving everyone else. Rate-limit deletion jobs like any other heavy batch traffic. A cascade that issues 10 million deletes in a minute is, operationally, a DDoS on your own database.

Deep Dive: Tiering Economics and the Five-Minute RuleShow

Tiering decisions come down to one comparison: the cost of keeping data in a faster tier vs the cost of fetching it from a slower one when needed. The classic form of this argument is Jim Gray and Franco Putzolu's "five-minute rule" (The 5 Minute Rule for Trading Memory for Disc Accesses, SIGMOD 1987).

The original rule. Keep a page in RAM if it's accessed more often than once every T seconds. The break-even interval is:

T_break_even = (pages per MB of RAM / accesses per second per disk)
             × (price per disk drive / price per MB of RAM)

With 1987 prices, T came out at about 5 minutes. A page touched more often than every 5 minutes was cheaper to cache than to re-read. Gray and Graefe revisited it a decade later ("The Five-Minute Rule Ten Years Later", SIGMOD Record 1997). Later analyses for flash showed the same structure with different constants. The shape of the argument is the durable lesson: break-even access interval = (cost of capacity in the fast tier) / (cost per access in the slow tier).

Applying it to cloud object tiers. Replace "RAM vs disk" with "S3 Standard vs S3 Standard-IA". Use the approximate us-east-1 list prices from earlier in this page:

Saving per GB-month by moving to IA:  0.023 - 0.0125 = 0.0105 $/GB-month
Extra cost per GB read from IA:       0.01 $/GB retrieval (plus slightly higher request fees)
Break-even: IA is cheaper if each GB is read less than about 1.05 times per month

For Glacier Instant Retrieval (about $0.004/GB-month storage, $0.03/GB retrieval):

Saving vs Standard:  0.023 - 0.004 = 0.019 $/GB-month
Break-even reads:    0.019 / 0.03 ≈ 0.63 full reads per GB per month

So GIR pays off only if, on average, each byte is read less than about once every 1.6 months. Add the minimum storage duration (90 days for GIR) and the effective rule becomes "objects that live at least 90 days and are read less than about once every two months". This is exactly the "logs older than 30–90 days" profile, which is why that rule is so common.

Including request costs. For small objects, per-request fees dominate. Suppose IA GETs cost $0.001 per 1,000 vs $0.0004 for Standard, and a 100 KB object is read 10 times a month. The request delta is negligible, but the 128 KB minimum billable size inflates storage by 28%. Below about 128 KB, IA is nearly always worse. This is why the implementation section filtered by ObjectSizeGreaterThan.

The time-to-first-byte dimension. Cost isn't the only axis. Each tier also has a latency SLA: tens of milliseconds for Standard, IA and GIR; minutes to hours for Glacier Flexible; up to 12 or 48 hours for Deep Archive. Model this as a constraint: "data needed within an incident response window of 15 minutes must stay in an instant tier". Then minimise cost subject to it. A simple planning table per data class makes this explicit:

Data classRead rate after 30 daysLatency needTier choice
App logsUnder 0.1 reads/GB/monthMinutes (incident) for 90 daysStandard 30 d → GIR to 180 d → Deep Archive
User photos (old)Long tail, unpredictable100 ms (user-facing)Intelligent-Tiering, or a self-managed warm tier like f4
Compliance recordsAbout 0 (audit only)Days acceptableDeep Archive plus Object Lock
ML training snapshotsBursty full scansHours acceptableStandard during training, then Glacier Flexible

Self-managed storage economics. If you run your own storage (HDFS, Ceph), tiering decisions move from price lists to replication factor and media. Moving data from 3× replication on SSD to RS(10,4) erasure coding on HDD cuts raw bytes from 3.0× to 1.4×, and the per-GB media cost by roughly 5–10×. The trade-off is that reads during failures need reconstruction across many disks (Distributed File Systems: GFS, HDFS and Successors). Facebook's f4 is the canonical example: it targeted "warm" BLOBs whose request rate had fallen to a level that erasure-coded storage could serve with acceptable latency (Muralidhar et al., OSDI 2014).

Access-pattern drift and adaptive tiering. Age-based rules assume access decays monotonically, but popularity can revive. An old video goes viral, or an old log is needed for a security investigation. Adaptive systems (S3 Intelligent-Tiering, GCS Autoclass, cache-like promotion in self-managed systems) track per-object access and move objects back up. The cost is per-object monitoring fees and less predictable spend. A practical hybrid is to use age rules for machine data (logs, metrics, events), whose access is predictable, and adaptive tiering for human-facing content, whose access is long-tailed and unpredictable.

Deep Dive: Downsampling Math, Sketches and Time-Series CompressionShow

Downsampling is lossy compression with a contract: which questions must remain answerable after the raw data is gone? Getting this right is mostly algebra.

Mergeable vs non-mergeable aggregates. An aggregate is mergeable if you can combine two partial results into the result for the union without the raw data.

  • Mergeable: count, sum, min and max merge trivially. The mean is derivable as sum/count, so store both, never the mean alone.
  • Variance: the variance of the union needs count, mean and M2 (the sum of squared deviations), which merge using Chan et al.'s parallel algorithm (1979).
  • Not mergeable: the median and other exact percentiles. The p99 of two hours is not the average or maximum of the two hourly p99s. Averaging percentiles is one of the most common dashboard bugs.

Sketches make quantiles mergeable. To keep latency percentiles after downsampling, store a mergeable sketch instead of exact values:

  • t-digest (Dunning and Ertl, 2019 arXiv paper) clusters values into centroids with more resolution at the tails, which makes it accurate for p99 and p99.9 in a few KB.
  • DDSketch (Masson, Rim and Lee, VLDB 2019) guarantees relative error, for example 1%, on any quantile, with fully mergeable logarithmic buckets. It's used by Datadog, where it was developed.
  • HDR Histogram (Gil Tene) uses fixed log-linear buckets with configurable precision; it's popular in latency benchmarking.
  • Prometheus native histograms use exponential buckets with a configurable schema, so histograms merge across series and time.
  • HyperLogLog (Flajolet et al., 2007) gives mergeable distinct counts (unique users per day, rolled up into unique users per month) with about 0.81% standard error at 16 K registers (12 KB). Note that you can't get monthly uniques by summing daily uniques. Merge the HLL sketches instead (Probabilistic Data Structures for Big Data).
  • Count-Min Sketch (Cormode and Muthukrishnan, 2005) gives mergeable frequency estimates for heavy hitters, which feeds top-K rollups.

The general rule: for every metric you downsample, write down the aggregate set (count, sum, min, max, plus a sketch type if percentiles or uniques are needed). Store that set at each resolution.

Worked example: storage savings. A service emits one latency histogram per instance every 10 seconds; 1,000 instances; each histogram is 40 buckets × 8 bytes = 320 bytes before compression.

Raw:     1,000 × 8,640 samples/day × 320 B ≈ 2.76 GB/day → 30 days ≈ 83 GB
5-min:   merge 30 samples into 1   → 1,000 × 288/day × 320 B ≈ 92 MB/day → 1 year ≈ 34 GB
1-hour:  merge 12 five-minute buckets into 1 → ≈ 7.7 MB/day → 5 years ≈ 14 GB
Cross-instance rollup (drop the instance label): divide again by 1,000

The arithmetic shows why long-range metrics are cheap if you downsample, and why label cardinality matters more than resolution. Keeping an instance label on 5-year data multiplies storage by the instance count.

Time-series compression before downsampling. Raw data itself compresses dramatically because consecutive samples are similar. Facebook's Gorilla (Pelkonen et al., VLDB 2015) introduced two techniques now used widely, including Prometheus TSDB-style chunk encodings:

  • Delta-of-delta timestamps. Scrapes are regular, so the delta between consecutive deltas is usually 0, stored in a single bit. The paper reports about 96% of timestamps compressing to 1 bit.
  • XOR floating-point values. XOR each value with the previous one. Similar values share sign, exponent and high mantissa bits, so the XOR has many leading and trailing zeros. Store only the meaningful middle bits. About 51% of values compressed to a single bit (the value didn't change).

Together these took a 16-byte (timestamp, value) pair down to about 1.37 bytes on average, a roughly 12× reduction. That let Gorilla keep 26 hours of data in memory. Columnar stores achieve similar effects with delta encoding, run-length encoding, dictionary encoding of labels, and general compressors (LZ4, ZSTD). This is why ClickHouse and TimescaleDB compressed chunks routinely report 10–20× ratios on metrics.

Choosing the ladder. The resolution ladder should match query windows. Dashboards typically render 500–2,000 points across the panel width. A 1-year panel at 1-hour resolution is 8,760 points, so it's already more than enough, and raw 10-second data (3.15 M points) would be pure waste. A rule of thumb: pick resolutions so that the longest window queried at each level returns at most a few thousand points per series. Then set retention per level to the longest window you ever query at that level.

What downsampling can't do. It can't answer questions about individual events (which request failed, which user saw an error) or about dimensions you dropped. Keep raw exemplars or sampled traces linked from metrics (Observability: Logs, Metrics and Traces), and keep raw data long enough to cover incident investigations. Typically that means 7–30 days.

Key Takeaways#

  • Data has a lifecycle: create → hot → warm → cold → archive → delete. Design every stage deliberately, driven by a classification (owner, sensitivity, regulation, retention class) and a written retention schedule.
  • Tier by access pattern and latency need. Use age rules for machine data and adaptive tiering for long-tail human content. Respect minimum durations, minimum billable sizes and retrieval fees, and bundle small objects before tiering them.
  • Do the break-even math: a cheaper tier wins only if (storage saving per GB-month) exceeds (reads per GB-month × retrieval cost). Gray and Putzolu's five-minute rule is the same argument.
  • Inside databases, partition by time and drop partitions, use TTLs where supported, and use ILM or tiered storage for search and streams. Never delete row by row at scale.
  • Downsample with mergeable aggregates (count, sum, min, max, sketches like DDSketch, t-digest and HLL). Never average percentiles, and match resolution ladders to query windows.
  • Retention has a minimum and a maximum. Laws can require you to keep data and also require you to delete it. Legal holds override deletion, and WORM storage (Object Lock) enforces immutability.
  • Deletion is a distributed saga: fan out to every store, handle tombstones, compaction, snapshots and backups, replay the deletion log after restores, and verify with scans and canary accounts.
  • Crypto-shredding erases immutable and long-lived copies by destroying per-user or per-tenant keys, but only for data that was encrypted under those keys everywhere.
  • Catalogues and lineage make lifecycle enforceable. You can't retain, tier or delete data you don't know exists.