Secrets, retention and deletion across the stack
Rotate secrets and delete a tenant's data from the API, storage, vector index, logs and providers with an audit trail.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.
In short
Secrets and customer data both have a lifecycle: they are created, used, copied into several places and must eventually be rotated or deleted. In a document Q&A service a tenant's data lives in Postgres, object storage, the vector index, caches, logs, backups and possibly a model provider. A real deletion or rotation plan lists every one of those places, says how long data stays in each, and leaves an audit record that proves the work was done.
Think of it like this: Moving out of a flat is not just returning the front door key: you also collect the spare keys, cancel the post, and get a signed note saying the deposit is settled.
Explained simply
A secret is anything that grants access, such as a database password, a model provider API key or the key that signs tokens. Secrets leak in boring ways: pasted in a chat, left in Git history, printed in a log. So you plan to replace them regularly, which is called rotation, and you make rotation routine enough that nobody fears it.
Rotation without downtime works by overlap. You create the new secret while the old one still works, move every user of it across, check that nothing still uses the old one, and only then switch the old one off.
Customer data has a lifecycle too. When a tenant uploads a document, copies appear in many places: the database, file storage, the search index, caches, logs, backups and sometimes the model provider. Each place should have a written rule for how long data stays, called a retention period.
When a customer asks you to delete their data, you run a deletion job that visits every one of those places, records what happened in each, and reports when the last copy is gone. That record, an audit trail, is how you prove the deletion happened.
Press Play on a diagram to walk through it one step at a time.
- 1Create new
Add version 2 in the secret store; version 1 still valid
- 2Accept both
Verifiers accept old and new keys
- 3Switch callers
Restart or reload clients to use version 2
- 4Watch
Confirm no traffic still uses version 1
- 5Revoke old
Disable version 1 and record the rotation
- Back to step 1
- Postgres
- documents and jobs rows
- conversations and messages
- chunk rows with embeddings
- Object storage
- original uploads
- extracted text
- Redis
- cached answers
- quota counters
- Logs and traces
- request logs
- error reports
- Backups
- database snapshots
- bucket versions
- Model provider
- prompts kept under its retention policy
- Admin to API: DELETE /tenants/fabrikam1DELETE /tenants/fabrikam
- API to Stores: Mark tenant deleting; audit 'requested'2Mark tenant deleting; audit 'requested'
- API to Worker: Enqueue deletion job3Enqueue deletion job
- API to Admin: 202 Accepted with job ID4202 Accepted with job ID
- Worker to Stores: Delete rows, objects, cache keys5Delete rows, objects, cache keys
- Stores to Worker: Counts per store6Counts per store
- Worker to Stores: Audit 'completed'; job status done7Audit 'completed'; job status done
In depth
Keeping secrets out of code and images
Secrets belong in a secret manager, such as HashiCorp Vault, Google Secret Manager, AWS Secrets Manager or Azure Key Vault, and reach the app at runtime as environment variables or mounted files. Locally, a git-ignored .env file with placeholder values is enough. A pydantic-settings class loads them, and SecretStr keeps the value out of repr output and accidental logs.
Never bake secrets into a Docker image: anyone who can pull the image can read its layers. Never commit them: even after you delete the line, Git history keeps it. If a secret was ever committed, treat it as leaked and rotate it. Add a secret scanner to pre-commit or CI so mistakes are caught early.
- Secret manager in the cloud, .env locally (git-ignored)
- SecretStr hides values in repr and logs
- Scan commits with a tool such as gitleaks
- A committed secret is a leaked secret: rotate it
Rotating without downtime
Each kind of secret rotates a little differently, but the pattern is always overlap. For a database, create a second login or set a new password on a second role, update the app's secret, roll the instances, then drop the old login. For a provider API key, create a second key in the provider console, deploy it, watch usage on the old key fall to zero, then revoke it.
Token signing keys use a key ID. The issuer publishes its public keys as a JWKS document, and each token header carries a kid. Publish the new key first, wait for caches to refresh, then start signing with it. Keep the old public key published until every token it signed has expired. The API should pick the key by kid, not assume there is only one.
- 1Publish key-2
JWKS lists key-1 and key-2
- 2Wait
Verifiers refresh their JWKS cache
- 3Sign with key-2
New tokens carry kid=key-2
- 4Let key-1 tokens expire
Wait at least the longest token lifetime
- 5Remove key-1
JWKS lists key-2 only
Retention per data store
Write a small table with one row per store: what it holds, why, how long, and what enforces the limit. Uploads might stay until the tenant deletes them. Chat messages might expire after 90 days through a nightly job. Redis cache entries expire through TTLs measured in minutes. Application logs might keep 30 days through the log platform's retention setting. Backups follow their own schedule, for example 35 days.
The point is that every limit is enforced by something automatic: a TTL, a bucket lifecycle rule, a scheduled DELETE, a log retention setting. A policy that relies on someone remembering is not a policy. The numbers above are examples; real ones come from your contracts and any laws that apply to your customers.
Deleting a tenant across the stack
Deletion is a job with steps, like ingestion in reverse. First mark the tenant as deleting, so the API refuses new requests and retrieval skips its rows. Then delete in an order that never leaves orphans you cannot find: rows in chunks and messages, then documents and jobs, then objects under the tenant's storage prefix, then cache keys under its prefix. Each step is idempotent, so a crashed job can safely restart.
Some copies cannot be removed at once. PostgreSQL frees deleted rows only when VACUUM runs, and backups keep old data until they expire. Third-party inference is the same: providers keep prompts for a period set by their terms, which can include abuse monitoring, unless you have a zero-retention agreement. Check the current terms of your provider and state the real worst-case date in your reply to the customer.
- Mark first, then delete, then verify
- Delete by tenant prefix in object storage and Redis
- Every step idempotent and recorded
- Backups and provider copies age out on their own schedule
An audit trail that proves it
An audit record answers who did what, to which resource, when, and with what result. Write it to an append-only table or log that application code can insert into but not update or delete. For a deletion, record the request ID, the requester, the tenant, each store with the count of items removed and a timestamp, and the final status.
Do not copy the deleted data into the audit log, or you have just moved it. IDs and counts are enough. Rotation events belong here too: which secret, which version, who rotated it and when the old one was revoked. During an incident or a customer audit, this trail turns "we think we did it" into evidence.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Rotate secrets without downtime~35m
- 2Set retention per data store~35m
- 3Delete across index, storage and logs~35m
- 4Check third-party inference retention~35m
- 5Record an audit trail~35m
Key points
- Rotate by overlapping old and new secrets, so no request fails during the switch.
- Give each data store its own written retention period, and enforce it with a job or a lifecycle rule.
- Deletion is a tracked job across every store, not one DELETE statement.
- Backups and provider-side copies expire on their own schedule; document that delay honestly.
- The audit trail records who asked, what was deleted where, and when, without copying the deleted content.
Key terms
Tap a card to flip it. 0/5 known
Examples
Rotating the model provider key with zero failed requests
Prerequisites: the API reads MODEL_API_KEY from the secret manager at startup. Step 1: create a second key in the provider console and store it as a new secret version. Step 2: roll the API and worker instances one at a time; each starts with the new key. Step 3: in the provider's usage page, watch requests on the old key drop to zero. Step 4: revoke the old key and write an audit entry. Rollback: if errors rise in step 2, point the secret back to the previous version and roll again, since the old key still works.
from pydantic import SecretStr
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: SecretStr
model_api_key: SecretStr
settings = Settings()
print(settings.model_api_key) # **********
key = settings.model_api_key.get_secret_value() # use only when callingDeleting tenant fabrikam locally and proving it
Prerequisites: the local Compose stack with Postgres, MinIO or the local file store, and Redis. Step 1: count fabrikam rows, objects and cache keys and note them. Step 2: call the deletion endpoint and wait for the job to finish. Step 3: run the same counts and expect zero everywhere. Step 4: read the audit table and expect a requested and a completed entry with counts that match step 1. Cleanup: reseed fabrikam from the fixtures if you need it again.
async def delete_tenant(db, store, cache, tenant_id, audit):
counts = {}
counts["chunks"] = (await db.execute(delete(Chunk).where(Chunk.tenant_id == tenant_id))).rowcount
counts["documents"] = (await db.execute(delete(Document).where(Document.tenant_id == tenant_id))).rowcount
await db.commit()
counts["objects"] = await store.delete_prefix(f"tenants/{tenant_id}/")
counts["cache_keys"] = await cache.delete_prefix(f"t:{tenant_id}:")
await audit.record("tenant.deleted", tenant_id=tenant_id, counts=counts)
return countsQuick reference
- Secrets live in a secret manager; .env only for local placeholders, never committed
- Rotate by overlap: add new, switch callers, confirm, revoke old
- JWT signing keys: publish new kid first, remove old after the longest token lifetime
- Every store needs a retention period and an automatic enforcer
- Deletion order: mark tenant, delete rows, objects, cache, then verify counts
- Postgres deleted rows are reclaimed by VACUUM; backups age out on schedule
- Check your model provider's current data retention terms before promising dates
- Audit records hold IDs, counts and times, never the deleted content
Common mistakes
- Deleting the Postgres rows but leaving the uploads in the bucket and the embeddings in a separate index.
- Rotating a key by replacing it in place, which breaks every running instance until it restarts.
- Putting secrets in Docker images, Git history or log lines, where rotation never reaches them.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a retention table for the document Q&A service covering at least five stores, with an enforcer for each.
- Exercise 2medium
Make the API accept two provider keys during rotation: try the primary, and fall back to the secondary only on a 401 from the provider.
- Exercise 3hard
Design an append-only audit table in PostgreSQL that the application role can insert into but not change or delete.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How often should I rotate secrets?
- Rotate at once after any suspected leak or when someone with access leaves, and on a regular schedule otherwise. Automating rotation matters more than the exact interval.
- Does deleting a row in PostgreSQL remove the data immediately?
- The row disappears from queries at once, but its bytes stay on disk until VACUUM reuses the space, and backups keep it until they expire.
- Do model providers keep my prompts?
- It depends on the provider, product and contract. Many keep requests for a limited time for abuse monitoring unless you have a zero-retention agreement, so read the current terms.
- What is crypto-shredding?
- Encrypting each tenant's data with its own key and deleting that key to make all copies unreadable, including those in backups.