← Back to SQL, page 19

sql-0367 · Medium mid

Should uploaded files such as images and PDFs be stored in the database?

Usually not: store the file in object storage and keep a row with its key, size, type, checksum and owner in the database. Large blobs inflate backups, replication and memory use, and object stores serve files more cheaply. Small files that must be transactionally consistent with other data, such as tiny thumbnails or signatures, can live in the database.

Full answer

Typical design:

text
files(id PK, owner_id FK, storage_key UNIQUE, content_type, size_bytes,
      sha256, created_at, deleted_at)

The application uploads the object (often directly from the client with a signed URL), then records the row. Deleting marks the row and a job removes the object.

Why not blobs in tables:

  • Backups and restores grow with every upload.
  • Replicas copy all of it.
  • Reading a large blob through the database ties up a connection.

Consistency gaps (a row without its object, or an orphaned object) are handled by recording a pending state before upload and a periodic reconciliation job. For SQLite-based local apps, storing small blobs inline is reasonable, since SQLite reads small blobs efficiently.

Key points

  • Store files in object storage
  • Keep metadata and the key in the database
  • Blobs bloat backups and replicas
  • Reconcile rows and objects periodically

Common mistakes

  • Storing full file paths that break when buckets move
  • Deleting rows without deleting objects

Follow-ups

  • How would you serve private files securely?
  • How would you deduplicate identical uploads?

Tips

  • Describe the metadata row