
Deletion is a state transition, not a DELETE statement
Treats data lifecycle as database state: snapshot, minimize, retain, and erase, so operational history survives without keeping the raw PII.
Series: Build your AI app (5 articles)
- …
- 5Deletion is a state transition, not a DELETE statement This article
As children, we love heroes, as adults, we understand villains.
When a database table has a foreign key cascade, deletion looks deceptively simple:
DELETE FROM accountsWHERE id = '...';That statement may remove the account row. It may remove API keys, generations, credit records, webhook endpoints, memberships, and other dependent data. But it does not answer the difficult questions:
- Which operational evidence must be preserved?
- Which raw records can be deleted immediately?
- Which aggregates should survive?
- When must an archive be removed?
- What happens if deletion fails halfway through?
- How do we prove that the system did not accidentally retain identifiable data?
At BabySea, account deletion and retention are implemented as database-controlled lifecycle workflows. Raw operational data is deleted with purpose-specific rules. Selected values are converted into account-level aggregates before those rows disappear. Platform-wide reporting is preserved separately, while individual account records are removed.
This is not a claim that a database migration alone makes BabySea legally compliant. EU data protection obligations depend on purpose, legal basis, transparency, processor arrangements, retention periods, access controls, correction rights, backup handling, and organizational controls. The engineering goal is to make the lifecycle explicit and enforceable.
The lifecycle is a set of different data classes
Not every record is deleted for the same reason.
At BabySea, the lifecycle includes:
- Generated media and generation records
- API request logs
- Webhook delivery logs
- Credit ledger entries
- Activity history
- Daily dashboard snapshots
- Account-deletion audit records
- Platform-wide tombstones
These records have different lifetimes.
A prompt or output file may have a short operational retention period. A credit ledger entry may need to remain for financial reconciliation. A webhook log can be useful for diagnostics but does not need to retain the entire payload indefinitely. A daily request total can remain useful after every raw request row has been removed.
The system therefore keeps
purpose and retention separate from the deletion mechanism.Pre-delete snapshots preserve counts, not records
One of the first reliability problems in retention systems is that aggregate data disappears whenever source rows disappear.
For example:
3,000 API request rows are deleted -> the account's daily request dashboard becomes incorrectThe solution is to create the aggregate before deleting the source row.
BabySea uses
BEFORE DELETE triggers for source records. A trigger reads the old row, converts it into a one-day aggregate, and merges that aggregate into the account's daily snapshot table.The snapshot operation is additive:
existing daily request count: 42deleted request row: 1 POST requestnew daily request count: 43The same pattern is used for:
- API requests
- Webhook deliveries
- Generations
- Credit movements
- Activity events
A single migration helper recursively merges JSONB numeric values:
CREATE OR REPLACE FUNCTION public.jsonb_add_counts(a JSONB, b JSONB)RETURNS JSONBSET search_path = ''LANGUAGE plpgsql IMMUTABLEAS $$DECLARE key TEXT; result JSONB := COALESCE(a, '{}'::JSONB);BEGIN FOR key IN SELECT jsonb_object_keys(COALESCE(b, '{}'::JSONB)) LOOP IF jsonb_typeof(b -> key) = 'number' THEN result := jsonb_set( result, ARRAY[key], to_jsonb( COALESCE((result ->> key)::NUMERIC, 0) + (b ->> key)::NUMERIC ) ); ELSIF jsonb_typeof(b -> key) = 'object' THEN result := jsonb_set( result, ARRAY[key], public.jsonb_add_counts(result -> key, b -> key) ); END IF; END LOOP;
RETURN result;END;$$;The helper does not copy entire objects. It merges numeric counters.
A request snapshot might contain:
{ "POST /v1/generate": { "total": 25, "success": 22, "client_error": 2, "server_error": 1 }}A generation snapshot might contain:
{ "bfl/flux-schnell": { "total": 18, "succeeded": 16, "failed": 2 }}These structures preserve a useful daily view while avoiding the original prompts, URLs, response payloads, headers, and request bodies.
Snapshot rows use account ownership and constraints
Each snapshot is account-scoped:
table: account_daily_generation_stats
id UUID, primary keyaccount_id UUID, not null, references accounts(id), cascade on account removalday DATE, not nulltotal_generations INTEGER, default 0succeeded_generations INTEGER, default 0failed_generations INTEGER, default 0canceled_generations INTEGER, default 0failover_generations INTEGER, default 0perf_count INTEGER, default 0perf_total_time_sum NUMERIC, default 0perf_predict_time_sum NUMERIC, default 0total_output_file_assets INTEGER, default 0by_model JSONB, default empty objectby_provider JSONB, default empty objectby_error_code JSONB, default empty objectcreated_at TIMESTAMPTZ, default now
constraint: UNIQUE(account_id, day)The
UNIQUE(account_id, day) constraint is important.It means every source row can add itself to exactly one daily row:
upsert into account_daily_generation_stats key: (account_id, day) new row: total = 1, succeeded = 1 or 0, failed = 1 or 0 on conflict: add the new counters to the existing totalsThis makes trigger execution and concurrent deletion safe.
The snapshot table is also protected by row-level security:
row-level security: enabled on account_daily_generation_stats
policy ACCOUNT_CAN_READ_GENERATION_STATS applies to: read access, authenticated role condition: auth.uid() = account_id OR has_role_on_account(account_id)The account owner or an authorized team role can read the snapshot. It is not a public reporting table.
Two deletion paths use the snapshot mechanism
BabySea has two classes of deletion.
1. Resource deletion
A customer can delete an API key or webhook endpoint. The child logs should not disappear silently because the dashboard needs daily accounting.
Before deleting the parent resource, a
BEFORE DELETE trigger can aggregate all matching child rows.For a webhook:
for each distinct day in this webhook's delivery logs: upsert into account_daily_webhook_stats, key (account_id, day) total_deliveries = logs that day success_deliveries = logs that day with status 200-299 failed_deliveries = logs that day outside 200-299 total_attempts = 0 on conflict: add the counts to the existing totalsAfter the snapshot runs, the cascade can delete the raw logs.
This has an important guard:
if the owning account no longer exists: return the old row and skip the snapshotThe account is already being cascade-deleted in another path. The resource snapshot should not create misleading activity when the account itself no longer exists.
2. Scheduled retention deletion
Scheduled retention is different. The source row is deleted directly, so there is a per-row
BEFORE DELETE trigger:CREATE TRIGGER trg_snapshot_credit_ledger_rowBEFORE DELETE ON public.credit_ledgerFOR EACH ROWEXECUTE FUNCTION public.snapshot_credit_ledger_row();For each row:
function snapshot_credit_ledger_row()
1. if the owning account no longer exists -> return the old row 2. day = date of the old row's created_at 3. upsert into account_daily_credit_stats, key (account_id, day) total_reserved = amount if type is reserve, else 0 total_charged = amount if type is charge, else 0 total_refunded = amount if type is refund, else 0 total_added = amount if type is add, else 0 balance_after = old row's balance_after on conflict: add each total to the existing totalThe trigger then allows the deletion to proceed.
This makes retention additive: every source row contributes once before it disappears.
Retention is category-specific
BabySea defines retention for several independent categories:
- Stored generation output files
- Generation records
- API request logs
- Webhook event logs
- Activity history
- Credit ledger history
Stored output files have plan-based hourly retention, stored as a
retention_hours value on each plan:starter-monthly 12 hourspro-monthly 24 hoursscale-monthly 120 hoursenterprise-monthly 168 hoursThe storage cleanup query can resolve the account's active plan:
function get_account_retention_hours(account_id) join: plans -> subscription_items -> subscriptions filter: subscription belongs to the account, is active, and the plan has a retention_hours value return: that value, or 1 hour when no plan matches runs as: SECURITY DEFINER, locked search_pathDatabase record retention is separate:
expired file asset records
per account: resolve retention days (default for the free plan: 1 day) select: id, account_id, generation_id, created_at where: created_at is older than now minus the account's retention days order: oldest first limit: 500 per batchThis is an application of the principle that retention is part of the data model.
A credit pack subscription, a free account, a monthly plan, and an enterprise contract should not necessarily have one universal rule.
Batch deletion preserves transaction boundaries
The retention worker can select expired records, archive them if required, and call a single SQL function to delete them:
function delete_expired_records(category, ids)
logs_generation_records -> remove matching rows from file_assets logs_api_requests -> remove matching rows from api_key_log logs_webhook_events -> remove matching rows from webhook_log logs_activity -> remove matching rows from activity_log logs_credit_ledger -> remove matching rows from credit_ledger anything else -> raise "Unknown retention category"
returns: number of rows removed runs as: SECURITY DEFINER, locked search_pathBatch deletion matters for scale.
A trigger runs for every row. That is acceptable for bounded batches. It is also a reason to avoid unbounded global deletes: each row may execute snapshot queries and JSONB merges.
A safe retention worker should:
- Select a bounded number of records.
- Re-read them at deletion time.
- Aggregate before deleting.
- Limit the batch size.
- Record partial progress.
- Retry safely.
- Stop on database errors.
The database should own the snapshot invariant. The cron should only discover and submit work.
Archive data is not automatically a legal deletion
The migration creates a private storage bucket for retention archives:
bucket: retention-archivepublic: falsefile size limit: 100 MB (104857600 bytes)allowed mime types: application/jsonThe bucket is service-role only:
policy SERVICE_ROLE_CAN_ACCESS_RETENTION_ARCHIVE applies to: all operations on storage objects, service_role only condition: bucket_id = 'retention-archive'That is a useful security boundary. An archive should not be accessible through normal application roles.
But a private archive is still data.
If an archive contains prompts, source payloads, email addresses, URLs, or file references, it remains inside the deletion and retention scope. Creating an archive does not convert a record into an aggregate or make it anonymous.
A production archive needs at least:
- A documented purpose
- An explicit retention period
- Encryption
- Restricted service-role access
- Object-level lifecycle policy
- Immutable audit logs for access
- Scheduled purge
- Backup handling
- Data-subject and deletion routing
An application should not say "we deleted the database row" while an export, object store, or backup copy continues to retain the same information indefinitely.
Account deletion uses a three-phase database workflow
When an account is deleted, BabySea preserves a limited set of platform reporting values. The deletion trigger executes inside the account deletion transaction.
Phase 1: capture financial totals
Before the ledger is flushed, it reads:
- Final account balance
- Total charged amounts
- Total purchased credits
- Subscription-added credits
write one row to admin_financial_tombstones account_id = the deleted account deleted_at = now final_balance = current credit balance, or 0 total_charged = sum of absolute amounts of charge entries, or 0 total_purchased = 0 total_subscription_added = 0The result is a platform-wide financial summary rather than a copy of every ledger row.
Phase 2: flush raw rows through snapshot triggers
While the account still exists, the trigger explicitly deletes the remaining raw logs:
remove, in order, for the account: 1. API key logs (through the account's API keys) 2. webhook logs (through the account's webhooks) 3. file assets 4. credit ledger entriesEvery delete can invoke a
BEFORE DELETE snapshot trigger.For example:
CREATE TRIGGER trg_snapshot_credit_ledger_rowBEFORE DELETE ON public.credit_ledgerFOR EACH ROWEXECUTE FUNCTION public.snapshot_credit_ledger_row();The account still exists during this phase:
guard: if the owning account no longer exists -> return the old rowThat guard prevents snapshot triggers from creating records after the account itself has disappeared.
Phase 3: copy daily snapshots into standalone tombstones
The account's daily rows are copied into tables with no foreign key:
copy every row of account_daily_generation_stats for this accountinto admin_tombstone_daily_generation_stats(all columns, unchanged: counts, perf sums, by_model, by_provider, by_error_code, created_at)The destination table has no foreign key:
table: admin_tombstone_daily_generation_stats
same columns and defaults as account_daily_generation_statsaccount_id is a plain UUID, not nullno reference to accountsThe result is consistent in Postgres:
- The account exists at the start of the deletion.
- Financial values are captured.
- Raw rows are aggregated and removed.
- Daily snapshots are copied into standalone reporting tables.
- The account and dependent account-scoped rows are deleted afterward.
If any phase fails, the transaction does not finish deleting the account.
Account-deletion audit records are also retained data
Account deletion also creates an append-oriented audit record:
table: account_deletion_log
id UUID, primary keyaccount_id UUID, not nullemail_hash TEXTaccount_type TEXT, not nulldeleted_by UUID, not nulldeletion_reason TEXT, not nullsummary JSONB, not nulldeleted_at TIMESTAMPTZ, default nowretention_expires_at TIMESTAMPTZ, default now + 7 yearsIts purpose is not to restore the account. It records that a deletion occurred and retains a limited operational summary:
- Account creation and deletion timestamps
- Membership count
- Credit totals
- Provider and model counts
- Successful generation count
- API key totals
- Webhook totals
- Consent and bug-report counts
- Custom-domain count
- Order totals
An email is stored only as a SHA-256 hex digest. That is less direct than plaintext, but it is not automatically pseudonymous or anonymous.
A deterministic hash can be:
- Re-identifiable through known email lists
- Used for record correlation
- Sensitive enough to require access controls
- Subject to the same transparency and retention obligations
This is why the deletion log is restricted, append-oriented, and assigned an expiry.
Postgres prevents updates to its audit records:
CREATE OR REPLACE FUNCTION public.prevent_audit_log_mutation()RETURNS TRIGGERSET search_path = ''LANGUAGE plpgsql AS $$BEGIN RAISE EXCEPTION 'account_deletion_log is append-only. UPDATE is not permitted.';END;$$;Only the normal retention purge can delete expired rows.
EU privacy design principles
For an EU-facing product, a deletion architecture should implement at least these principles:
Data minimization
Before copying or aggregating data, ask:
- Is this value needed?
- Is a count sufficient?
- Can we remove a dimension?
- Can we reduce it to a day or month?
- Can we remove a provider or API-key identifier?
- Is a stable hash necessary?
A conservative implementation preserves the minimum output required for each purpose.
Purpose limitation
An account-deletion audit table and a platform analytics table should not silently become a generic data store.
Every retained field needs:
- A purpose
- A legal or contractual justification
- A retention period
- A user-facing explanation
- A deletion and access process
- Restricted access
Storage limitation
The database, Supabase Storage, retention archive, application logs, provider systems, backups, and downstream analytics need to be considered independently.
A database row can be deleted while a backup or archive remains. The architecture should state the behavior of each location and apply the legally appropriate retention and erasure policy.
Security
The important safeguards include:
-
SECURITY DEFINERfunctions with a lockedsearch_path
- Row-level security for account-readable snapshots
- Service-role-only mutation grants
- Private storage buckets
- Restricted tombstone access
- Encryption at rest and in transit
- Clear service-role deployment boundaries
- Logged access to sensitive audit records
Verifiability
A deletion system should expose evidence:
- Which deletion was initiated
- When the request was accepted
- Which stages completed
- Whether storage cleanup completed
- Which retry or partial state exists
- What was deleted
- What remains
- When remaining data expires
The same data should be usable for support and verification without exposing the deleted person's raw activity to administrators.
The hard cases
Backups
Postgres backups do not prove a specific account is immediately erased by the backup restore process.
BabySea should define whether backups:
- Overwrite or expire normally
- Contain encrypted backups
- Are excluded from active processing
- Are isolated until expiry
- Support future restoration without unintended account revival
Backups are a retention and recovery concern, not simply a deleted-row problem.
Provider systems
Deleting BabySea's row does not necessarily erase a provider's copy of a prompt or artifact. Provider terms and regional controls must be checked, and provider-specific deletion or retention interfaces must be mapped separately.
The control plane should distinguish:
- BabySea raw records deleted
- BabySea output files deleted
- Provider-side copies deleted or retained
- Downstream analytics deleted or aggregated
- Archives deleted or retained
A system is not well described by "deleted everywhere" unless it can trace every data copy.
Analytics and research
A platform can retain aggregate information after account deletion. It should not continue to copy account-specific dimensions unless each one is justified.
Platform tombstones should be designed with:
- No joins to living accounts
- No recoverable name or email fields
- Restricted admin access
- Explicit retention
- Aggregated numbers
- Independent deletion controls
Data subject requests
EU rights are broader than SQL deletion.
The system may need to support:
- Access
- Rectification
- Erasure
- Restriction
- Portability
- Objection
- Automated-decision restrictions
A row deleted from the product database may already have entered an archive or derived system. A deletion request should trigger an inventory process, not just a single cascade.
The actual invariant
The invariant in this architecture is:
Raw data is removable, while deliberately retained evidence is first converted into purpose-limited structures.
That leads to a clear execution boundary:
Before retention deletion -> snapshot source row -> update account-level aggregate -> delete raw row
Before account deletion -> capture approved financial evidence -> delete and aggregate raw logs -> copy approved platform aggregates -> delete account and account-scoped records -> erase or scrub required PII -> clean external storage -> initiate provider-specific cleanupThe database does not decide that every record is "legal." It decides that the lifecycle steps execute consistently inside the database transaction.
That distinction is the difference between a delete statement and a deletion system.
Closing
Deletion is an engineering state machine.
It spans:
- Database rows
- Storage objects
- Daily snapshot tables
- Tombstones
- Audit logs
- Retention archives
- Provider systems
- Backups
- External analytics
- Regional infrastructure
BabySea's SQL implements lifecycle-aware deletion: selected raw records are aggregated before removal, retention is managed by data category, and limited deletion and platform records are kept for defined operational purposes. I don't describe those retained records as automatically anonymous; some still contain identifiers or pseudonymous data and remain subject to access and retention controls. The database enforces the lifecycle mechanics, while legal compliance depends on the full data inventory, documented purposes and legal basis, applicable retention periods, and handling across storage, backups, providers, and downstream systems.
Series: Build your AI app (5 articles)
- …
- 5Deletion is a state transition, not a DELETE statement This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article