Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 5 · Concept · 15 min · revision 3

Why Files Do Not Belong on the API Server's Disk

Understand why storing user uploads on application server local filesystems breaks container scalability, causes data loss on redeploys, and why database BLOBs degrade relational performance.

Contentsand lesson path

On this page

  1. Why it matters
  2. The database BLOB anti-pattern
  3. Architectural separation: object storage and relational metadata
  4. Check your understanding
  5. Apply it
  6. Review prompt

Lessons of File Uploads & Object Storage

  1. Why Files Do Not Belong on the API Server's Disk Concept · 15 min
  2. Receiving Uploads Safely Worked example · 25 min
  3. Lab: Object Storage with Presigned URLs Lab · 30 min
  4. Large Uploads and Post-Processing Pipelines Concept · 20 min
  5. Check: Review an Upload Feature for Threats Knowledge check · 6 questions

What you will learn

  • Store files in S3-compatible object storage with metadata in the database, and serve them through short-lived presigned URLs.

01. Why it matters

When you build your first file upload feature, such as user avatars, PDF invoices or CSV exports, the obvious implementation writes the uploaded bytes to the server's own disk with open("/var/uploads/" + filename, "wb").

On one development laptop this works. Once the application runs as containers on a cluster (Kubernetes, AWS ECS or a serverless container platform), files on the local disk get lost, go missing on some requests, or fill the disk.

Three facts of container platforms cause this:

  • Container filesystems are disposable. Following the Twelve-Factor App, instances are stateless and disposable. When Kubernetes restarts a container after an out-of-memory kill, rolls out a new image or scales down replicas, the new container starts again from the image, and files written to the old container's writable layer are gone. A persistent volume keeps them, but a typical ReadWriteOnce volume can be attached to only one node at a time, so it does not solve the next problem.
  • Each replica has its own disk. A service with several replicas behind a load balancer sends each request to any of them. If Alice's avatar is written to replica A and Bob's request for her profile reaches replica B, B has no such file and answers 404 Not Found. The result is files that are present on some requests and missing on others.
  • Disks are small and shared. API servers usually have a modest root disk, often tens of gigabytes. Uploads fill it silently, and when it is full, logging, temporary files and other processes on that host start failing too. Docker also recommends volumes rather than the container's writable layer for write-heavy data, because writes through the storage driver (such as overlay2) are slower than writes to a volume.

02. The database BLOB anti-pattern

Once teams see that container disks are disposable, many move the bytes into the relational database instead, as binary columns (BLOB in MySQL, BYTEA in PostgreSQL).

Storing files in PostgreSQL does give you transactions (the file and its row commit together), and the files survive redeploys. But it moves the load onto the most expensive part of your system:

  • Cache pressure: The database keeps hot table and index pages in memory (shared_buffers and the operating system cache). Reading and writing many megabyte-sized values pushes those pages out, so ordinary queries go to disk more often.
  • TOAST overhead: When a row grows past about 2 kB, PostgreSQL compresses large values and moves them, split into chunks, to a separate TOAST table (The Oversized-Attribute Storage Technique). That keeps the main table small, but every read or update of a large file still fetches, reassembles and often decompresses all of its chunks.
  • Backups grow with every file: pg_dump output, write-ahead log (WAL) archives and replicas all carry every byte of every file, so backups, restores and point-in-time recovery get slower and more expensive as uploads accumulate.
  • Connections held by slow clients: Streaming a 50 MB file out of PostgreSQL to a slow mobile client keeps one database connection busy for the whole transfer, taking it away from the pool that other API requests need.

03. Architectural separation: object storage and relational metadata

The usual design separates object storage for the bytes from structured metadata in the database:

  • Object storage for the bytes: Cloud services such as Amazon S3, Google Cloud Storage and Azure Blob Storage, and self-hosted S3-compatible servers such as SeaweedFS or Ceph, are built for large binary objects. The cloud services grow capacity for you, replicate data across availability zones and offer cheaper storage tiers; Amazon S3, for example, is designed for 99.999999999% (11 nines) durability of objects over a year. A self-hosted server is only as durable as the disks and replication you give it.
  • The relational database for metadata only: The main database stores a small structured record per file: the object storage key, the owner's user ID, the original filename (sanitised), the detected MIME type, the size in bytes, a content hash and a status (pending, scanning, ready, rejected).
  • CDN delivery: Files in a bucket can be served through a content delivery network (CDN) such as CloudFront or Cloudflare. Downloads then go to the CDN or the bucket instead of your API servers, which saves their bandwidth and serves users from a nearby location.

With bytes and metadata separated, API servers keep no files of their own, the database stays small, and storage capacity grows independently of both.

Python · models.py (SQLAlchemy 2.x typed mapping: metadata only, no bytes)
import uuid
from datetime import datetime

from sqlalchemy import BigInteger, DateTime, Enum, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column


class Base(DeclarativeBase):
    pass


class StoredFile(Base):
    __tablename__ = "stored_files"

    # Unique file record ID (never trust client filenames)
    id: Mapped[str] = mapped_column(
        String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    owner_id: Mapped[str] = mapped_column(String(36), index=True)
    # Object storage location: s3://bucket-name/{storage_key}
    storage_key: Mapped[str] = mapped_column(String(255), unique=True)
    original_filename: Mapped[str] = mapped_column(String(255))
    content_type: Mapped[str] = mapped_column(String(100))
    size_bytes: Mapped[int] = mapped_column(BigInteger)
    sha256_checksum: Mapped[str] = mapped_column(String(64))
    status: Mapped[str] = mapped_column(
        Enum("pending", "scanning", "ready", "rejected", name="file_status"),
        default="pending",
    )
    # server_default: the database stamps each row at insert time.
    # default=datetime.now(timezone.utc) would be evaluated once, at import,
    # and every row would get that same timestamp.
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now())

04. Check your understanding

Practice check · 3 questions

File storage architecture principles check

Three questions assessing container storage limitations, database BLOB hazards, and object storage.

Q1. To check that uploads survive, you upload a file and run `docker compose restart api`. The file is still there. What does that prove?
Q2. With bytes in a BYTEA column, a file and its row were saved in one transaction. Once the bytes move to object storage, what new failure must the app handle?
Q3. A model declares `created_at = Column(DateTime(timezone=True), default=datetime.now(timezone.utc))`. What timestamps do new rows get?
Practice only: not graded, not saved, not evidence.

05. Apply it

Audit your application codebase for instances of local file storage anti-patterns:

  • Remove local file paths: Search for open(), shutil.copy(), or framework file-saving helpers that write to local disk paths like /uploads or /tmp. Refactor these routines to write to S3 or a local MinIO bucket.
  • Design a metadata table: Create a dedicated stored_files relational schema capturing ownership, storage keys, MIME types, byte sizes, and verification states.
  • Test that files outlive the container: In a Docker Compose environment, upload a file, run docker compose up -d --force-recreate api, and verify that the file is still served because its bytes reside in an external object bucket rather than the container filesystem. Use --force-recreate (or docker compose down followed by up -d), not docker compose restart: a restart keeps the same container and its writable layer, so a file saved to local disk would survive it too and the test would prove nothing. Then repeat the test with the old local-disk code and watch the file disappear.

In the next lesson, you will learn how to receive file uploads safely, validating MIME types through magic bytes, enforcing size limits, and sanitizing filenames.

06. Review prompt

Explain why containerized cloud deployments make storing uploaded files on API server local disks unreliable. Describe the three major operational penalties of storing large binary files as database BLOBs, and detail the architectural separation of concerns between relational metadata tables and cloud object storage.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check