How to Store Large Files Outside the Database Without Breaking Links

You store files outside the database when the database stops being a good file server: when rows get large, when every page load drags binary data through the application, or when backups and replication become painful. The fix is to move the bytes to a filesystem or object store and keep a stable reference in the database, but only if you preserve the URLs and code paths that already point at those files. The decision to store files outside database hosting is mostly about access patterns and backup size; the hard part is the migration without broken links.

When the database is the wrong place for bytes

A relational database stores binary large objects as values in a column. That works for small blobs, thumbnails, signatures, a few kilobytes each. It stops working well when the values are megabytes and the table has millions of rows. The engine has to page those values through its buffer pool, and a plain SELECT that forgets to exclude the blob column pulls the whole thing over the wire. Backups grow with the data, so a database dump that used to take minutes now takes hours and competes with live traffic. Replication streams the same bytes to every replica.

Object storage and plain filesystems are built for this. They stream bytes, they serve range requests, and they let a reverse proxy or CDN hand out the file without touching your application. The signal to move is simple: if you find yourself writing code to avoid selecting a column, or if your dump size is dominated by one table, the bytes belong elsewhere.

Keep the database as the index, not the vault

The pattern that survives migration is a small table that maps a stable key to a storage location. The key is what your URLs and your code already use, usually an integer id or a random token. The location is a path or an object key. Nothing in the URL has to change when the bytes move.

CREATE TABLE files (
  id          bigserial PRIMARY KEY,
  token       text NOT NULL UNIQUE,
  storage     text NOT NULL,      -- 'db', 'fs', 'object'
  path        text,               -- relative path or object key
  mime        text NOT NULL,
  bytes       bigint NOT NULL,
  sha256      text NOT NULL
);

Your application resolves a request for /files/<token> by looking up the row, then reading from whichever backend storage names. During and after migration, that column is the switch. Old rows still say db and are served from the blob column. New rows say object and are served from the store. A single resolver function hides the difference from the rest of the code, so templates and API clients never learn where the bytes live.

Preserve the URL contract while you store files outside database hosting

The link is the contract. If your pages emit /uploads/2024/photo.jpg or /files/8f3a..., those strings must keep resolving after the move. There are two clean ways to do that. The first is to keep your own route and have the application stream or redirect to the new location. The second is to put a reverse proxy in front and let it serve from the filesystem or proxy to the object store, so the application is not in the hot path at all.

A redirect is the least invasive option. The application looks up the token, finds the object key, and answers with a 302 and a Location header pointing at the store or a signed URL. The browser follows it and the URL in the address bar stays yours.

HTTP/1.1 302 Found
Location: https://cdn.example.net/media/8f3a/photo.jpg
Cache-Control: private, max-age=300

If you serve from the filesystem behind a proxy, the config is a location block that maps the public path onto the directory, with try_files falling through to the application so not-yet-migrated files still resolve. Keep the public prefix identical to the old one. Do not rename directories during the move; renaming is what breaks links.

location /uploads/ {
    root /srv/app/storage;
    try_files $uri @app;
    add_header Cache-Control "public, max-age=31536000, immutable";
}
location @app {
    proxy_pass http://127.0.0.1:8000;
}

Move the bytes in batches and verify each one

Do not attempt a single big migration. Walk the table in key order, copy a batch, write the new storage and path, and verify the checksum before you flip the row. The sha256 column earns its keep here: compute it on read from the old source and on write to the new one, and refuse to update the row if they differ.

psql -At -c "SELECT id, path FROM files WHERE storage='db' ORDER BY id LIMIT 500" \
  | while IFS='|' read -r id path; do
      pg_dump_blob "$id" > "/srv/app/storage/$path" && \
      sha256sum "/srv/app/storage/$path"
    done

The shape of the output is one checksum line per file, which you compare against the stored hash before flipping storage to fs. Run the batch again if anything mismatches. Keep the blob column in place until the whole table has been flipped and you have served traffic from the new backend for a while; dropping it is the last step, not the first.

Mind the headers and the edge cases

Two things bite people after the move. The first is Content-Type: the object store may not guess it from the extension, so set it explicitly on upload from the mime column. The second is Content-Disposition: if users download rather than view, set attachment; filename="..." so the browser does not rename the file to the token. Range requests matter for large media; confirm the store or proxy honours Range and returns 206 Partial Content, otherwise video seeking breaks and users notice.

Also decide what happens to deletes and overwrites. If a file is replaced, write a new token rather than overwriting the object, so cached URLs stay valid. Deletes should remove the row first, then the object, so a failed object delete leaves an orphan you can sweep later rather than a dangling link.

What to do next

Start by adding the files table and a resolver function, and route every file read through it while everything still points at the database. That change alone is safe and reversible. Then move one small batch to the filesystem, verify the checksums, and watch the logs for redirects and content types. Once a batch survives real traffic, scale the loop up and only then consider dropping the blob column.

Related articles

Subscribe to our newsletter

Get the latest hosting tips, performance insights, and industry news.