Back

Blog details

Should You Store Files in a Database or Object Storage?

AIOZ Network
8 min readNovember 13, 2026
aioz-storage
AIOZ Storage: Files in a Database or Object Storage?

In the database vs object storage choice for files, object storage should hold the bytes and your database should hold a row that points to them. Keep a file inside the database only when it is small, roughly under 256 KB, and changes together with its row.

TL;DR:

  • Keep file bytes in object storage and the metadata (owner, name, type, size, checksum, object key) in your database. Upload the object first, then commit the row.
  • Small files can live in a database: a Microsoft Research study found objects under 256 KB do best there, and objects over 1 MB do best outside it.
  • Large files in a database inflate backups, transaction logs and replicas, and they hit hard caps such as PostgreSQL's 1 GB field and MongoDB's 16 MiB document.
  • On AIOZ Storage the pattern works with any S3 SDK pointed at s3.aiozstorage.network, plus two client settings shown below.

Should You Store Files in a Database?

Sometimes, yes. A database is a fine home for files that are small, few in number and tied to a single row, such as an avatar thumbnail that must change in the same transaction as its record. You get one backup and one commit for both the file and its data.

The best-known measurement is still "To BLOB or Not To BLOB", a 2006 Microsoft Research report by Russell Sears, Catharine van Ingen and Jim Gray. They found that objects smaller than 256 KB are best stored in a database, while objects larger than 1 MB are best stored in a filesystem. Between those sizes, the read-to-write ratio and how often you overwrite objects decide the outcome. The study compared SQL Server 2005 with NTFS rather than with object storage, so treat its numbers as a starting point for your own tests.

Microsoft's SQL Server guidance lands in the same place. Its FILESTREAM page suggests storing data outside the table when objects are, on average, larger than 1 MB, and notes that smaller objects often stream better as BLOBs inside the database.

Hard limits settle the question for big files. PostgreSQL caps any single field at 1 GB. MongoDB caps a document at 16 MiB, and beyond that you need GridFS, which splits a file into 255 KiB chunks and does not support multi-document transactions. So the one atomic commit you wanted is gone at exactly the sizes where it would matter.

Size scale for storing a file in a database or object storage: under 256 KB a database is fine, 256 KB to 1 MB depends on reads, writes and overwrites, over 1 MB store it outside the database; MongoDB's 16 MiB document cap and PostgreSQL's 1 GB field cap marked

Where Large Files Hurt a Database

The trouble rarely shows up on the first insert. It appears in everything the database does around your data, and Brent Ozar's 2021 post on the subject covers the first three of these:

  • Backups grow and slow down. Every full backup copies every file again, and each new file version also passes through the transaction log, so your log backups grow too.
  • Replicas carry the same bytes. Each replica stores and replays every file, which makes high availability and disaster recovery slower and more expensive to run.
  • Old versions pile up. Users soon want every past version of a document, and each copy adds to the database you have to back up and restore.
  • Housekeeping still applies. PostgreSQL moves values over about 2 kB out of the main table (its TOAST mechanism), but they are still logged to the WAL and vacuumed like any other data.
  • Every download goes through your app. A browser can't fetch a row directly, so each download costs you an app request and a database connection for the whole transfer.

Database vs Object Storage: How Do They Compare for Files?

Here are the two side by side for storing files. Most applications end up using both, each for the part it handles well.

Database (BLOB or bytea column)Object storage
Built forSmall structured values, queries and transactionsWhole files addressed by a key
Size ceiling1 GB per PostgreSQL field; 16 MiB per MongoDB documentFiles in the gigabytes, uploaded in parts
TransactionsFile and row commit togetherNo shared transaction with your database; you order the writes
Finding filesSQL over any metadata columnListing by key prefix only
BackupsFiles ride along in every backup and replicaProtected separately, so your database stays small
DeliveryThrough your app serverStraight to the browser with a presigned or public URL
What you pay forDatabase disk, memory and replicasGB-months stored plus data downloaded

Can the database itself run on object storage? Not as its main disk, because a database rewrites small pages all the time. Our guide to object, block and file storage explains why databases belong on block volumes.

You store the object key in the row. That key is the name a bucket uses to find the file, as our guide to how S3 object storage works explains. The row also keeps whatever you need to search, authorize and verify the file: owner, original file name, content type, size and a SHA-256 checksum. The bytes sit in a bucket under that key, and nothing else about the file needs to live in the database.

Diagram of the metadata plus object pattern: the app uploads file bytes to an AIOZ Storage bucket, then inserts a row with the object key, owner, name, type, size and checksum into the database; on download the app reads the row, checks the owner and returns a presigned URL so the browser fetches the bytes straight from the bucket

The order of the writes matters, because the two systems can't share a transaction:

  1. Make a key you never reuse. Build it from your own ID, for example files/<owner>/<id>, so one upload can never overwrite another.
  2. Upload the bytes first. If the upload fails, no row points at a missing file.
  3. Commit the row second. If the commit fails, you are left with an orphan object, which a cleanup job can find by listing keys that have no row.
  4. Read through the row. Look the row up, check that the caller owns it, then return a short-lived presigned URL so the browser downloads straight from storage.

Deletes run the other way: remove the row, then the object, and let the same cleanup job catch any object left behind. Your database stays the source of truth for which files exist. Object storage listings only filter by key prefix, so a question like "this user's PDFs from last month" has to be answered by your table.

How AIOZ Storage Handles It

AIOZ Storage is S3-compatible object storage, so you can build this pattern with the AWS SDKs you already know. We protect each object with Reed-Solomon erasure coding across the AIOZ DePIN network. Here is a minimal table for the metadata, written for SQLite:

CREATE TABLE files (
  id           TEXT PRIMARY KEY,
  owner_id     TEXT NOT NULL,
  object_key   TEXT NOT NULL UNIQUE,
  file_name    TEXT NOT NULL,
  content_type TEXT NOT NULL,
  size_bytes   INTEGER NOT NULL,
  sha256       TEXT NOT NULL,
  created_at   TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);

And here is the upload and download logic with boto3, following the order above:

import hashlib
import sqlite3
import uuid

import boto3
from botocore.config import Config

s3 = boto3.client(
    "s3",
    region_name="us-east-1",
    endpoint_url="https://s3.aiozstorage.network",
    aws_access_key_id="<your-access-key-id>",
    aws_secret_access_key="<your-secret-access-key>",
    config=Config(
        signature_version="s3v4",
        request_checksum_calculation="when_required",
        response_checksum_validation="when_required",
        s3={"addressing_style": "path"},
    ),
)
db = sqlite3.connect("app.db")
BUCKET = "user-files"


def save_file(owner_id, file_name, data, content_type):
    file_id = uuid.uuid4().hex
    key = f"files/{owner_id}/{file_id}"
    # 1. Bytes first, under a key that is never reused.
    s3.put_object(Bucket=BUCKET, Key=key, Body=data, ContentType=content_type)
    # 2. Then the row that points to them.
    with db:
        db.execute(
            "INSERT INTO files (id, owner_id, object_key, file_name,"
            " content_type, size_bytes, sha256) VALUES (?, ?, ?, ?, ?, ?, ?)",
            (file_id, owner_id, key, file_name, content_type,
             len(data), hashlib.sha256(data).hexdigest()),
        )
    return file_id


def download_link(file_id, owner_id):
    row = db.execute(
        "SELECT object_key FROM files WHERE id = ? AND owner_id = ?",
        (file_id, owner_id),
    ).fetchone()
    if row is None:
        return None  # no such file for this user
    return s3.generate_presigned_url(
        "get_object", Params={"Bucket": BUCKET, "Key": row[0]}, ExpiresIn=600
    )

The endpoint, the us-east-1 region and path-style addressing come from AIOZ's Python SDK and CLI pages. We added the two when_required settings because AIOZ Storage needs a Content-Length header on uploads, and boto3 1.36.0 and later sends uploads chunked by default (we confirmed this on Oct 19, 2026). Path style matters because <bucket>.s3.aiozstorage.network has no DNS record. The s3v4 setting gives you standard SigV4 presigned URLs.

The 600-second expiry matches AIOZ's file manager tutorial, which also uploads with put and hands back presigned download links but keeps no database of its own. We ran the SQL in SQLite and compiled the Python on Oct 29, 2026. The upload itself is untested, because our test machine has no AIOZ Storage credentials.

Three more details shape the design. If you leave out ContentType, AIOZ Storage detects the MIME type from the file's content and stores it as object metadata, though keeping the type in your row saves a request later. The docs set a default rate limit of 100 requests per second, so batch your cleanup job's listings and deletes. Storage costs 0.017 USD per GB per month, charged hourly, plus 0.005 USD per GB downloaded, paid from a prepaid balance.

To try the pattern end to end, create an access grant with S3 credentials and follow AIOZ's file manager tutorial, then add the table above.

FAQ

Is it bad practice to store images in a database?

Not for a handful of small images tied to one row each. It becomes a problem once images are large or numerous, because every backup, replica and restore then carries them.

What is the largest file PostgreSQL can store in a bytea column?

A single field is capped at 1 GB. PostgreSQL's separate large object feature allows values up to 4 TB, but those still live inside the database and its backups.

How do you keep files and rows consistent without a shared transaction?

Upload the object first and commit the row second, and use keys you never reuse. A periodic cleanup job then deletes objects that no row points to.

Should you store the presigned URL in the database?

No. Store the object key and generate a fresh URL on each request, because presigned URLs expire. AIOZ Storage rejects SigV4 URLs set to last longer than 7 days.

Is object storage slower than a database for tiny files?

Each object read is a separate HTTP request, so thousands of tiny values can cost more time and more requests than one query. That is the case where keeping small values in the database still wins.

References

We only send updates when meaningful changes ship, and you can unsubscribe anytime

Related Content

blog thumbnail

Full vs Incremental vs Differential Backup Types Explained

Full vs incremental vs differential backup: what each run copies, how restore chains work, storage and time trade-offs, synthetic fulls and RPO/RTO fit.

aioz-storage
8 min readDecember 04, 2026
blog thumbnail

RAID vs Erasure Coding: Two Ways to Survive Disk Failure

RAID vs erasure coding: RAID guards the disks of one array, while erasure coding spreads k data and m parity pieces over nodes. Compare overhead and rebuilds.

aioz-storage
9 min readDecember 01, 2026
blog thumbnail

What Is Reed-Solomon Coding? The Math Behind Erasure Codes

Reed-Solomon coding turns k data pieces into n, and any k of them rebuild the original. See the polynomial math, GF(2^8), a demo and how AIOZ Storage uses it.

aioz-storage
7 min readNovember 27, 2026
blog thumbnail

RPO vs RTO Explained, With Backup and Restore Examples

RPO vs RTO: RPO caps how much data you can lose, RTO caps how long you can stay down. See how to calculate both, MTD, and the DR strategies that meet them.

aioz-storage
7 min readNovember 24, 2026
blog thumbnail

What Is AWS Signature Version 4? How S3 Requests Are Signed

AWS Signature Version 4 signs each S3 request with an HMAC key derived from your secret. See the four steps, a worked example and the errors that break it.

aioz-storage
7 min readNovember 20, 2026
blog thumbnail

Encryption at Rest vs in Transit, and What Each Protects

Encryption at rest vs in transit: at rest guards stored bytes from stolen disks, in transit guards requests on the network with TLS. See what each one misses.

aioz-storage
7 min readNovember 17, 2026