JuniorDatabase

Why don't we usually store images directly in the database? Where do you store them?

Images are large and you almost never query them by their content. Storing them directly in the database (as binary or base64) causes several problems:

  • It uses the most expensive space. Database storage is usually limited and costs more than file storage. For example, Supabase's free plan has a 500 MB database: a long post is only a few dozen KB of text, while a single phone photo is several MB. A few dozen posts with images and it's full.
  • It's slow and heavy. Every query drags large data along, backups and restores take longer, and the database's cache fills up with image bytes.
  • It can't use a CDN. Images in object storage are served through a CDN and cached close to users; images in the database have to go through the application server.

The common approach: store image files in object storage (Supabase Storage, Amazon S3, Cloudflare R2…) and keep only the path and some metadata (size, alt text, who uploaded it) in the database. On top of that, compress images before uploading (resize, convert to WebP/AVIF) to cut both storage and bandwidth.

Bonus points: mention cleaning up images that no post uses anymore, and permissions for the file store, meaning who can upload and who can view.