Contents
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 type | Daily | Monthly | Yearly |
|---|---|---|---|
| Images | 100MB | 3GB | 36GB |
| Videos | 200MB | 6GB | 72GB |
| Logs | 50MB | 1.5GB | 18GB |
| Total | 350MB | 10GB | 120GB |
Question: Where should we store it?
Chapter 1: Traditional solutions (and why they fail)
Solution 1: PostgreSQL BYTEA
| Aspect | Rating |
|---|---|
| Setup complexity | LOW (just ALTER TABLE) |
| Setup time | 10 minutes |
| Maintenance | MEDIUM |
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:
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
| Aspect | Rating |
|---|---|
| Setup complexity | LOW (mkdir /uploads) |
| Setup time | 5 minutes |
| Maintenance | HIGH (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:
# 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 404sSolution 3: ownCloud / Nextcloud
| Aspect | Rating |
|---|---|
| Setup complexity | HIGH (docker-compose, Redis, MySQL, cron) |
| Setup time | 2–3 days |
| Maintenance | HIGH (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)
| Aspect | Rating |
|---|---|
| Setup complexity | MEDIUM (AWS account, IAM, policies) |
| Setup time | 2–3 days (approval process) |
| Maintenance | LOW (managed service) |
| Cost | HIGH (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:
| Item | Usage | Cost |
|---|---|---|
| Storage | 50GB | $1.15 |
| GET requests | 1M | $0.40 |
| PUT requests | 100K | $0.50 |
| Data transfer | 50GB | $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
-- 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 GB1,000 tests × 30MB on average = 30GB just for screenshots!
Problem 2: Slow queries
-- 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: 2500msPostgreSQL loads the ENTIRE blob into memory. Ten screenshots at 500KB each = 5MB loaded!
Problem 3: Backup nightmare
| Scenario | Before | After |
|---|---|---|
| pg_dump time | 2 minutes | 2 hours |
| Dump size | 100MB | 55GB |
| Restore time | 5 minutes | 4 hours |
| Weekly backup storage | 700MB | 385GB |
Problem 4: Memory and connection problems
@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
| Metric | Impact |
|---|---|
| Database size | +60GB (30× increase) |
| Backup time | 2 minutes → 2 hours (60× slower) |
| Query time | 5ms → 2500ms (500× slower) |
| VACUUM time | 1 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
@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
-- 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!| Metric | Before (BYTEA) | After (MinIO) | Improvement |
|---|---|---|---|
| Table size | 48 GB | 245 MB | 196× smaller |
| Query time | 2500ms | 5ms | 500× faster |
Chapter 4: Use case — test automation
Problem definition
| Daily generation | Amount |
|---|---|
| Tests | 500 |
| Screenshots | 500 × 7 × 300KB = 1.05GB |
| Videos | 500 × 20MB = 10GB |
| Logs | 500 × 4 × 75KB = 150MB |
| Total/day | ~11.2GB |
| Monthly | ~336GB |
| Yearly | ~4TB |
Storage required: YES! Database storage: NO!
The solution
Test starts:
Test runs:
Test ends:
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:
| Metric | PostgreSQL BYTEA | MinIO |
|---|---|---|
| Time | 45 seconds | 8 seconds |
| Peak memory | 800MB | 100MB |
| Database growth | +300MB | +150KB (metadata) |
Query (100 screenshots):
| Metric | PostgreSQL BYTEA | MinIO |
|---|---|---|
| Query time | 8.5 seconds | 12ms + 1.2s (parallel downloads) |
| Data transferred | 30MB | 15KB (paths only) |
| Memory | 350MB | 2MB |
Backup:
| Metric | PostgreSQL BYTEA | MinIO + PostgreSQL |
|---|---|---|
| Backup time | 2h 15min | 15 minutes |
| Dump size | 52GB | 250MB + 50GB files |
That is 9× faster!
One-year cost comparison
| Metric | PostgreSQL BYTEA | MinIO + PostgreSQL |
|---|---|---|
| Database size | 4.2 TB | 2 GB |
| File storage | N/A | 4 TB |
| Backup storage | 29.4 TB | 4 TB |
| Backup time/day | 8 hours | 20 minutes |
| Query time | 2–5 seconds | 5–10ms |
| Memory/query | 500MB+ | 2–5MB |
| Hardware cost | $40,000 | $3,000 |
Savings: $37,000!
Chapter 6: Best practices
DO
// 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/tempDO NOT
// 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
-- 1. Add new columns
ALTER TABLE test_screenshots ADD COLUMN minio_path VARCHAR(500);
ALTER TABLE test_screenshots ADD COLUMN migrated BOOLEAN DEFAULT false;// 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);
}
}
}-- 3. After migration completes
ALTER TABLE test_screenshots DROP COLUMN content;
VACUUM FULL test_screenshots; -- Reclaim space!Conclusion
Decision matrix
| Store in PostgreSQL | Store in MinIO |
|---|---|
| Small data (<1KB) | Large files (>100KB) |
| Frequently queried | Binary data |
| Needs transactions | Media files |
| Structured data | Logs, backups |
SaaS vs on-premise
| Choose AWS S3 (SaaS) if | Choose MinIO (on-premise) if |
|---|---|
| Cloud-first strategy | Data sovereignty required |
| Global distribution required | Lower long-term costs |
| You do not want to manage infrastructure | Full infrastructure control |
| Budget for recurring costs | You 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 fileReal results
| Metric | Before (BYTEA) | After (MinIO) |
|---|---|---|
| Database | 52GB | 2GB (26× smaller) |
| Backup time | 2 hours | 15 minutes (8× faster) |
| Query time | 2.5 seconds | 5ms (500× faster) |
| Memory/operation | 500MB | 2MB (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!