Contents
Why Store Images, Videos and Text in MinIO Instead of PostgreSQL?

Why Store Images, Videos and Text in MinIO Instead of PostgreSQL?

“Where should I store files: in the database or MinIO?”

I've faced this question a hundred times. Here is my answer.

Prologue: The problem

My journey through storage solutions has been educational.

Project 1 (2018): PostgreSQL BYTEA

Manager: “We need storage for screenshots!”

Me: “Easy, I'll put them in the database...”

A month later:

DBA: “Why is my database growing by 50GB a day?!”

Me: “Screenshots... My mistake.”

Project 2 (2019): Filesystem

Manager: “We need storage!”

Me: “Filesystem? Easy...”

Two months later:

DevOps: “The server's disk is full!”

Me: “Backup?”

DevOps: “File backup? It isn't automatic...”

Project 3 (2020): ownCloud

Manager: “We need enterprise storage!”

Me: “OK, ownCloud...”

Three weeks of setup and complex configuration. It worked, but was overkill for automated uploads.

Project 4 (2021): AWS S3 (SaaS)

Manager: “We need cloud storage!”

Me: “AWS S3?”

Two weeks waiting for AWS approval.

CFO: “How much does it cost?!”

Me: “Um... €500/month...”

It's a great solution, but costs add up.

Project 5 (2024): MinIO (on-premise)

Manager: “We need storage! On-premise!”

Me: “MinIO! Five-minute setup, S3-compatible, zero cost.”

Manager: “Perfect!”

The perfect balance: S3 API plus on-premise control!

A real-world scenario

Test automation generates each day:

  • 100 tests/day
  • 5 screenshots/test = 500 images/day (200KB each)
  • 20 videos/day (10MB each)
  • 1,000 log files/day (50KB each)
File typeDailyMonthlyYearly
Images100MB3GB36GB
Videos200MB6GB72GB
Logs50MB1.5GB18GB
Total350MB10GB120GB

Question: Where should we store it?

Chapter 1: Traditional solutions (and why they fail)

Solution 1: PostgreSQL BYTEA

AspectRating
Setup complexityLOW (just ALTER TABLE)
Setup time10 minutes
MaintenanceMEDIUM

Advantages: Simple, with no extra service; ACID transactions; backups included with the database; no separate authentication.

Disadvantages: Exploding database size, slow queries loading blobs, huge backup dumps, memory problems, and no optimization for large files.

Verdict: “Seems simple, becomes a nightmare.” The temptation is understandable:

sql
CREATE TABLE test_screenshots (
    id SERIAL PRIMARY KEY,
    test_id INTEGER,
    filename VARCHAR(255),
    content BYTEA,  -- Store the image here! Easy!
    content_type VARCHAR(100),
    created_at TIMESTAMP DEFAULT NOW()
);

-- Upload a screenshot:
INSERT INTO test_screenshots (test_id, filename, content, content_type)
VALUES (123, 'login.png', '\xDEADBEEF...', 'image/png');

-- Easy! What could go wrong?

Solution 2: Filesystem

AspectRating
Setup complexityLOW (mkdir /uploads)
Setup time5 minutes
MaintenanceHIGH (manual backups)

Advantages: Fast direct disk access, simple, no dependencies or extra cost.

Disadvantages: Limited to one server, no backup unless configured manually, no redundancy, difficult sharing across servers, path and permission problems.

Verdict: “OK for development, BAD for production.” Real problems:

bash
# Problem 1: Path hell
/var/uploads/test-123/screenshot.png           # Server 1
/home/jenkins/uploads/test-123/screenshot.png  # Server 2
C:\uploads\test-123\screenshot.png             # Windows

# Problem 2: How many files do we have?
find /uploads -type f | wc -l
# Output: 1,245,678 files

# How do I back up over 1M files?
rsync -avz /uploads backup:/uploads  # 6 hours!

# Problem 3: Full disk
df -h /uploads
# Output: 100% used

# Problem 4: Multiple servers behind a load balancer
# Server 1 has the files, server 2 does not = random 404s

Solution 3: ownCloud / Nextcloud

AspectRating
Setup complexityHIGH (docker-compose, Redis, MySQL, cron)
Setup time2–3 days
MaintenanceHIGH (updates, backups, monitoring)

Advantages: Web UI for manual uploads, user management, file sharing and versioning, desktop and mobile sync.

Disadvantages: Overkill for automated uploads, complex configuration, high resource use and slow API for bulk operations.

Verdict: “Excellent for team sharing, the wrong tool for automation.”

Solution 4: AWS S3 (SaaS)

AspectRating
Setup complexityMEDIUM (AWS account, IAM, policies)
Setup time2–3 days (approval process)
MaintenanceLOW (managed service)
CostHIGH (per GB and request)

Advantages: Virtually unlimited scaling, high availability (99.99%), built-in backup and CDN, standard S3 API, no maintenance.

Disadvantages: Costs, especially for dev/test; IAM complexity; approvals; data sovereignty concerns; no local deployment.

Verdict: “Perfect for production, but it depends on the SaaS versus on-premise strategy.”

Example costs for a test environment:

ItemUsageCost
Storage50GB$1.15
GET requests1M$0.40
PUT requests100K$0.50
Data transfer50GB$4.50
Monthly~$7
× 5 environments$35/month
Yearly$420

For test data!

Chapter 2: PostgreSQL BYTEA (and why NOT)

Problem 1: Database size explosion

sql
-- Before (without screenshots):
SELECT pg_size_pretty(pg_database_size('testdb'));
-- Output: 2 GB

-- After one month (with screenshots):
SELECT pg_size_pretty(pg_database_size('testdb'));
-- Output: 52 GB

1,000 tests × 30MB on average = 30GB just for screenshots!

Problem 2: Slow queries

sql
-- Query BEFORE screenshots:
SELECT * FROM test_results WHERE test_id = 123;
-- Execution time: 5ms

-- Query AFTER (JOIN loading blobs):
SELECT tr.*, ts.content  -- Loads a 5MB blob!
FROM test_results tr
LEFT JOIN test_screenshots ts ON ts.test_id = tr.test_id;
-- Execution time: 2500ms

PostgreSQL loads the ENTIRE blob into memory. Ten screenshots at 500KB each = 5MB loaded!

Problem 3: Backup nightmare

ScenarioBeforeAfter
pg_dump time2 minutes2 hours
Dump size100MB55GB
Restore time5 minutes4 hours
Weekly backup storage700MB385GB

Problem 4: Memory and connection problems

java
@Test
public void testLogin() {
    TestResult result = testRepository.findById(123);

    // This loads ALL screenshots into memory!
    List<Screenshot> screenshots = result.getScreenshots();

    // Each screenshot = 500KB
    // 10 screenshots = 5MB
    // 100 concurrent tests = 500MB RAM!
}
// OOM exception incoming!

Connection pool exhaustion:

  • A query loads a 5MB blob and holds a connection for 5+ seconds.
  • A pool of 20 connections can be exhausted in seconds.
  • Other queries time out.

The numbers

MetricImpact
Database size+60GB (30× increase)
Backup time2 minutes → 2 hours (60× slower)
Query time5ms → 2500ms (500× slower)
VACUUM time1 minute → 2 hours (120× slower)
Memory per operation+500MB

Verdict: “The database is for DATA, not FILES!”

Chapter 3: The MinIO solution (and why YES)

The right architecture

MinIO for files: Five-minute Docker setup, $0 self-hosted on-premise, cluster scalability and performance optimized for large files.

PostgreSQL for metadata: screenshot_id, test_id, filename, minio_path (s3://bucket/path), size and created_at.

┌──────────────────┐
│   PostgreSQL     │  ← Metadata only (tiny!)
│                  │
│  id: 123         │
│  path: "s3://test-screenshots/123.png"
│  size: 245KB     │
└────────┬─────────┘
         │ Reference (path only)
         ↓
┌──────────────────┐
│     MinIO        │  ← Actual files (large!)
│  (On-Premise)    │
│                  │
│  /test-screenshots/
│    ├─ 123.png    │
│    ├─ 124.png    │
│    └─ 125.mp4    │
└──────────────────┘

Implementation

java
@Entity
@Table(name = "test_screenshots")
public class TestScreenshot {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long testId;
    private String filename;
    private String minioPath;  // s3://bucket/path - NOT the contents!
    private Long fileSize;
    private String contentType;
    private LocalDateTime createdAt;

    // NO BYTEA field!
}

@Service
public class ScreenshotService {

    @Autowired
    private MinioClient minioClient;

    public TestScreenshot saveScreenshot(Long testId, MultipartFile file) {
        // 1. Upload to MinIO (file storage)
        String filename = generateFilename(testId, file.getOriginalFilename());
        String minioPath = uploadToMinio(file, filename);

        // 2. Save metadata to PostgreSQL (tiny record!)
        TestScreenshot screenshot = new TestScreenshot();
        screenshot.setTestId(testId);
        screenshot.setMinioPath(minioPath);  // Just a path string!
        screenshot.setFileSize(file.getSize());

        return repository.save(screenshot);  // Fast! Metadata only!
    }
}

The difference

sql
-- Table size BEFORE (with BYTEA):
SELECT pg_size_pretty(pg_total_relation_size('test_screenshots'));
-- Output: 48 GB

-- Table size AFTER (metadata only):
SELECT pg_size_pretty(pg_total_relation_size('test_screenshots'));
-- Output: 245 MB

-- That is 196× smaller!
MetricBefore (BYTEA)After (MinIO)Improvement
Table size48 GB245 MB196× smaller
Query time2500ms5ms500× faster

Chapter 4: Use case — test automation

Problem definition

Daily generationAmount
Tests500
Screenshots500 × 7 × 300KB = 1.05GB
Videos500 × 20MB = 10GB
Logs500 × 4 × 75KB = 150MB
Total/day~11.2GB
Monthly~336GB
Yearly~4TB

Storage required: YES! Database storage: NO!

The solution

1

Test starts:

Create a TestRun record in PostgreSQL (metadata only).
2

Test runs:

Create screenshots, record video and generate logs; upload each to MinIO and save its reference in PostgreSQL.
3

Test ends:

Update the TestRun status.

Queries are fast because they return only PostgreSQL metadata; files load on demand with MinIO streaming through presigned URLs.

Chapter 5: Performance comparison

Benchmark: 1,000 screenshots (300MB total)

Upload:

MetricPostgreSQL BYTEAMinIO
Time45 seconds8 seconds
Peak memory800MB100MB
Database growth+300MB+150KB (metadata)

Query (100 screenshots):

MetricPostgreSQL BYTEAMinIO
Query time8.5 seconds12ms + 1.2s (parallel downloads)
Data transferred30MB15KB (paths only)
Memory350MB2MB

Backup:

MetricPostgreSQL BYTEAMinIO + PostgreSQL
Backup time2h 15min15 minutes
Dump size52GB250MB + 50GB files

That is 9× faster!

One-year cost comparison

MetricPostgreSQL BYTEAMinIO + PostgreSQL
Database size4.2 TB2 GB
File storageN/A4 TB
Backup storage29.4 TB4 TB
Backup time/day8 hours20 minutes
Query time2–5 seconds5–10ms
Memory/query500MB+2–5MB
Hardware cost$40,000$3,000

Savings: $37,000!

Chapter 6: Best practices

DO

java
// 1. Store metadata in the DB, files in MinIO
@Entity
public class Document {
    private String minioPath;  // Path reference
    private Long fileSize;
    private String contentType;
    // NO byte[] content!
}

// 2. Use a presigned URL for temporary access
String url = minioService.getPresignedUrl(path, 3600);
response.redirect(url);  // Client downloads directly

// 3. Stream large files (do not load everything into memory)
InputStream stream = minioService.getObject(path);
// Stream to the response...

// 4. Organize files into buckets and folders
String path = String.format("test-screenshots/%d/%s/%s",
    testId, dateFolder, filename);

// 5. Set lifecycle policies (automatically delete old files)
// mc ilm add --expiry-days 90 local/test-screenshots/temp

DO NOT

java
// 1. Do not store files in the database
@Column(columnDefinition = "BYTEA")
private byte[] fileContent;  // NO!

// 2. Do not load all files into memory
List<byte[]> allFiles = new ArrayList<>();
for (Screenshot s : screenshots) {
    allFiles.add(s.getContent());  // OOM!
}

// 3. Do not use a filesystem across multiple servers
String path = "/var/uploads/" + filename;  // Does not scale!

// 4. Do not swallow upload errors
try {
    minioService.upload(file);
} catch (Exception e) {
    // File lost forever!
}

Chapter 7: Migration strategy

Step-by-step migration from PostgreSQL BYTEA

sql
-- 1. Add new columns
ALTER TABLE test_screenshots ADD COLUMN minio_path VARCHAR(500);
ALTER TABLE test_screenshots ADD COLUMN migrated BOOLEAN DEFAULT false;
java
// 2. Migration service (batch processing)
@Service
public class BlobMigrationService {

    public void migrateScreenshots() {
        List<Screenshot> batch = repository.findByMigratedFalse(100);

        for (Screenshot screenshot : batch) {
            // Upload to MinIO
            String minioPath = minioService.uploadBytes(
                screenshot.getContent(),
                String.format("test-screenshots/%d/%s",
                    screenshot.getTestId(),
                    screenshot.getFilename())
            );

            // Update the record
            screenshot.setMinioPath(minioPath);
            screenshot.setContent(null);  // Remove BYTEA
            screenshot.setMigrated(true);
            repository.save(screenshot);
        }
    }
}
sql
-- 3. After migration completes
ALTER TABLE test_screenshots DROP COLUMN content;
VACUUM FULL test_screenshots;  -- Reclaim space!

Conclusion

Decision matrix

Store in PostgreSQLStore in MinIO
Small data (<1KB)Large files (>100KB)
Frequently queriedBinary data
Needs transactionsMedia files
Structured dataLogs, backups

SaaS vs on-premise

Choose AWS S3 (SaaS) ifChoose MinIO (on-premise) if
Cloud-first strategyData sovereignty required
Global distribution requiredLower long-term costs
You do not want to manage infrastructureFull infrastructure control
Budget for recurring costsYou already have hardware

Hybrid approach: MinIO for dev/test and AWS S3 for production. Same API = same code!

Key takeaways

Database = Metadata (fast queries, small size)
├─ id: 123
├─ filename: "screenshot.png"
├─ path: "s3://bucket/123.png"  ← Reference only!
└─ size: 245KB

MinIO = Files (optimized storage, streaming)
└─ s3://bucket/123.png (245KB)  ← Actual file

Real results

MetricBefore (BYTEA)After (MinIO)
Database52GB2GB (26× smaller)
Backup time2 hours15 minutes (8× faster)
Query time2.5 seconds5ms (500× faster)
Memory/operation500MB2MB (250× less)
Hardware cost$40,000$3,000 (92% cheaper)

ROI: Priceless!


This article draws on years of experience with different storage solutions. Each approach had its place and taught me something. MinIO is currently my preferred on-premise object storage solution, while AWS S3 remains a top choice for a SaaS strategy.

P.S. The database is for DATA; MinIO/S3 is for FILES. Remember that!

P.P.S. An S3-compatible API means flexibility: develop on MinIO and deploy to AWS, or vice versa!

All articles