StackPractices
beginner By Mathias Paulenko

Data Retention Policy Template

A template to define how long data is kept, when it is archived, and when it must be deleted for compliance and cost reasons.

Overview

A data retention policy defines how long an organization keeps data, when it moves to lower-cost storage, and when it is permanently deleted. Use it to classify what you keep, attach periods, handle legal holds, and leave the compliance paper trail in place. A clear policy reduces storage costs, legal risk, and operational complexity.

When to Use

  • Bootstrapping retention rules for a new platform or app before data piles up.
  • Preparing for GDPR, CCPA, HIPAA, or SOC 2 audits — pair this policy with the Data Classification template so every category has an owner.
  • Cutting storage spend by moving stale data down cheaper tiers.
  • Responding to a data subject access or deletion request (see the GDPR data privacy recipe for the request-handling side).
  • Defining backup and archive strategies.
  • Post-breach, when the review asks why that data was still sitting there.

Prerequisites

  • An inventory mapping each data type to its system and storage location.
  • Legal and compliance guidance for minimum and maximum retention periods.
  • Data classification scheme such as public, internal, confidential, restricted.
  • Storage and backup tooling that actually understands lifecycle policies.
  • A working legal-hold process — flagging, suspending deletes, releasing.
  • Someone accountable for each data category or system.

Solution

Template

1. Policy Scope and Roles

FieldDescriptionExample
Policy nameName of the policyCustomer Data Retention Policy
Effective dateWhen the policy takes effect2026-07-01
Review cycleHow often the policy is reviewedAnnually
Policy ownerTeam responsible for the policyData governance
Legal approverCompliance or legal reviewerLegal counsel
Technical ownerTeam implementing controlsPlatform engineering
ScopeSystems and data coveredAll production databases, logs, object storage, and backups

2. Data Categories and Retention Periods

Data CategoryExamplesRetention PeriodArchive AfterDelete AfterLegal Basis
Customer account dataProfiles, preferencesLife of account + 1 year1 year after close2 years after closeContract, legal obligation
Transaction recordsOrders, payments7 years1 year7 years after period closeTax and financial law
Application logsRequest logs, error logs90 days30 days90 daysOperational need
Security logsAuthentication, access logs2 years1 year2 years after creationSecurity and compliance
Backup dataFull and incremental backups30 days30 daysPer backup scheduleDisaster recovery
Analytics dataAggregated events1 year6 months1 year after aggregationLegitimate interest
Marketing dataEmail interactions, leads2 years or until opt-out1 yearOn opt-out or 2 yearsConsent
Temporary dataCache, import files7 days3 days7 daysOperational need

3. Retention Rules by Data Classification

ClassificationMinimum RetentionMaximum RetentionSpecial Handling
PublicAs needed by business1 year or lessNo special handling
InternalBusiness need3 yearsStandard lifecycle
ConfidentialLegal or contract minimum7 years or lessEncryption, access logs
RestrictedRegulatory minimumRegulatory maximumLegal hold process, encryption, audit trail

4. Data Lifecycle Actions

StageTriggerActionResponsible Tool / Team
ActiveData createdStore in primary tier with access controlsApplication team
Cool30 days oldMove to lower-cost storage classStorage lifecycle policy
Archive1 year oldMove to archive with retrieval policyStorage lifecycle policy
Mark for deletionRetention period endsFlag records and notify ownersData governance platform
Secure deletionApproved by legal / policyDelete or anonymize permanentlyPlatform engineering
Audit logEvery lifecycle actionLog retention and deletion eventsAudit logging system
ScenarioProcessOwnerDocumentation
Litigation holdSuspend deletion for affected dataLegal counselHold notice and scope
Regulatory investigationExtend retention as requiredCompliance officerRegulatory request record
Data subject requestReview and delete or anonymizeData privacy teamRequest log and response
Exception requestSubmit reason, risk review, approvalData governanceException register
Policy overrideExecutive approval with legal reviewC-level / legalSigned exception record

6. Deletion and Verification Checklist

  • Data owner confirms retention period has expired.
  • No active legal hold covers the data.
  • Data is deleted from primary storage and indexes.
  • Backups containing the data are purged or scheduled for purge within policy.
  • Archives are deleted or anonymized according to schedule.
  • Derived datasets, caches, and replicas are refreshed or cleared.
  • Deletion is logged with timestamp, owner, and scope.
  • A sample spot-check confirms the deletion.
  • Compliance team reviews deletion logs periodically.

Explanation

Every retention decision trades business value against legal obligation and storage cost — and getting it wrong in either direction is expensive. Putting it in writing kills the ambiguity: engineers know what to delete, auditors get evidence, and the same rules get applied every time. Classify the data, attach a period, automate the transition — that alone removes most of the manual work and stops data lingering past its useful life.

The lifecycle in section 4 follows a fixed, sequential pipeline:

Data lifecycle pipeline: data starts active, cools to cheaper storage, archives, gets marked for deletion when retention expires, and is securely deleted with an audit log entry

Two points in that pipeline cause most real-world failures. The first is propagation: deleting from primary storage doesn’t touch backups, replicas, caches, or derived datasets — which is why the checklist in section 6 exists. The second is the legal hold gate between “mark” and “delete”: without an explicit hold check, lifecycle automation will happily purge data under litigation.

The example periods are a starting point only — legal requirements move with data type and jurisdiction, so — regulations differ by data type and jurisdiction. GDPR’s storage-limitation principle (Art. 5(1)(e)) doesn’t set fixed periods; it requires you to keep personal data “no longer than necessary” and justify each period. HIPAA requires retaining compliance documentation for six years. US tax and financial records (SOX, IRS, SEC/FINRA) commonly require seven years. In regulated environments, security and audit logs typically live anywhere from one to seven years. Anchor every row of the retention table to a named legal basis or a documented business need, and record who approved it.

The same trade-off applies to storage tiers. Hot storage (block volumes, STANDARD object class, warm log indexes) is the most expensive per GB-month and should only hold data you query often. A rough rule that consistently holds up in practice: most operational data is read in its first 30 days, rarely until day 90, and almost never afterwards — which is why the example lifecycle transitions at 30, 90, and 365 days. If your access pattern differs, measure it before setting the thresholds: query the access logs or storage analytics for a month rather than guessing. Also budget for retrieval — archive classes like Glacier and Deep Archive are cheap to store but charge per-GB retrieval fees, so data that auditors or support teams pull regularly belongs in a cool tier, not deep archive.

How to Adopt This Template

Rolling out the policy works best as five passes rather than a single big-bang rewrite:

  1. Inventory — list every data store (databases, object storage, logs, caches, warehouses, backups) and the categories it holds. Retention can’t be set for data nobody inventoried.
  2. Classify — apply the classification scheme from section 3 so every store maps to public, internal, confidential, or restricted.
  3. Assign periods — fill the retention table row by row with a legal basis and an owner for each category. Where the law is silent, write down the business reason.
  4. Automate — implement lifecycle rules (the S3 config and purge script below are starting points), and add the legal-hold gate before any deletion step.
  5. Verify and review — schedule the deletion checklist quarterly, log every action, and re-run the policy after regulatory changes or new data stores.

S3 Lifecycle Policy Configuration

{
  "Rules": [
    {
      "ID": "transition-to-glacier",
      "Status": "Enabled",
      "Filter": { "Prefix": "logs/" },
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 90, "StorageClass": "GLACIER" },
        { "Days": 365, "StorageClass": "DEEP_ARCHIVE" }
      ],
      "Expiration": { "Days": 2555 }
    },
    {
      "ID": "expire-temp-data",
      "Status": "Enabled",
      "Filter": { "Prefix": "temp/" },
      "Expiration": { "Days": 7 }
    },
    {
      "ID": "retain-user-data",
      "Status": "Enabled",
      "Filter": { "Prefix": "users/" },
      "NoncurrentVersionExpiration": { "NoncurrentDays": 90 },
      "Expiration": { "Days": 3650 }
    }
  ]
}

Database Retention Purge Script

-- PostgreSQL scheduled purge job
-- Run weekly via pg_cron or external scheduler

-- Purge expired sessions (retention: 30 days)
DELETE FROM sessions
WHERE created_at < NOW() - INTERVAL '30 days';

-- Purge audit logs (retention: 7 years for compliance)
-- DO NOT purge: archived separately

-- Purge deleted user data (retention: 90 days after deletion)
DELETE FROM user_data
WHERE deleted_at IS NOT NULL
  AND deleted_at < NOW() - INTERVAL '90 days';

-- Purge event logs (retention: 180 days)
DELETE FROM event_logs
WHERE created_at < NOW() - INTERVAL '180 days';

-- Vacuum and analyze after purge
VACUUM ANALYZE sessions;
VACUUM ANALYZE user_data;
VACUUM ANALYZE event_logs;

Data Classification and Retention Matrix

=== Data Classification and Retention Matrix ===

| Data Type          | Classification | Retention  | Storage         | Purge Method       |
|--------------------|----------------|------------|-----------------|--------------------|
| User PII           | Confidential   | 3 years    | Encrypted RDS   | Scheduled purge    |
| Payment records    | Restricted     | 7 years    | Encrypted RDS   | Legal hold review  |
| Audit logs         | Internal       | 7 years    | S3 Glacier      | Lifecycle policy   |
| Application logs   | Internal       | 90 days    | CloudWatch      | Auto-expire        |
| Session data       | Internal       | 30 days    | Redis           | TTL auto-expire    |
| Temporary files    | Public         | 7 days     | S3 temp/        | Lifecycle policy   |
| Analytics events   | Internal       | 2 years    | BigQuery        | Partition expire   |
| Backups            | Confidential   | 90 days    | S3 + Glacier    | Backup policy      |
| Customer exports   | Confidential   | 30 days    | S3 signed URL   | Lifecycle policy   |
| ML training data   | Internal       | 1 year     | S3 IA           | Scheduled purge    |

Variants

  • Cloud object storage lifecycle policy: S3, Azure Blob, or GCP Storage rules that move or expire objects — retention enforced where storage costs least.
  • Database retention policy: partition drops beat row deletes; where partitioning doesn’t fit, schedule a purge job.
  • Log retention policy: app, infra, and security logs each age differently — hot retention for debugging, archive for compliance.
  • Customer data retention policy: GDPR and CCPA personal data, where consent and erasure requests drive the periods.
  • Healthcare data retention policy: PHI follows HIPAA’s own retention clock — plus tighter access controls on top.
  • Financial data retention policy: tax and audit records belong on tamper-proof storage regulators can verify.

What Works

  • Classify data before defining retention periods.
  • Let the storage or database itself move data — native lifecycle features beat custom scripts.
  • Apply the shortest retention that satisfies legal and business needs.
  • Keep a centralized inventory of data stores and retention rules.
  • Log every deletion and retention action for audit purposes.
  • Train teams on legal hold and exception processes.
  • Review the policy at least annually and after regulatory changes.
  • Use encryption and access controls for data in retention.
  • Test deletion procedures periodically to ensure data is truly removed.

Common Mistakes

  • Keeping all data forever “just in case.”
  • Deleting data without confirming legal hold status.
  • Forgetting about backups, archives, or replicas when deleting primary data.
  • Applying one flat retention period to every data type.
  • Not documenting exceptions and their approvals.
  • Failing to log deletion events.
  • Ignoring data in third-party services or caches.
  • Not reviewing retention policies after new regulations.

Troubleshooting

  • Purge jobs silently don’t run: the scheduler (pg_cron, EventBridge, cron) fired but the job failed on permissions or locks. Alert on job failure and on “oldest record age” metrics, not just job success.
  • Deletion doesn’t reach backups or replicas: primary data is gone but the same PII survives in a 30-day backup or a read replica. Treat backups as their own retention class with a defined propagation lag.
  • Lifecycle rules delete data under legal hold: object-lock or lifecycle automation bypasses the hold flag. Add an explicit hold check to the deletion path and test it with a fixture.
  • Third-party SaaS data is forgotten: analytics tools, support desks, and email providers hold copies outside your stores. Add each vendor’s retention/deletion controls to the inventory.
  • Table growth after purge: DELETE frees rows but not disk space. Follow purges with VACUUM/OPTIMIZE or partition drops (dropping a partition is faster and cheaper than row deletes).

Frequently Asked Questions

What is the difference between archiving and deleting data?

Archiving moves data to long-term, lower-cost storage for compliance or reference. Deleting permanently removes data so it cannot be recovered.

How do we handle backups under a retention policy?

Backups live on their own schedule. When primary data is deleted, the deletion should eventually propagate to backups according to the backup retention policy, or backups should be explicitly purged if required by law.

What happens if a legal hold conflicts with the retention policy?

Legal hold takes precedence. The affected data must be preserved beyond its normal retention period until the hold is released, and this exception must be documented.

How do we handle GDPR right to erasure requests?

When a user requests data deletion, identify all data stores containing their PII. Create a deletion ticket that tracks each store. Delete or anonymize data in the primary database, object storage, caches, search indexes, data warehouses, and backups. For backups, document that the data will be purged when the backup retention period expires (or initiate an expedited backup purge if required). Log the deletion with timestamp, scope, and approver. Provide confirmation to the user within 30 days. Test the erasure process quarterly.

What is data anonymization and when should we use it?

Data anonymization removes or obscures personally identifiable information while preserving the data structure for analytics. Techniques include: masking (replacing PII with fake data), hashing (one-way transformation), aggregation (grouping data to remove individual records), and pseudonymization (replacing direct identifiers with pseudonyms). Use anonymization when you need historical data for analytics but no longer need the PII. Document the anonymization method and verify it cannot be reversed.

How do we manage legal holds?

When a legal hold is issued, immediately suspend all deletion and purging for the affected data. Tag the data with a legal-hold flag in the system. Document the hold: scope, issuing authority, date, and expected duration. Notify all teams with access to the data. Monitor the hold status regularly. When the hold is released, document the release and resume normal retention schedules. Never auto-delete data with an active legal hold. Audit legal hold compliance annually.

How do we verify data has been deleted?

Once a purge job finishes, don't trust it — verify. Query for records older than the retention period (zero rows expected), count files under the S3 prefixes, and spot-check a sample of specific records. Log verification results. For compliance, have a second person verify the deletion. Keep deletion certificates and logs in an immutable bucket. Review deletion verification results monthly.

How do we handle data retention across multiple regions?

Regions bring their own rules: GDPR in the EU, CCPA in California, PDPA in Singapore. Build a retention matrix that ties each data type to the regions' rules. Where data crosses regions, the strictest period wins. Store data in the region where it was collected when possible. Document cross-region data flows and the retention rules that apply. Review regional requirements annually as laws change.

How do we handle data retention for machine learning models?

ML models and training data have unique retention needs. Retain model artifacts for the lifetime of the model in production plus 1 year for audit purposes. Training data should follow the data classification policy of the source data. Feature stores should expire features that are no longer used. Log model predictions for 90 days for debugging and bias auditing. Document which datasets were used to train each model version for reproducibility and compliance.

What is immutable storage and when do we need it?

Immutable storage (S3 Object Lock, Azure Immutable Blob) prevents objects from being deleted or overwritten for a specified retention period. Use it for: compliance requirements (SEC, FINRA, HIPAA), legal hold data, audit logs that must be tamper-proof, and financial records. Configure WORM (Write Once Read Many) mode at the bucket level. Document the immutability period and ensure it aligns with regulatory requirements. Test that deletion attempts are blocked.

Review the data retention policy annually and after any regulatory change. Update the retention matrix, purge schedules, and legal hold procedures, and train all team members on the updated policy.

Review the data retention policy annually and after any regulatory change. Update the retention matrix, purge schedules, and legal hold procedures. Train all team members on the updated policy.