Retention

This page covers how long personal data is kept and what happens when the time is up. It shows how to declare a retention period, what the three expiry actions do, how expired rows leave queries before they leave the table, and how to run, configure, pause and rehearse the retention worker. The code is the Shop sample.

Declare a period, an anchor and an action

Retention is part of the entity's classification. A parcel's address is needed until the parcel has arrived and any complaint is settled, so the shop deletes the row 30 days after its last change.

using Custodian;

namespace Shop;

/// <summary>
/// A parcel on its way to the customer. The address is only needed until the parcel arrives and any delivery complaint
/// is settled, so the row is deleted 30 days after its last change, which is the delivery.
/// </summary>
[PersonalDataEntity(
    Purpose = Purposes.Fulfilment,
    LawfulBasis = LawfulBasis.Contract,
    Retention = "P30D",
    Anchor = RetentionAnchor.LastActivity,
    OnExpiry = ExpiryAction.Delete)]
public sealed class Shipment
{
    public int Id { get; set; }

    public int OrderId { get; set; }

    [DataSubject]
    public Guid RecipientSubjectId { get; set; }

    [PersonalData(DataCategory.Identity)]
    public string RecipientName { get; set; } = "";

    /// <summary>A home address. Encrypted, so erasing the customer also erases it from backups.</summary>
    [PersonalData(DataCategory.Location), Encrypted]
    public string DeliveryAddress { get; set; } = "";

    public string Carrier { get; set; } = "";

    public DateTimeOffset? DeliveredAt { get; set; }
}

Retention is an ISO 8601 duration. Anchor says what the period counts from:

OnExpiry says what happens to the row. An order must be kept for seven years for bookkeeping. After that the shop still wants its sales figures, so it blanks the personal fields and keeps the row.

[PersonalDataEntity(
    Purpose = Purposes.Billing,
    LawfulBasis = LawfulBasis.LegalObligation,
    Retention = "P7Y",
    Anchor = RetentionAnchor.CreatedAt,
    OnExpiry = ExpiryAction.Anonymise)]

Custodian stamps every personal row with its expiry when the row is saved. An entity without a retention period that Custodian can resolve stops the application at startup. Classifying personal data covers the attributes in full.

Expired rows disappear from queries at once

A row whose retention has ended is hidden from EF Core queries, and from Dapper queries made with QueryPersonalAsync, from that moment. It does not wait for the worker.

[Theory, EachProvider]
public async Task A_parcel_delivered_more_than_thirty_days_ago_is_hidden_before_it_is_purged(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    var astrid = await shops.Nordic.SignUp(Customers.Astrid());
    await shops.Nordic.DeliverParcelTo(astrid, deliveredAt: shops.DaysAgo(31));
    var recent = await shops.Nordic.DeliverParcelTo(astrid, deliveredAt: shops.DaysAgo(29));

    var parcels = await shops.Nordic.As(Staff.Warehouse).For(Purposes.Fulfilment).Query(db => db.Shipments.Select(s => s.Id));

    Assert.Equal([recent.Id], parcels);
}

The row is still in the table until the next retention run, and raw SQL can still see it. See A_hidden_parcel_stays_in_the_table_until_the_retention_run. The Clinic sample shows the same for appointments in An_appointment_disappears_from_the_front_desk_once_the_medical_record_retention_has_passed.

The retention worker

The worker is a hosted service that applies the expiry actions. Turn it on when you register Custodian.

o.Retention.FromConfiguration(configuration.GetSection("Retention"));
o.Retention.RunWorker(every: TimeSpan.FromHours(1));

The worker connects with the Retention database role. It works through one tenant at a time and audits what it did per entity and purpose, as counts. It acts on a row once the row has been expired for longer than the grace window, which is 24 hours unless you change it with o.Retention.GraceWindow(...).

If you schedule jobs with something else, leave RunWorker out and call IRetentionRunner from your own job. One call is one pass. The samples' tests run a pass the same way.

public Task<RetentionReport> RunRetention(bool? dryRun = null) =>
    InScope(services => services.GetRequiredService<IRetentionRunner>().RunAsync(dryRun, Cancellation));

The returned RetentionReport lists the rows per entity, purpose and action, the rows skipped for a legal hold, and whether the row limit stopped the pass.

Change retention without a release

o.Retention.FromConfiguration(...) names a configuration section that overrides what the attributes declare. A DPO can then shorten or lengthen a period, or change the anchor or the action, without a new build. The section is keyed by entity, then Purposes, then the purpose. The keys under it are Retention, Anchor and OnExpiry. This environment variable keeps parcels for 60 days:

export Retention__Shipment__Purposes__fulfilment__Retention=P60D

An override for a purpose the entity does not declare is an error. The Shop sample ships an empty Retention section, so its attributes apply as written.

A legal hold makes the worker skip rows until the hold is lifted. Place one through ILegalHolds.

public Task<LegalHold> PlaceLegalHoldOn(ShopCustomer customer) =>
    _work.Use<ILegalHolds, LegalHold>(holds =>
        holds.PlaceAsync(new LegalHoldScope.ForSubject(customer.Subject), "Tax audit 2026", Cancellation));

A hold covers one data subject (ForSubject), every row of one entity (ForEntity), or the rows whose retention falls in a date range (ForDateRange). The reason is stored as you give it, so it must not contain personal data. LiftAsync ends a hold and GetActiveAsync lists the holds in force.

[Theory, EachProvider]
public async Task A_legal_hold_keeps_the_retention_run_from_deleting_a_customers_parcels(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    var astrid = await shops.Nordic.SignUp(Customers.Astrid());
    var held = await shops.Nordic.DeliverParcelTo(astrid, deliveredAt: shops.DaysAgo(45));
    await shops.Nordic.PrivacyOffice.PlaceLegalHoldOn(astrid);

    var report = await shops.RunRetention();

    Assert.Equal([held.Id], await shops.Nordic.RawSql<int>("SELECT id FROM shipments"));
    Assert.Equal(1, report.HeldRows);
}

Held rows are counted in the report and left exactly as they were. The Clinic sample shows that the encrypted reason for a held patient's visit stays in A_legal_hold_on_a_patient_keeps_the_expired_reason_for_her_visit_untouched. A hold also blocks erasure. EraseAsync throws LegalHoldException while a hold covers the subject's data.

Dry runs

A dry run reports what a pass would do and changes nothing. Use it before you turn the worker on, and after you change a retention period.

[Theory, EachProvider]
public async Task A_dry_run_reports_the_parcels_it_would_delete(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider);
    var astrid = await shops.Nordic.SignUp(Customers.Astrid());
    await shops.Nordic.DeliverParcelTo(astrid, deliveredAt: shops.DaysAgo(45));

    var report = await shops.RunRetention(dryRun: true);

    Assert.True(report.DryRun);
    Assert.Equal(new RetentionActionCount(nameof(Shipment), Purposes.Fulfilment, ExpiryAction.Delete, Rows: 1), Assert.Single(report.Actions));
}

The table is untouched afterwards. See A_dry_run_deletes_nothing. Pass dryRun: true for a single pass, or call o.Retention.DryRun() to make every pass a dry run. The command-line tool offers the same report from a terminal.

Row limits

A wrong retention period could empty a table. MaxRowsPerRun caps how many rows one pass may change. The default is 100,000.

[Theory, EachProvider]
public async Task The_retention_run_stops_at_the_maximum_rows_per_run(DatabaseProvider provider)
{
    await using var shops = await servers.OpenShop(provider, o => o.Retention.MaxRowsPerRun(2));
    var astrid = await shops.Nordic.SignUp(Customers.Astrid());
    await shops.Nordic.DeliverParcelTo(astrid, deliveredAt: shops.DaysAgo(45));
    await shops.Nordic.DeliverParcelTo(astrid, deliveredAt: shops.DaysAgo(45));
    await shops.Nordic.DeliverParcelTo(astrid, deliveredAt: shops.DaysAgo(45));

    var report = await shops.RunRetention();

    Assert.True(report.LimitReached);
    Assert.Single(await shops.Nordic.RawSql<int>("SELECT id FROM shipments"));
}

LimitReached tells you that rows were left for the next pass. The worker also changes rows in small batches, each in its own transaction, to avoid lock escalation. o.Retention.BatchSize(...) sets the batch size. The default is 500.

Next