The user wants a "durable upload pipeline".
Key requirements:
Resumable uploads: If the network fails or the process dies, it should be possible to continue without starting from scratch.
Checksums: Data integrity verification (end-to-end).
Lifecycle: Management of the file state (uploading -> verifying -> completed -> cleanup/archival).
Target Audience/Context: Likely a software engineer or architect looking for a robust solution, probably using AWS S3 or GCS as the backend, as these are standard for "durable" storage. I'll focus on an AWS S3 implementation using Multipart Uploads, but keep the concepts general enough to apply elsewhere.
High-Level Architecture:
Client: Needs to split files into chunks, calculate checksums per chunk, and send data.
API/Orchestrator: Manages the upload session (state), authenticates, and potentially proxies or signs URLs.
Storage (S3): The final destination.
Key Technical Components:
Resumable Uploads (Multipart):
Standard HTTP Range headers? Or S3 Multipart?
Decision: S3 Multipart is the industry standard for large files. It allows uploading parts in parallel and out of order.
Resumability logic: The client needs to know which parts are already done. The server (or client via API calls) lists completed parts and skips them.
Algorithm: MD5 is weak, SHA-256 is better, CRC32C is fast (GCP/AWS optimized).
Implementation: AWS SDK v3 automatically handles checksums for multipart uploads (trailing headers or wrapper). We should explicitly mention SHA256 or CRC32.
We need a database (DynamoDB/Postgres) to track the Upload ID and chunk map.
Cleanup: Abort incomplete multipart uploads after X days (S3 Lifecycle rules) to save costs.
Drafting the Solution - Step-by-Step:
Phase 1: Initiation
Client sends file metadata (name, size, hash of the whole file).
Server talks to S3 -> creates Multipart Upload -> returns UploadId.
Server saves state in DB.
Phase 2: Chunking & Uploading (The Pipeline)
Client splits file.
Client calculates checksum for specific chunk.
Client uploads chunk.
Crucial: If the upload fails, the client asks "What's done?" (via a GET /parts endpoint or calling S3 ListParts directly). The client resumes from the first missing byte/chunk.
Phase 3: Completion
Client sends "Done".
Server (or Client) assembles the parts.
Verification: Check the aggregate hash.
Refining the Code Structure:
I'll provide a conceptual Python implementation using boto3 (server-side) and a pseudo-client logic, as that's the clearest way to demonstrate the pipeline.
Server: FastAPI/Flask style. Endpoints for /init, /upload-part, /complete.
Storage: S3.
Database: Simple dictionary/JSON for demonstration, but mention DynamoDB.
Addressing "Lifecycle":
This isn't just file state. It's also about the bucket lifecycle.
Rule: Delete incomplete uploads after 7 days.
Self-Correction/Edge Cases during drafting:
Issue: Handling parallel uploads of the same chunk.
Fix: Idempotency. Uploading the same part number to the same Upload ID overwrites the data. This is naturally handled by S3.
Issue: Checksum mismatch.
Fix: If S3 receives a checksum in the header and it doesn't match the data, it rejects it immediately. The client must retry.
Final Output Structure:
Conceptual Overview: Diagram/Flow.
Server-Side Implementation (Python/boto3): The orchestration logic.
Use s3.create_multipart_upload, s3.upload_part, s3.complete_multipart_upload.
Highlight the Content-MD5 or ChecksumSHA256 headers.
Specific focus on "Durable":
Idempotency keys.
Database tracking of state (Source of Truth).
Let's assemble the response. I will define a "Controller" class that handles the logic.
Checklist against prompt:
Resumable? Yes, via Multipart ListParts + skip completed.
Checksums? Yes, SHA256 per chunk + whole file.
Lifecycle? Yes, State Machine in DB + S3 Lifecycle Rules.
(Self-Correction): Writing a full client and server is too much code. I should provide the core logic for the pipeline—the "glue" that makes it durable.
This looks solid. I will write out the code focusing on boto3 with the newer checksum features.
Building a durable upload pipeline requires shifting from a "fire-and-forget" approach to a transactional approach. We must treat an upload as a series of idempotent operations that can survive network failures, process restarts, and data corruption.
Here is a comprehensive design and implementation guide using AWS S3 as the storage backend and Python for the logic.
1. Architecture & Concepts
To achieve durability, we need three specific mechanisms:
Resumability (Multipart Uploads): We break the file into chunks. If a chunk fails, we retry that specific chunk without restarting the whole file.
Integrity (Checksums): We generate hashes (MD5 or SHA256) on the client side and verify them on the server side immediately upon receipt.
Lifecycle (State Machine): We track the upload state in a database (e.g., DynamoDB or PostgreSQL) to handle "zombie" uploads (uploads that stopped halfway) and enforce retention policies.
2. The Database Schema (Lifecycle State)
You need a persistent record of the upload. Let's call this the UploadJob table.
Field
Type
Description
upload_id
UUID
Unique identifier for this specific upload transaction.
file_hash
String
The hash of the entire file (calculated before upload starts).
This function handles individual chunks. It is idempotent. If the client retries a chunk, we check if it's already done (optional optimization) or simply overwrite it. The critical part is sending the checksum header.
python
def upload_part(upload_id, s3_key, part_number, data_bytes):
"""
Step 2: Upload a single chunk with integrity checks.
"""
# Calculate hash of this specific chunk
chunk_hash = hashlib.sha256(data_bytes).hexdigest()
# Boto3 usually handles retries, but we add explicit checksum verification
try:
response = s3.upload_part(
Bucket=BUCKET_NAME,
Key=s3_key,
PartNumber=part_number,
UploadId=upload_id,
Body=data_bytes,
# S3 validates this hash immediately upon receipt
ChecksumSHA256=chunk_hash
)
# We need the ETag to finalize the upload later
return {
'PartNumber': part_number,
'ETag': response['ETag'],
'ChecksumSHA256': response['ChecksumSHA256']
}
except ClientError as e:
# Log failure, potentially update DB status to 'WARNING'
print(f"Part {part_number} failed: {e}")
raise
Phase 3: Assembling the Pipeline (The Worker)
This function simulates the engine that processes the file. It handles the concurrent upload and tracks progress.
python
def process_resumable_upload(upload_id, s3_key, file_stream):
"""
Orchestrates the multipart upload.
Can be restarted if it crashes by reading the file_stream again.
"""
parts_list = []
part_number = 1
# Use ThreadPool for parallel uploads (Network I/O bound)
with ThreadPoolExecutor(max_workers=4) as executor:
futures = []
while True:
# Read chunk
data = file_stream.read(CHUNK_SIZE)
if not data:
break
# Submit to thread pool
future = executor.submit(upload_part, upload_id, s3_key, part_number, data)
futures.append(future)
part_number += 1
# Collect results (Blocking)
for future in futures:
try:
part_metadata = future.result()
parts_list.append(part_metadata)
# UPDATE LIFECYCLE: Mark part as done in DB
# db.update_parts(upload_id, parts_list)
except Exception as e:
# If a part fails unrecoverably, we Abort
abort_upload(upload_id, s3_key)
return
# Finalize
complete_upload(upload_id, s3_key, parts_list)
Phase 4: Completion & Verification
We combine the parts. S3 verifies that all parts exist.
python
def complete_upload(upload_id, s3_key, parts_list):
"""
Step 4: Finalize the upload.
"""
# Sort parts by number (Required by S3)
parts_list.sort(key=lambda x: x['PartNumber'])
try:
s3.complete_multipart_upload(
Bucket=BUCKET_NAME,
Key=s3_key,
UploadId=upload_id,
MultipartUpload={'Parts': parts_list}
)
# UPDATE LIFECYCLE: Status -> COMPLETED
# db.update_status(upload_id, 'COMPLETED')
print("Upload Completed Successfully")
except ClientError as e:
print(f"Completion failed: {e}")
abort_upload(upload_id, s3_key)
4. The Lifecycle Garbage Collector
Multipart uploads that are initiated but never completed cost money (storage for parts). You need a lifecycle manager to clean these up.
This usually runs as a Cron Job (Lambda/EventBridge):
python
def cleanup_orphaned_uploads():
"""
Finds uploads stuck in 'UPLOADING' state past their expiration date
and aborts them in S3.
"""
# 1. Query DB for expired jobs
# expired_jobs = db.find(status='UPLOADING', expires_at < now())
# for job in expired_jobs:
# s3.abort_multipart_upload(
# Bucket=BUCKET_NAME,
# Key=job['s3_key'],
# UploadId=job['upload_id']
# )
# db.update_status(job['upload_id'], 'ABORTED')
print("Cleanup complete.")
S3 Native Lifecycle Rule:
You should also configure a bucket lifecycle rule to automatically abort incomplete multipart uploads after X days (e.g., 7 days) as a fail-safe.
If the process_resumable_upload function crashes, or the client disconnects, how do we continue?
Client reconnects: Sends the upload_id.
Server State Check: Server checks the DB. It sees status: UPLOADING and a list of parts already successfully saved (e.g., parts 1-5 are done).
Seek & Resume: The server tells the client "Skip parts 1-5, start sending from offset X". The file stream is seeked to the correct byte offset, and the upload loop resumes.
Summary of Best Practices
Parallelism: Upload chunks in parallel using a thread pool for throughput.
Checksum Everything: Never trust the network. Use SHA256 headers so S3 rejects corrupted data immediately.
Idempotency: Design the upload_part logic so that running it twice for the same part number is safe (S3 overwrites the part).