Sub topic 14
Access control, encryption, and retention
Earlier chapters reduced what reaches your logs. This chapter covers the logs that remain: who can read them, how they are protected on disk and in transit, and when they are deleted. It assumes you can write Python, have called an LLM API, know what a log pipeline does, and have read the chapters on the logging policy and redaction.
Why storage controls still matter
Redaction is pattern-based, so it misses some data. A name in free text, a customer's medical detail, or a pasted internal document can pass through a regex unchanged. Treat any stored content log as possibly containing sensitive data, and protect it for that reason.
Three questions decide how to protect a log store:
- Who can read it?
- What happens if the storage is copied, stolen, or misconfigured?
- How long does it exist?
Access control answers the first, encryption the second, and retention the third. None of them replaces the others.
Split logs into tiers
Your logging policy already separates two kinds of data: metadata (model, token counts, latency, status, hashes) and content (redacted, truncated prompts and responses). Store them separately, because they carry different risk and different audiences.
| Tier | Contents | Typical readers | Typical retention |
|---|---|---|---|
| Metadata | Request ID, model, sizes, hash, status, latency | Engineers, on-call, finance | 30 to 90 days |
| Content | Redacted prompt and response excerpts | A small named debugging group | 1 to 14 days |
| Audit | Who read content logs, and when | Security and compliance | Longer, per policy |
A separate store per tier (different bucket, index, or table) lets you set permissions, keys, and expiry independently. Mixing both tiers in one index forces you to give everyone the strictest access or no one the access they need.
Access control
Apply least privilege: give each person the minimum access their job needs.
- Default deny for content. Most engineers need metadata to find slow or failing calls. Few need prompt text. Grant content access to a named group, not to everyone with production access.
- Use roles, not shared accounts. Individual identities make an audit trail meaningful. A shared "logs-reader" login hides who read what.
- Time-box elevated access. For urgent debugging, grant content access for a few hours through an approval step ("break-glass"), then let it expire automatically. This matches the opt-in, time-limited content logging from the previous chapter.
- Control the exports. Dashboards, saved queries, alert payloads, and chat notifications copy log text into places with weaker permissions. Alerts should carry request IDs, not content. Anyone can look up an ID, but only authorized people can open the content behind it.
- Limit third-party sinks. If a vendor's log service receives content, its staff, subprocessors, and retention rules become part of your risk. Send content only to services your organization has approved for that data.
- Audit reads. Record who queried the content store, when, and with what filter. Review the audit log periodically, and alert on unusual volume, such as one user exporting thousands of records.
Service accounts need the same care. The application should have write-only access to the log store: it can append records but cannot read or delete them. If the app is compromised, the attacker cannot use its credentials to read old logs.
Encryption
Encryption protects data when someone gets the storage or network traffic without getting authorized access.
In transit. Use TLS between the app, the log shipper, and the log backend. Do not send logs over plain HTTP or unencrypted syslog, even inside a private network. Internal networks are not a trust boundary you should rely on.
At rest. Enable encryption on every place a log can land:
- the log database or search index
- object storage buckets
- disk volumes on log collectors, since they buffer data locally
- backups and snapshots
Managed services usually offer this with a checkbox or a key setting. Use a customer-managed key for the content tier if you can. Then you can restrict which identities may use the key, and the key's access log becomes another audit source.
Using a separate key for the content tier has a second benefit. Disabling or deleting that key makes every copy of the content unreadable, including copies in backups you cannot easily find. This is called crypto-shredding. It is a strong backstop, but it does not replace normal deletion.
Retention
Retention is the rule for how long logs exist. Shorter is safer: data that no longer exists cannot leak, be subpoenaed, or be misused. Choose the period by asking what the log is for.
- Debugging content is useful for days. A bug reproduced next week no longer needs last month's prompts. Seven days is a common starting point.
- Metadata for cost and latency analysis is useful for months, because you compare week over week and month over month. It holds no prompt text, so a longer period is acceptable.
- Audit records may be required for longer by regulation or company policy. Check your organization's rules rather than guessing.
If you are subject to data-protection law, personal data in content logs may have to be deleted on request, and "we keep everything for a year" will be hard to defend. Ask your privacy or legal contact about deletion requests before launching content logging.
Enforce retention in storage
Do not rely on a cleanup script that someone has to remember to run. Prefer a rule the storage system enforces. On Amazon S3, a lifecycle rule expires objects by prefix:
{
"Rules": [
{
"ID": "expire-llm-content-logs",
"Status": "Enabled",
"Filter": { "Prefix": "llm-logs/content/" },
"Expiration": { "Days": 7 },
"NoncurrentVersionExpiration": { "NoncurrentDays": 1 }
}
]
}Save this as lifecycle.json and apply it with aws s3api put-bucket-lifecycle-configuration --bucket YOUR_BUCKET --lifecycle-configuration file://lifecycle.json. The NoncurrentVersionExpiration line matters if bucket versioning is on. Without it, "deleted" objects stay as old versions.
Databases and log platforms have equivalents: time-to-live columns, index lifecycle policies, or per-index retention settings.
A local purge job
When logs are files on a host, a small job can enforce the same tiers. This version supports a dry run so you can check what it would delete before turning it on. It needs Python 3.10 or later.
import os
import tempfile
import time
from pathlib import Path
RETENTION_DAYS = {"metadata": 90, "content": 7}
def purge_expired(root: Path, tier: str, now: float | None = None,
dry_run: bool = True) -> list[Path]:
now = time.time() if now is None else now
cutoff = now - RETENTION_DAYS[tier] * 86400
expired = []
for path in sorted((root / tier).glob("*.jsonl")):
if path.stat().st_mtime < cutoff:
expired.append(path)
if not dry_run:
path.unlink()
return expired
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "content").mkdir()
old = root / "content" / "old.jsonl"
new = root / "content" / "new.jsonl"
old.write_text("{}\n")
new.write_text("{}\n")
ten_days_ago = time.time() - 10 * 86400
os.utime(old, (ten_days_ago, ten_days_ago))
print([p.name for p in purge_expired(root, "content")])
print(old.exists())
purge_expired(root, "content", dry_run=False)
print(old.exists(), new.exists())Running it prints ['old.jsonl'], then True (the dry run deleted nothing), then False True (only the expired file was removed).
Find every copy
Deleting from the primary store is not enough. Data from one request may also sit in:
- search indexes built from the log store
- backups and snapshots, which often have their own, longer retention
- a log shipper's disk buffer
- analytics exports, data warehouse tables, and notebooks
- bug tickets and chat messages where someone pasted a log line
List these copies when you design the pipeline. Give each a retention no longer than the source, or make sure it contains only metadata.
Common mistakes
- Setting retention once and never checking it. Verify that expiry works by confirming old objects are gone.
- Giving the same role access to both tiers because it is simpler.
- Putting content in alert messages, which then live in a chat tool forever.
- Using one encryption key for everything, so you cannot shred content without destroying metadata.
- Granting the application read and delete rights on the log store when it only needs to write.
Exercise
Your team keeps redacted prompt excerpts for 7 days in a content store, but the storage snapshots are kept for 30 days. A user asks you to confirm their prompt text is gone after 7 days. What is wrong, and give two ways to fix it?
Show answer
The snapshots still hold the content for up to 30 days, so the effective retention is 30 days, not 7. Fixes: (1) exclude the content store from snapshots, or shorten the snapshot retention for it to 7 days; (2) encrypt the content tier with its own key and disable that key at day 7, which makes the snapshot copies unreadable (crypto-shredding). Also check other copies such as search indexes and exports.
Exercise
An alerting rule posts the full text of failed LLM prompts to a team chat channel with 200 members. Which part of the content tier's design does this break, and how would you change the alert?
Show answer
It copies content into a place with broader access and no retention control, bypassing the content tier's access limits and expiry. Change the alert to include only the request ID, model, error type, and status. Responders then look up the content, if they are authorized, in the content store, where reads are audited.