Build a Scalable Chunk-Based Storage Deduplication System
System DesignModel answerLast updated
Design an enterprise-grade deduplication storage service handling petabyte-scale data with content-addressed chunking, distributed indexing, and safe garbage collection.
You're tasked with architecting a storage service that eliminates duplicate data across large file repositories. The system must handle petabyte-scale workloads efficiently.
Your design should cover:
Core Architecture:
- How files are broken down, stored, and reconstructed
- Index and metadata organization
- API surface for upload, retrieval, and deletion operations
- Request flows for both storing and fetching data
Operational Robustness:
- Ensuring data consistency when operations fail or retry
- Safe removal of unused storage without risking data loss
- Handling corrupted or lost data
- Index partitioning and redistribution strategies
- Rolling out changes without downtime
Production Concerns:
- Observability: what metrics and alerts matter
- Cost management across compute, storage, and bandwidth
- Capacity forecasting approach
- Security and regulatory compliance (encryption, access controls, data residency)
- Protecting live traffic during maintenance operations
Think through the trade-offs at each layer. Where would you optimize for durability versus latency? How do you balance deduplication efficiency against complexity? What failure modes keep you up at night?
Hints
Hint 1
Break files into variable-size blocks using content-aware boundaries—this maximizes deduplication when files are edited
Hint 2
Don't rely on reference counting for cleanup in distributed systems; consider time-based marking approaches instead
Hint 3
The index needs to answer 'do we have this chunk?' at high throughput—think about how to shard and cache effectively
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Chunk-Based Deduplication Storage System
1. Requirements and Capacity Planning
First, establish concrete targets:
Functional scope:
- Store, retrieve, and remove files with sub-file deduplication
- Multi-tenant isolation with per-tenant deduplication boundaries
- Content-addressed storage to avoid redundant uploads
Scale parameters:
- 10 PB of logical data ingested
- Deduplication factor of 3:1 → ~3.3 PB physical storage
- Peak write throughput: 10 GB/s
- Read traffic: 30 GB/s (typical 3:1 read-to-write ratio)
- Target: 11-nines durability, 99.95% availability
Capacity calculations:
- Average chunk: 64 KB (using content-defined chunking, range 16-256 KB)
- Total unique chunks: 3.3 PB / 64 KB ≈ 50 billion chunks
- Index metadata: ~80 bytes per chunk (hash, location, timestamps) → 4 TB index
- Lookup throughput: 10 GB/s / 64 KB = 156K chunks/s
- Storage objects: group chunks into 64 MB packfiles → ~50 million packfiles
These numbers drive the architectural choices below.
2. API Design
The API enables clients to avoid uploading data the service already possesses:
POST /v1/sessions → {session_id}
POST /v1/sessions/{id}/check-exists {chunk_hashes: [...]} → {need_upload: [...]}
PUT /v1/sessions/{id}/data binary chunk batch
POST /v1/sessions/{id}/finalize {filename, chunk_list, metadata}
GET /v1/files/{id} → data stream (supports byte ranges)
DELETE /v1/files/{id}
GET /v1/files/{id}/info → metadata
Security principles:
- Server independently computes hashes of all received data—client hashes are hints only
- The check-exists endpoint respects tenant boundaries; knowing a hash doesn't grant access to content from another tenant
3. Data Organization
Chunk index (distributed key-value store like DynamoDB or Cassandra):
- Key:
(tenant_id, content_hash) - Value:
{packfile_id, byte_offset, size, status, last_referenced_time} - Partitioned by hash prefix for uniform distribution
File metadata (transactional database):
- Key:
file_id - Value:
{chunk_sequence: [(hash, size)], total_size, owner, permissions, upload_time, deletion_mark} - Must support atomic updates for consistency
Packfiles (object storage like S3):
- Immutable containers holding many chunks
- Header maps
content_hash → byte_rangefor rebuilding the index - Self-describing for disaster recovery
Packfile tracking:
- Metadata:
{packfile_id → bytes_active, bytes_total, creation_time} - Drives storage reclamation decisions
4. System Components and Data Flow
Architecture layers:
- Stateless API servers handling requests
- Chunking service (applies content-defined chunking algorithm like FastCDC)
- Distributed index tier, horizontally partitioned
- Pack assembly workers collecting chunks into packfiles
- Transactional metadata service
- Read cache (SSD-backed) for hot chunks
- Background workers: cleanup, compaction, integrity checks (isolated resource pools)
Upload workflow:
- Client chunks file content and hashes each piece with SHA-256
- Batch lookup against index using Bloom filters per partition to filter negatives cheaply
- Upload only chunks the service doesn't have
- Pack assembler buffers incoming chunks and writes complete packfiles to object storage
- After successful object write, index entries are created atomically
- File metadata record is committed in a transaction that also updates
last_referenced_timefor all chunks and validates that none are marked for deletion - If any chunk is marked for deletion, abort and force client to re-upload those chunks
Retrieval workflow:
- Fetch file metadata (cached aggressively)
- Batch-resolve chunk locations from index
- Merge adjacent chunks in the same packfile into single range requests
- Parallel fetch from object storage
- Verify hash of each chunk; on mismatch, try replica and alert
- Stream assembled file to client
Key invariant: Data exists in object storage before index entries point to it; index entries exist before any file metadata references them. Failures leave orphaned data (harmless) never dangling pointers.
5. Consistency and Safe Cleanup
Idempotency:
- Chunk writes are naturally idempotent due to content addressing
- Session creation/finalization uses idempotency tokens stored for 24 hours
- Retrying finalization returns the same file ID
Garbage collection strategy (avoiding reference counting):
Reference counting breaks under network partitions and retries. Instead, use snapshot-based mark-and-sweep:
- Snapshot phase: Capture consistent view of all live file metadata at time T
- Mark phase: Scan snapshot and build set of referenced chunks per index partition
- Candidate phase: Chunks absent from live set AND with
last_referenced_time < T - grace_period(e.g., 24h) transition toCANDIDATE_DELETE - Grace period: Wait another 24 hours
- Sweep phase: Delete candidates whose status and timestamp haven't changed; update packfile active-bytes count
The upload workflow prevents resurrection races: finalizing a file that references a deletion candidate fails atomically, forcing re-upload.
Storage compaction:
- Rewrite packfiles with <40% live data
- Copy live chunks to new packfile
- Atomically update index to point to new location
- Delay old packfile deletion beyond maximum cache TTL
- Budget-controlled to balance cost savings against egress/PUT charges
Fault isolation:
- Deploy in cells (independent index clusters, databases, and storage buckets)
- Assign tenants to cells to limit blast radius
- Separate resource quotas for foreground and background work
- Circuit breakers on object storage calls
Recovery mechanisms:
- Pack writers are stateless; crashes lose only uncommitted packfiles (cleaned after 7 days)
- Index can be reconstructed from packfile headers
- Cross-region async replication of packfiles and database
- Object storage versioning or delayed deletion to recover from bugs
- Regular restore testing (quarterly minimum)
6. Sharding and Operational Changes
Index partitioning:
- Partition by hash prefix—cryptographic hashes ensure uniform distribution
- Use consistent hashing with virtual nodes for smooth rebalancing
- Each partition sized for ~500 GB to balance parallelism and overhead
Partition migration:
- Add new owner to shard map; dual-write to old and new
- Background scan copies range with rate limiting
- Reads try new owner first, fall back to old
- Update shard map to remove old owner
- Delete old partition after safety window
Schema evolution:
- Version all data structures
- Add optional fields first, make required later
- Run dual-write periods when changing key structures
- Backfill data out-of-band with throttling
Deployment safety:
- Blue-green deployments with traffic shifting
- Feature flags for risky changes
- Gradual rollout: canary cells first, then broader
- Automated rollback on error rate spike
7. Observability and Cost Management
Critical metrics:
- Latency: p50/p90/p99 for uploads, downloads, and index lookups
- Throughput: GB/s in/out, requests/second
- Index hit rate and cache effectiveness
- Deduplication ratio (logical bytes / physical bytes)
- Background job lag: chunks awaiting cleanup, packfiles needing compaction
- Data integrity: hash mismatches, object fetch failures
Alerts:
- Upload/download error rate >0.1%
- Index lookup latency p99 >100ms
- Cleanup lag >48 hours
- Storage growth rate deviating from forecast
- Any hash verification failures
Cost controls:
- Storage: archival tier for cold data
- Compute: autoscale based on queue depth
- Network: regional affinity to reduce cross-region egress
- Capacity planning: model growth from upload rates and dedup ratios; provision 6 months ahead
SLO examples:
- 99.9% of uploads complete successfully
- 99.95% of downloads return correct data <500ms (p99)
- RPO <1 hour, RTO <4 hours for regional failures
8. Security and Compliance
Data protection:
- Encryption at rest (server-side) and in transit (TLS)
- Per-tenant encryption keys with key rotation
- Access control evaluated on every operation
- Audit logs for data access and deletion
Regulatory compliance:
- Data residency: pin tenants to geographic cells
- Right to deletion: hard delete after retention period
- Retention policies enforced at metadata layer
- GDPR/CCPA compliance through tenant isolation and deletion workflows
Privacy:
- Deduplication scoped per tenant by default to prevent cross-tenant inference
- Optional cross-tenant dedup for trusted environments (internal data lakes)
Common Pitfalls
- Using reference counts: Distributed refcounts drift and require complex repair; time-based marking is more robust
- Trusting client hashes: Always recompute server-side to prevent poisoning attacks
- Global deduplication: Enables proof-of-ownership attacks; scope to trust boundaries
- Synchronous GC: Background cleanup must not block uploads or risk consistency
- Small chunks: Index size and lookup overhead dominate; 64 KB is empirically balanced
- Ignoring pack fragmentation: Degrades read performance; compaction is essential