Sub topic 3
Why files belong in object storage, and how to name keys
This chapter assumes you know HTTP basics, how a client, API server, and database fit together, and roughly what Amazon S3 is. By the end you should be able to explain why uploaded files do not belong in your database or on an application server's disk. You should also be able to design object keys that stay safe, cacheable, and easy to clean up.
Why not the database or local disk?
The first working version of many upload features stores the file somewhere convenient. Two places are common, and both cause problems as the system grows.
Files in a relational database (as BYTEA or BLOB columns) keep the file and its metadata consistent in one transaction. The costs show up later:
- Large rows bloat tables, backups, and replicas. A 20 MB video copied to every replica makes replication slow and expensive.
- Database connections are scarce. Streaming a download through a connection ties it up for the whole transfer.
- Database storage costs more per gigabyte than object storage.
- You cannot hand a file to a CDN without a service in front of the database.
Files on the application server's disk are fast to build and fail in other ways:
- When you run two or more servers, a file saved on server A is missing on server B unless you add shared storage.
- Autoscaling and deploys replace machines, and the disk goes with them.
- Capacity is tied to the machine size. A full disk can take the API down.
- You must build your own replication and backups.
Object storage solves these problems by design. It is a service that stores immutable blobs (objects) in flat namespaces (buckets) and exposes them over HTTP. Amazon S3, Google Cloud Storage, and Azure Blob Storage work this way, as do S3-compatible systems such as MinIO and Cloudflare R2.
What object storage gives you
| Property | What it means for uploads |
|---|---|
| Durability | Objects are replicated across devices and facilities. S3 Standard is designed for 99.999999999% (eleven nines) durability. |
| Effectively unlimited capacity | You do not provision disks. You pay for what you store. |
| HTTP API | Clients and CDNs can read and write objects directly. This enables the direct upload pattern in the next chapter. |
| Per-object metadata | Each object carries `Content-Type`, `Cache-Control`, and custom metadata. |
| Access control | Policies and presigned URLs grant narrow, temporary access. |
| Lifecycle and events | Rules can expire or move objects, and uploads can trigger processing. |
It also has trade-offs you need to design around:
- Objects are immutable. You cannot edit bytes in place. To change a file you write a whole new object, which suits content-addressed and versioned naming.
- It is not a file system. There are no real directories, no atomic rename, and no append. A "rename" is a copy followed by a delete.
- Latency is higher than local disk, typically tens of milliseconds for the first byte.
- Listing is slow and paginated. Do not use it as a query engine. Keep a database table for lookups.
The split: bytes in storage, metadata in the database
The standard design stores the bytes in object storage and a row of metadata in your database. The row references the object by bucket and key.
A typical table looks like this:
CREATE TABLE media (
id UUID PRIMARY KEY,
owner_id BIGINT NOT NULL,
bucket TEXT NOT NULL,
object_key TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes BIGINT,
sha256 TEXT,
status TEXT NOT NULL DEFAULT 'pending',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (bucket, object_key)
);The status column matters. The row can exist before the bytes arrive, and the bytes can arrive before validation finishes. Later chapters use values such as pending, uploaded, scanned, and ready. Never show a file to other users while its status is pending.
Designing object keys
A key is the object's full name, such as incoming/3f2a9c/avatar.jpg. S3 shows / as a folder separator in its console, but the namespace is flat. The slash is only a character, though it is useful for prefix listings and for policies and lifecycle rules that match a prefix.
Good keys follow a few rules.
1. Generate keys on the server
Never use the client's file name as the key. Names can collide, so two users uploading avatar.jpg would overwrite each other. They can also contain path tricks (../), control characters, or very long strings. Create the key yourself from an identifier you control, and store the original file name as metadata.
import uuid
def new_object_key(owner_id: int, extension: str) -> str:
allowed = {"jpg", "png", "webp", "mp4"}
if extension not in allowed:
raise ValueError("unsupported extension")
return f"incoming/{owner_id}/{uuid.uuid4().hex}.{extension}"
print(new_object_key(42, "jpg"))Taking the extension from an allowlist, rather than from the user's string, keeps unexpected characters out of the key.
2. Do not put secrets or personal data in keys
Keys appear in URLs, access logs, CDN logs, and error messages. Avoid email addresses, full names, and anything you would not want in a log line. A random identifier is safer than a guessable sequence like user/42/1.jpg.
A random key is not an access control, though. Treat an unguessable URL as a convenience, not a lock. Private files need signed access, covered later in this tutorial.
3. Separate stages by prefix
Use prefixes to mark where an object is in its life:
incoming/for untrusted uploads that are not yet validated.processed/orpublic/for files that passed checks and were transformed.tmp/for scratch data you can expire after a day.
Prefixes let you write narrow rules. An upload policy can allow writes only under incoming/. A lifecycle rule can delete tmp/ after 24 hours. A CDN origin path can expose only public/. A client then cannot write directly into the area that your CDN serves.
4. Use content-addressed keys for delivered files
For files that viewers fetch, a key built from a hash of the content gives the best caching behavior. Compute the hash during processing and put it in the key:
import hashlib
def content_key(data: bytes, variant: str, ext: str) -> str:
digest = hashlib.sha256(data).hexdigest()[:12]
return f"public/{digest}/{variant}.{ext}"
print(content_key(b"example image bytes", "w800", "webp"))If the content changes, the hash changes, so the key and URL change. The old URL keeps returning the old bytes, and caches never serve stale content under the same URL. This is what allows a one-year immutable cache lifetime, as a later chapter on CDNs shows. It also gives you free de-duplication, since identical files map to the same key.
5. Avoid mutable names for cached content
A key like users/42/avatar.jpg that you overwrite on each change is easy to build and hard to cache. Browsers and CDNs may keep the old image until it expires, and purging caches costs time and money. If you want a stable name, store it in the database and have it point at the current content-addressed key.
6. Think about request distribution
Older S3 guidance told you to start keys with random characters to spread load. Current S3 scales request rates per prefix automatically, so you rarely need this. Some other stores, and very high request rates on any store, can still concentrate load on a narrow key range. Check your provider's documentation for the actual limits before you add random prefixes. Sequential prefixes such as dates are fine for most applications and make time-based cleanup simple.
Putting a key scheme together
A reasonable scheme for an avatar upload uses two stages:
| Stage | Example key | Written by |
|---|---|---|
| Upload | `incoming/42/5d0e8f1c….jpg` | Client, using a presigned URL |
| Delivery | `public/9b1c4e7a2f10/w800.webp` | Processing worker |
The client can only write to incoming/. A worker validates the file, creates variants, and writes content-addressed objects under public/. The media row records both keys until you delete the original.
Common mistakes
- Using the original file name as the key, which causes overwrites and path injection.
- Storing only the URL in the database. Store the bucket and key, so you can move to another domain or CDN without rewriting rows.
- Listing a bucket to find a user's files instead of querying the database.
- Overwriting a delivered object in place and then fighting stale caches.
- Mixing untrusted and trusted files under the same prefix, which makes policies and cleanup harder.
Exercise
A team stores each profile photo at avatars/{user_id}.jpg and overwrites it when the user uploads a new one. Users report seeing old photos for hours after changing them. Propose a key design that fixes this, and say where the stable reference should live.
Show answer
Write each processed photo to a content-addressed key such as public/{sha256_prefix}/w256.webp, so every new photo gets a new URL. Store the current key in the user's database row (or the media row the user references). The page then renders the new URL right away, and the old URL can stay cached or expire without causing stale results. The old object can be deleted later by a lifecycle rule or cleanup job.
Exercise
Give two reasons a server should generate object keys instead of using the file name the client sent.
Show answer
First, file names can collide, so one user's upload would overwrite another's. Second, client-supplied names can include path sequences, control characters, or personal data, which can break prefix-based policies and leak information into URLs and logs. A server-generated key from a random ID and an allowlisted extension avoids both.