Monday, February 4, 2008

Storing files on the disk vs. database


Until recently I have been a fan of storing files, uploaded through my web applications, on the disk. However lately I find myself moving more towards storing the files in the database as it's more flexible and easier to maintain. Below are some pros and cons.

Storing files on the disk:
Pros:

  • Performance - faster to retrieve files from the disk than a database.
  • Anyone having access to the disk can read and modify files, no need for an additional interface.

Cons:

  • Harder to implement security on single files.
  • Time consuming to do backups when there are thousands of files.


Storing files in a database:
Pros:

  • Web/database-farm support - easy to keep two or more databases up to date through replication.
  • Handling security is a cake - when getting the file use join/exists to query the user/role table to check for read access, if no read access return nothing.
  • More convenient to have all the data located in a single database file.

Cons:

  • Performance - one or more queries against the database are needed in order to get the file, 20 images on a webpage means 20+ queries. Network traffic can also become a bottleneck if the database is running on a seperate server.
  • Cost - on shared webhosts, database space is usually more expensive than diskspace.

Conclusion:If you need security checks, replication and don't want thousands of files on your disks, store the files in a database, otherwise store it on the disk.