Sub topic 3
Why files belong in object storage, and how to name keys
This chapter assumes you know HTTP basics, have a client, API server, and database architecture in mind, and have a general idea of what Amazon S3 is. It covers where uploaded files should live and how to name them.
Why not the database or the server disk?
Two obvious places to put a file are a database column (a BLOB) or the API server's local disk. Both break down as you grow.
| Option | Problem |
|---|---|
| Database BLOB | Large rows bloat backups and replicas. Reads of big values compete with normal queries for memory and connections. |
| Server local disk | A second server cannot see the file. Deploys and autoscaling can erase it. Disk space is capped by the instance. |
| Object storage | Not tied to any one server. Scales without limit, is durable, and serves files over HTTP. |
Object storage (S3, Google Cloud Storage, Azure Blob) holds immutable blobs under a key, inside a bucket. It has no real directories and no in-place edits. You write a whole object, read it, or delete it. That fits user uploads well, because files are written once and read many times.
Your database keeps only the metadata: the key, owner, size, declared type, and status.
Designing keys
A key is the object's full name. S3 shows slashes as folders in its console, but they are only characters in the key. Good keys have a few properties.
- Unique without coordination. Use a random ID such as a UUID. Never use the user's original filename as the whole key, because two users will upload
photo.jpg. - No user-controlled path parts. A name like
../../adminis harmless in S3, but it can cause trouble later in tools that treat keys as paths. Generate the key on the server. - Stable and meaningful by prefix. A prefix such as
incoming/oravatars/lets you attach lifecycle rules, permissions, and event triggers to one class of files. - No secrets or personal data. Keys appear in URLs, logs, and analytics.
Here is a key generator that follows those rules.
import uuid
from pathlib import PurePosixPath
ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".mp4"}
def make_key(prefix: str, original_name: str) -> str:
ext = PurePosixPath(original_name).suffix.lower()
if ext not in ALLOWED_EXTENSIONS:
ext = ""
return f"{prefix}/{uuid.uuid4().hex}{ext}"
print(make_key("incoming", "My Holiday Photo.JPG"))
# incoming/3f2a9c0d8e7b4c1aa5d6e2f1b9c04d37.jpgKeep the original filename in your database, not in the key. You can send it back later in a Content-Disposition header when the user downloads the file.
Content-addressed keys
For delivery you often want a key derived from the file's bytes, such as a hash. Identical content gets the same key, and changed content gets a new one. Later chapters use this to make URLs cacheable forever. A common layout is to upload to a random key under incoming/, then have a processing step copy the result to media/<hash>/<variant>.
Key hygiene
- Do not rely on sequential or timestamp-only prefixes for performance. Modern S3 scales per prefix automatically, but a random component still avoids hot spots and guessable names.
- Keys are case-sensitive and effectively permanent. Renaming means copy then delete.
- Keep keys URL-safe: lowercase letters, digits, hyphens, and slashes.
Common errors
- Using the original filename as the key, which causes overwrites and leaks user data into URLs.
- Storing the full public URL in the database. Store the key, so you can change buckets or CDN domains later.
- Putting everything under one prefix, which makes lifecycle and permission rules hard to scope.
Exercise
A teammate stores uploads at uploads/{user_id}/{original_filename}. Name two problems and propose a better key.
Show answer
Two uploads with the same filename from one user overwrite each other, and the filename and user ID are exposed in URLs and logs. A better key is incoming/{uuid4 hex}{safe extension}, with the user ID and original filename stored in the database.