Written on 14th April 2026 by Carter Phan.
Nhiều user upload cùng 1 file (same content)
→ hệ thống lưu nhiều bản giống nhau
→ tốn storage + bandwidth
Goal:
Same file → chỉ lưu 1 lần
Dùng content-based deduplication (hash) để xác định file giống nhau
Upload file
↓
Compute hash (SHA256)
↓
Check DB:
├── Exist → reuse
└── Not exist → store file
id
hash (UNIQUE)
storage_path
size
user_id
file_id
Nhiều user → cùng 1 file
1. Upload file (temp storage / S3)
2. Compute hash
3. Try insert (UNIQUE hash)
├── Success → new file
└── Fail → file đã tồn tại
4. Link user → file
User A upload
User B upload cùng lúc
→ cả 2 chưa thấy file
→ duplicate insert ❌
UNIQUE(hash)
⇒ DB đảm bảo chỉ có 1 bản
Try insert
→ nếu fail (duplicate)
→ fetch existing file
lock:file_hash
⇒ Giảm race nhưng không thay thế DB constraint
files:
ref_count
ref_count = 0 → xóa file
Nếu tồn tại → skip upload
File → chunk1 + chunk2 + chunk3
⇒ Resume upload + optimize bandwidth
→ race condition
→ duplicate data
→ waste bandwidth
Do
Don’t