Imagine a video creator uploading a 4 GB recording over a mobile connection. At 95% the network drops. Restarting the entire upload wastes time, bandwidth and battery. A resumable upload system lets the client retry only missing parts, while keeping incomplete or unsafe objects invisible to other users. This tutorial designs a fictional media platform using direct multipart object storage uploads, durable sessions and asynchronous validation.
Conceptual workflow: the client uploads parts directly to storage using URLs issued by the API; part sizes are configurable.
Requirements and scope
Support initiating an upload, uploading independent parts, discovering progress, completing an upload and canceling it. The client must survive network loss and application restarts. The server must enforce ownership, size limits and quotas. Completed objects become downloadable only after validation. Exclude video transcoding internals from the core design, but provide a durable event for downstream processing.
RequirementMechanismResume after disconnectDurable session and part listingLarge objectsMultipart object storageIntegrityPart and object checksumsSecurityScoped short-lived signed URLsCleanupExpiry worker and storage lifecycle rules
Capacity estimation
Assume 100,000 uploads daily, averaging 200 MB. That is 20 TB of ingress per day, or approximately 231 MB/s on average using decimal units. A tenfold burst reaches 2.31 GB/s. With 16 MiB parts, an average 200 MB upload needs about 12 parts. That yields roughly 1.2 million part uploads daily. These are planning assumptions rather than measured production traffic. The important implication is that application servers should not proxy every byte unless policy requires it.
Architecture evolution
A basic server accepts a single HTTP request and writes a local file. This is easy to implement but loses progress on failure and couples storage to a particular host. Shared object storage solves host dependence, but proxying all bytes still consumes application bandwidth. The next design separates the control plane from the data plane: the API manages sessions and authorization while clients send parts directly to object storage. Add a durable completion workflow and asynchronous scanning to make the system production-ready.
High-level design
The client calls the upload API with file metadata. The API creates a session and initiates multipart storage under a server-generated object key. It returns short-lived signed URLs for a bounded set of part numbers. The client uploads parts concurrently and records their identifiers. On reconnect it queries the session and reconciles with the authoritative storage part listing. Completion is coordinated by a worker, which verifies the manifest and finalizes the object. A scanner checks the quarantined object before a metadata transaction marks it available.
ComponentResponsibilityUpload APIAuthorization, quotas, session managementObject storageDurable parts and completed objectsMetadata databaseOwnership, state, expected size and expiryCompletion workerReconcile and finalize multipart uploadScannerValidate content and malware policyCleanup workerAbort expired multipart uploads
Keep the object private throughout this process. A download API checks that the metadata state is AVAILABLE before issuing a signed read URL. This avoids exposing partially uploaded or unvalidated files even if storage finalization happens before metadata publication.
Low-level API design
EndpointBehaviorPOST /uploadsCreate session with idempotency keyPOST /uploads/{id}/parts/signIssue URLs for requested part numbersGET /uploads/{id}Return state and paginated progressPOST /uploads/{id}/completeAccept ordered part manifest; return 202DELETE /uploads/{id}Request cancellation
POST /uploads
Idempotency-Key: video-2026-001
{“filename”:”demo.mp4″,”size”:4194304000}
201 Created
{“upload_id”:”u123″,”part_size”:16777216,
“state”:”UPLOADING”}
A repeated initiation key must return the same logical session when the request payload matches. Reject conflicting payloads under the same key. The API derives object keys from tenant and session identifiers, never directly from untrusted filenames. Validate requested part numbers against the expected size and provider limits. Sign only the intended method, object and part; bind checksum headers when supported.
Metadata and state machine
CREATE TABLE upload_sessions (
id uuid PRIMARY KEY,
tenant_id text NOT NULL,
request_key text NOT NULL,
object_key text NOT NULL UNIQUE,
storage_upload_id text,
expected_size bigint NOT NULL CHECK(expected_size > 0),
part_size integer NOT NULL,
state text NOT NULL,
expires_at timestamptz NOT NULL,
version bigint NOT NULL DEFAULT 0,
UNIQUE(tenant_id, request_key)
);
Use states INITIATING, UPLOADING, FINALIZING, SCANNING, AVAILABLE, FAILED and ABORTED. Persist the session before calling storage initiation; if a crash creates an orphan multipart upload, lifecycle cleanup bounds its lifetime. A conditional transition from UPLOADING to FINALIZING prevents two completion workers from independently accepting different manifests. Store the accepted manifest durably alongside the transition. Cancellation must compete through the same state machine; once finalization starts, return the current state rather than racing an abort against completion.
Client retry and resume algorithm
def upload_missing_parts(file, session, remote_parts):
for number, chunk in iter_chunks(file, session.part_size):
checksum = sha256(chunk).hexdigest()
if remote_parts.get(number) == checksum:
continue
url = request_signed_url(session.id, number, checksum)
retry_with_backoff(lambda: put_part(url, chunk))
return request_completion(session.id)
This is illustrative Python pseudocode: helpers must handle bounded parallelism, expired URLs, checksum formats and transient errors. The remote part map must contain verified checksums, not merely ETags assumed to be hashes. If a provider does not expose suitable checksums, re-upload uncertain parts or reconcile through its documented integrity mechanism. A retry of the same part number replaces that part in common multipart APIs, so prevent simultaneous writes of different bytes to one part. The client should verify that the local file has not changed since the session began.
Completion and crash recovery
Object storage completion and the metadata database are not one atomic transaction. A worker can successfully finalize the object and crash before updating the session. On retry, inspect the expected object key, version, size and integrity metadata. If the expected object already exists, reconcile the session instead of starting a second upload. If the provider reports a missing multipart session and no valid object exists, retry reconciliation or fail explicitly. Use a unique object key per logical upload and prohibit unrelated overwrites.
After finalization, move to SCANNING and persist a durable work item in the same database transaction. A transactional outbox or database-backed job queue avoids losing the scan request. Scanner retries must be idempotent. Only a successful scan and verified size allow the AVAILABLE transition. Reject or quarantine unsafe objects according to retention policy.
Scaling and tradeoffs
ApproachBenefitCostProxy uploadsCentral inspection and simple clientsHigh application bandwidthDirect multipartScalable data plane and independent retriesMore client and signing complexityResumable offset protocolSimple sequential progressLess natural parallelismSmaller partsLess retransmissionMore requests and metadataLarger partsFewer requestsMore memory and retry cost
Choose part size based on maximum object size, provider part limits and client memory. For example, 16 MiB parts require 256 parts for a 4 GiB file. Bound concurrency to perhaps four parts initially and adapt to measured throughput. Avoid loading an entire file into memory. A client with four 16 MiB buffers already needs about 64 MiB before overhead. Use streaming where possible. Scale API replicas independently of storage bandwidth, and rate-limit URL issuance to avoid uncontrolled resource consumption.
Failure scenarios
FailureRecoveryNetwork disconnectList uploaded parts and resumeSigned URL expiresAuthorize and sign a fresh URLDuplicate completionReturn durable state or reconcile objectWorker crashes after finalizationVerify object and advance metadataScanner unavailableKeep object private and retryAbandoned uploadAbort through expiry and lifecycle cleanup
Quota enforcement needs more than checking current storage usage. Reserve expected bytes when creating a session and release the reservation when canceled or failed. Reconcile actual completed size before converting reserved quota into consumed quota. Signed upload URLs may not enforce every declared size constraint on every provider, so verify actual part and final sizes and apply storage-side safeguards. Track orphan storage cost and apply lifecycle policies as a secondary cleanup mechanism.
Security, observability and testing
Use tenant-scoped authorization for every control-plane request. Signed URLs are bearer credentials; avoid logging them, keep their lifetime short and restrict permissions. Treat filename and MIME type as untrusted. Scan content, enforce decompression limits where applicable and serve untrusted files with safe download headers. Monitor initiation latency, part failures, completion latency, stale FINALIZING sessions, scan backlog, orphan bytes and quota reconciliation errors.
Test a disconnect after part three and assert that only missing parts are retransmitted. Test duplicate initiation and completion requests, expired signatures, wrong-tenant access, incorrect checksums and changed local files. Inject a crash after storage completion but before database update; verify that reconciliation publishes only the expected object. Race cancellation against completion and assert a valid terminal outcome. Load-test URL signing separately from data transfer and measure memory on constrained mobile devices.
Interview FAQs
Why upload directly to object storage?
It removes bulk data transfer from application servers while preserving authorization through scoped signed URLs.
Is an ETag always an MD5 checksum?
No. Multipart uploads and encryption can change ETag semantics. Use documented checksum fields.
How do you prevent duplicate objects?
Use a stable session key, unique object key and durable completion state, then reconcile after ambiguous failures.
Can a client resume on another device?
Yes if it can authenticate, access the same unchanged file and retrieve authoritative session progress.
How do you clean incomplete uploads?
Expire sessions, abort multipart storage and configure lifecycle cleanup for orphaned parts. Reconcile quota separately.
Conclusion
A robust upload system separates authorization from bulk data transfer, treats completion as a recoverable workflow and never exposes unvalidated objects. Start with direct multipart storage and a relational session database. Add bounded concurrency, durable scanning and cleanup before introducing unnecessary distributed coordination. For further reading consult Amazon S3 multipart upload documentation and the tus resumable upload protocol.
No Responses