Nov 23, 20266 min read

Implement a Data Retention Policy in Your Backend

How to turn a retention policy into code: a rule per data class, batched deletes that do not lock tables, legal holds, cleanup of files and derived data, and a deletion log, built as a scheduled job with Encore.

Illustration for Implement a Data Retention Policy in Your Backend

Keeping data forever is the default, and it becomes a liability when a customer asks what you hold, an auditor asks for how long, or a breach exposes records from years ago. A retention policy sets how long each kind of data lives, and only a job enforces it.

This guide turns the policy into code: rules as data, batched deletes, exceptions for legal holds and a log of what was removed.

What does a retention job need?

PartPatternWhat goes wrong without it
RulesOne entry per data class: table, column, daysPolicy lives in a document and drifts from reality
DeletesSmall batches with a short pauseLong locks and replication lag
Legal holdsA flag the job always checksDeleting data under investigation
CopiesA step per file store, index and cacheData survives in the places nobody looked
LogCounts per rule and run, no personal dataNo evidence the policy runs
Time seriesPartitions dropped by monthHuge deletes and table bloat

Why define retention in code?

Storage limitation is a principle in GDPR Article 5(1)(e): personal data should be kept in an identifiable form no longer than necessary for the purpose. Other regimes and contracts set their own periods. Whatever the source, a number in a policy document does nothing until a job reads it, so keep the rules in a table or a list in the service, reviewed like any other code change, and have the job log what each rule removed.

How do you delete in batches?

A single DELETE over a year of rows holds locks, produces a large write-ahead log burst and leaves dead tuples for vacuum to clean up. Delete a few thousand rows at a time instead, and repeat until a batch returns fewer rows than the limit:

DELETE FROM login_events WHERE ctid IN ( SELECT ctid FROM login_events WHERE created_at < now() - make_interval(days => 90) LIMIT 5000 );

For tables that only grow by time, such as events and audit logs, declarative partitioning is the better design: one partition per month, and retention becomes dropping the oldest partition, which is instant and leaves nothing to vacuum.

How do you handle holds and derived data?

A legal hold is a flag on the account or case, and every rule that touches user data must exclude held rows. The job should also clean what the rows pointed at: files in object storage, entries in a search index, cached copies and rows in analytics tables. Backups are different. They expire on their own schedule, so set the backup retention to match the policy and state it in the policy text.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and a retention service is a cron job that calls a private API endpoint, next to the Postgres database it cleans, declared in code. Cron jobs are managed by the Encore platform and do not run locally or in preview environments, so the endpoint is what you test.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create retention --example=hello-world$ cd retention && mkdir -p retention/migrations

The job

// retention/retention.go package retention import ( "context" "fmt" "time" "encore.dev/cron" "encore.dev/rlog" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("retention", sqldb.DatabaseConfig{ Migrations: "./migrations", }) // The policy as data. Identifiers come from this trusted list, never from input. type rule struct { Table string Column string KeepDays int // HoldClause excludes rows under a legal hold, for example // "AND NOT EXISTS (SELECT 1 FROM legal_holds h WHERE h.account_id = t.account_id)". HoldClause string } var rules = []rule{ { Table: "sessions", Column: "expires_at", KeepDays: 30, HoldClause: "AND NOT EXISTS (SELECT 1 FROM legal_holds h WHERE h.account_id = t.account_id)", }, { Table: "login_events", Column: "created_at", KeepDays: 90, HoldClause: "AND NOT EXISTS (SELECT 1 FROM legal_holds h WHERE h.account_id = t.account_id)", }, { Table: "support_messages", Column: "created_at", KeepDays: 365, HoldClause: "AND NOT EXISTS (SELECT 1 FROM legal_holds h WHERE h.account_id = t.account_id)", }, } const batchSize = 5000 // Run enforces every rule. It is safe to call repeatedly: a second run finds nothing to delete. // //encore:api private method=POST path=/retention/run func Run(ctx context.Context) error { for _, r := range rules { total, err := enforce(ctx, r) if err != nil { return fmt.Errorf("rule %s: %w", r.Table, err) } // Log counts only, never the deleted data. rlog.Info("retention rule applied", "table", r.Table, "deleted", total) if _, err := db.Exec(ctx, ` INSERT INTO retention_log (table_name, deleted_rows) VALUES ($1, $2)`, r.Table, total); err != nil { return err } } return nil } func enforce(ctx context.Context, r rule) (int64, error) { query := fmt.Sprintf(` DELETE FROM %[1]s WHERE ctid IN ( SELECT t.ctid FROM %[1]s t WHERE t.%[2]s < now() - make_interval(days => $1) %[3]s LIMIT $2 )`, r.Table, r.Column, r.HoldClause) var total int64 for { res, err := db.Exec(ctx, query, r.KeepDays, batchSize) if err != nil { return total, err } n := res.RowsAffected() total += n if n < batchSize { return total, nil } time.Sleep(200 * time.Millisecond) // let replication and vacuum keep up } } // Managed by the Encore platform in deployed environments. It does not run // under `encore run`, so call Run directly when testing locally. var _ = cron.NewJob("retention", cron.JobConfig{ Title: "Enforce data retention rules", Schedule: "30 3 * * *", Endpoint: Run, })

The migration adds the retention_log, legal_holds and data tables the rules refer to. encore run starts a local Postgres and applies it, so a test can insert rows older and newer than the limit, call Run and check that only the old, unheld rows disappear. On deploy, the database runs on RDS or Cloud SQL as the AWS infrastructure docs describe, so the data stays in your own account.

A coding agent that adds a new table to the service adds its rule to the list in the same change, and the test fails if a table with personal data has no rule.

Best fit: Teams that must show a retention policy is enforced, and want the rules, the job and the database in one repository.

Things to decide early

  • Owner of the policy. Name who approves a retention period change, and record it in the rule's commit.
  • Soft versus hard delete. Anonymizing a row can satisfy a period while keeping aggregates, but only when no identifier remains.
  • Object storage. Prefer bucket lifecycle rules for files, so deletion does not depend on the job running.
  • Monitoring. Alert when a run deletes zero rows for a table that should have old data, or far more than usual.

Frequently asked questions

How do you implement a data retention policy in a database?

Write the policy as data: for each table, a timestamp column and a number of days to keep. A scheduled job deletes rows older than the limit in small batches, skips rows under a legal hold and logs how many rows it removed, so the policy is enforced the same way every day.

How do you delete old rows from a large Postgres table safely?

Delete in batches of a few thousand rows with a short pause, so each statement is quick and holds locks briefly. For time-series tables, partition by month and drop whole partitions, which is much cheaper than deleting rows and leaves no dead tuples to vacuum.

Does deleting rows delete the data everywhere?

No. Copies remain in backups, search indexes, caches, object storage, analytics tables and logs until each is handled. A retention job needs a step for every place the data was copied, and backups should expire on their own schedule.

How do you run a retention job with Encore?

With Encore, declare a daily cron job that calls a private endpoint, which runs batched deletes against a Postgres database declared in the same service. Cron jobs are managed by the Encore platform and do not run locally, so test the endpoint directly.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders