Writing Account Deletion Code With LLMs in November 2026: Find Every Copy of the Data, Decide Soft or Hard Delete Per Table, and Make the Job Resumable
"Delete my account" sounds like one line of code. Ask an LLM to implement it and you will often get exactly that: a handler that runs DELETE FROM users WHERE id = ? and returns 200. Then the surprises start. The delete fails because of a foreign key, or it succeeds and cascades through tables you wanted to keep, like invoices you are legally required to retain. The user's files stay in object storage. Their email stays in your mailing list provider. Their name stays in search indexes, analytics events, and last night's backup. And if the request times out halfway, you are left with a half-deleted account that nobody can log into or clean up.
This guide covers how to get account deletion code out of an AI coding assistant that actually removes what it should, keeps what it must, and finishes reliably. The short version: inventory every place the data lives before writing code, decide per table whether to hard delete, anonymize, or keep, run the deletion as a resumable background job, and test it against a fully populated account.
Shredding one page is easy. Account deletion means finding every copy first. Image: Paper shredder - detail-9831 by Raimond Spekking, CC BY-SA 4.0, via Wikimedia Commons.
Why the one-line version fails
An LLM only sees the code you show it. If you paste the users model and ask for a delete endpoint, it has no way to know about the S3 bucket for avatars, the Stripe customer record, the support tool, or the analytics warehouse. It also does not know your legal obligations. So it fills the gap with the simplest assumption: the user is one row, and deleting that row deletes the user.
In a real application, a user's data is spread across:
- Your primary database: the user row, plus every table with a
user_idcolumn, plus rows that mention the user without a foreign key (comments, mentions, free-text notes). - File storage: avatars, uploads, generated exports, attachments.
- Caches and search indexes: Redis keys, Elasticsearch or similar documents, CDN-cached profile pages.
- Third-party services: payment provider, email delivery and newsletter tools, CRM, support desk, error tracking that captured user details.
- Logs, analytics, and backups: which usually cannot be edited row by row and need a retention policy instead.
None of that is visible from the user model. You have to supply it.
Step 1: Build a data inventory before asking for code
Start with a list, not a prompt. A quick way to get a first draft of the database part is to search your schema for user references:
-- PostgreSQL: find columns that look like user references
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = 'public'
AND (column_name LIKE '%user_id%' OR column_name IN ('email', 'owner_id', 'created_by'))
ORDER BY table_name;
You can ask the LLM to help here, and it is good at it: paste your migrations or schema file and ask it to list every table and column that holds or points to personal data, including ones without a foreign key. Then check the list yourself, and add the systems outside the database by hand: storage buckets, third-party accounts, search indexes. Ask the people who run support and marketing what tools they put customer data into. Those are the ones engineers forget.
Write the result down as a table in the repo, for example docs/data-inventory.md. It becomes the input to every later prompt.
Step 2: Decide what happens to each item
"Delete everything" is rarely correct. For each row in the inventory, pick one of four actions:
- Hard delete: remove the data completely. Right for profile details, uploaded files, sessions, API tokens, preferences.
- Anonymize: keep the record but strip what identifies the person. Right for things other users depend on, like comments in a shared thread or orders that feed your revenue reports. Replace the author with a placeholder such as "Deleted user" and clear name, email, and IP fields.
- Retain for a fixed period: keep it because a law or contract requires it, such as invoices and tax records, then delete on schedule. The exact period depends on your jurisdiction, so get that answer from someone qualified rather than from the model.
- Expire naturally: logs and backups that age out under an existing retention window. Document the window so you can tell the user honestly when the last copy disappears.
Add this decision as a column in your inventory. When you prompt the model, you are now giving it a specification, not a wish.
Step 3: Separate "request" from "deletion"
The endpoint the user hits should not do the deletion. It should record the request and return quickly. A good shape:
- Re-authenticate the user (ask for their password or a fresh login) before accepting the request, so a stolen session cannot wipe an account.
- Create a
deletion_requestsrow with the user ID, the time, and a status. - Immediately disable the account: revoke sessions and API tokens, block login, stop outgoing emails. From the user's point of view, the account is gone now.
- Optionally schedule the real deletion after a short grace period, so an accidental or malicious request can be undone. If you offer this, say so clearly in the UI.
A background worker then picks up due requests and does the slow, failure-prone work.
Erase what you must, keep what the law requires, and make the job safe to run twice. Image: Pink Pearl eraser by ZooFari, Public domain, via Wikimedia Commons.
Step 4: Make the deletion job resumable
Deletion touches many systems, and any of them can fail: a third-party API returns 500, the worker is restarted during a deploy, a storage listing times out. The job must be able to run again from the start and finish the work without errors or double effects. Concretely:
- Break it into named steps, one per inventory item:
delete_uploads,anonymize_comments,delete_payment_customer, and so on. Record each step's completion on the request row or a child table. - Make every step idempotent. Deleting a file that is already gone, or a Stripe customer that no longer exists, should count as success. Ask the model explicitly to treat "not found" as done.
- Delete in batches. A user with 200,000 events should not produce one giant transaction that locks a table. Delete a few thousand rows at a time in a loop until none remain.
- Do the database user row last. If you delete it first, you lose the IDs and email you need to find data in other systems.
- Retry with a limit, then alert. If a step keeps failing, mark the request as stuck and notify a human. A silent failure means you told a user their data was deleted when it was not.
Here is the skeleton worth asking for, in Python-flavored pseudocode:
STEPS = [
("revoke_tokens", revoke_tokens),
("delete_uploads", delete_uploads),
("delete_search_docs", delete_search_docs),
("delete_payment_customer", delete_payment_customer),
("anonymize_comments", anonymize_comments),
("delete_owned_rows", delete_owned_rows), # batched
("delete_user_row", delete_user_row), # always last
]
def run_deletion(request):
for name, step in STEPS:
if request.step_done(name):
continue
step(request.user_id) # must treat "already gone" as success
request.mark_step_done(name)
request.mark_complete()
Step 5: Watch for what the model gets wrong
When reviewing the generated code, check these specifically:
- Database cascades. Models often add
ON DELETE CASCADEto make a foreign key error go away. Read every cascade and confirm it matches your decision table. A cascade from users to invoices can quietly destroy records you must keep. - Soft delete flags that hide but keep. A
deleted_atcolumn is fine for the grace period. It is not deletion. Make sure the job eventually removes or anonymizes the row. - Anonymization that is not anonymous. Replacing a name with a hash of the email can still identify someone, because anyone with the email can compute the same hash. Use a fixed placeholder or a random value.
- Shared resources. If a user belongs to a team or organization, deleting their account must not delete the team's data. Decide whether ownership transfers to another member or the deletion is blocked until it does.
- Logging the data you are deleting. A debug line that prints the user record in the deletion job copies it into your logs. Log the request ID and step names only.
Step 6: Test with a fully populated account
A deletion test that creates a bare user and deletes it proves almost nothing. Write a fixture that creates a user with data in every place on your inventory: uploads, comments in a shared thread, an invoice, a team membership, a search document. Then run the job and assert, item by item, what should remain:
- No rows in hard-delete tables reference the user ID.
- Comments still exist, show the placeholder author, and contain no email or name.
- The invoice still exists and is marked for retention.
- No storage objects remain under the user's prefix.
- Calling the job a second time succeeds and changes nothing.
Add one more test that kills the job partway through (raise an exception from a middle step) and then reruns it. That single test catches most of the resumability bugs. For third-party services, use their test mode or a fake client that records calls, and assert the right delete calls were made.
Finally, keep the test in sync with the inventory. When someone adds a new table with a user_id column, a simple CI check that compares the schema to data-inventory.md and fails on unlisted columns stops new data from escaping deletion.
A prompt that tends to work
Once the inventory and decisions exist, a prompt along these lines gives far better results than "add account deletion":
Implement account deletion for our app. Attached: schema, data-inventory.md
(with an action per item: hard delete, anonymize, retain, expire), and our
existing background job framework.
Requirements:
- POST /account/delete requires re-authentication, creates a deletion_requests
row, revokes sessions and tokens, and blocks login immediately.
- A worker runs deletion after a 7-day grace period, as named idempotent steps
recorded per request, so it can resume after a crash.
- "Not found" from any system counts as success.
- Delete owned rows in batches of 5,000. Delete the user row last.
- Do not add or change ON DELETE CASCADE without listing it for review.
- Never log user field values; log request ID and step names only.
- Write tests using a fully populated user fixture, including a test that
fails mid-job and reruns.
Checklist before you merge
- Every table, bucket, index, and third-party service holding user data is in the inventory, with an action.
- The request endpoint re-authenticates, disables the account right away, and returns fast.
- The job is split into idempotent steps with recorded progress and runs the user row deletion last.
- Cascades match the decision table; retained records survive.
- Anonymized records contain no recoverable identity.
- Stuck deletions alert a human.
- Tests cover a fully populated account, a rerun, and a crash halfway through.
- You can tell a user, in plain words, what was deleted, what was kept and why, and when backups age out.
An LLM can write most of this code quickly and correctly once the hard decisions are made. What it cannot do is find the support tool your team pastes customer emails into, or decide which records the law requires you to keep. Do that part yourself, hand the model a clear specification, and review the result as if you were the user who clicked "Delete my account" and trusted it to mean something.
Comments
Post a Comment