AlgoViz

How Large Uploads Work

easy 38 min

A large file goes up in small numbered pieces.

Video lesson · Chapter 1 of 5

A train enters a tunnel

0:00 / 3:49

How a large upload continues

1:26Reel

Theory

Read or listen first. About 2 min.

What it is

An upload copies bytes from your device to another computer. A small photo can go in one request. A large video is better sent as a resumable upload: the file is cut into pieces, every piece has a fixed place, and the server remembers how much it has saved.

This page follows one file all the way: a 400 MB video, cut into 100 pieces of 4 MB. Here 1 MB means 1,000,000 bytes. Piece 73 starts at 288 MB and ends where piece 74 begins, at 292 MB. While piece 73 is travelling, the Wi-Fi dies. Everything interesting happens after that.

The whole method needs only three things: an upload ID that names this upload, an offset that says how many bytes the server has, and a rule: the server's number wins.

Why it exists

Networks break, and long transfers give them more time to do it. If an upload is one single request and it breaks at 72%, the 288 MB that already travelled may be thrown away. With pieces, at most one piece of 4 MB travels twice.

There is also a harder problem. When a connection dies, the client often cannot tell whether the request was lost or only the reply. In the first case the server has nothing new. In the second it has saved the piece. A good protocol makes both cases safe with the same action: send it again.

A short history

  1. 1981

    RFC 793 describes TCP, published in September. It already says that an acknowledgment does not guarantee that data reached the end user, only that the receiving TCP took responsibility for it.

  2. 1995

    RFC 1867, from November, adds a file field to HTML forms and defines multipart/form-data. A web page can now send a file, in one request.

  3. 2010

    Amazon S3 introduces multipart upload on 10 November: one object sent as a set of parts.

  4. 2015

    Version 1.0 of tus, an open protocol for resumable uploads over HTTP, is announced on 16 November.

  5. 2026

    The IETF's own resumable upload protocol is still a draft. Version 16 is dated 23 November 2026.

Words to know

Piece, chunk or part
A slice of the file that is sent by itself. Products use different words for the same idea.
Offset
A distance from the start of the file, in bytes. Offset 288 MB means that 288 MB come before it.
Upload ID or session
The name of one upload on the server, and the state kept under that name.
In flight
Sent by one side and not yet known to have arrived.
Idempotent
Doing it twice has the same effect as doing it once.
Checksum
A short value computed from bytes. If the bytes change, the value almost certainly changes too.
Fingerprint
What the client uses to recognise the same file later: name, size, last change, and a hash of the first bytes.
Atomic
Happens completely or not at all. Nobody ever sees half of it.
Lease or expiry
The time after which the server may throw an unfinished upload away.

How it works

Step through the idea, or press Play.

Step 1 of 4

Start. The server makes an upload ID. Its number is 0

Understand it

Start here

A wall across the river

Asha has 100 numbered stones on the left bank of a river. Lee is building a wall with them on the right bank. A basket on a rope carries one stone at a time. Asha keeps a twin of every stone, so nothing is ever lost for good. On the right bank a post shows how many stones the wall has.

Building a wall by basket
01 to100One giant load

Asha never needs to know what happened in the fog. The number on the post is enough.

Byte by byte

What happens when you choose a file

You press a button and the operating system shows a file picker. The page does not get a path on your disk and it cannot look around. It gets a File object: a name, a size, a type, the time of the last change, and permission to read those bytes. Choosing a 400 MB file does not load 400 MB into memory.

file.slice(288000000, 292000000) makes a small object that points at those bytes. The second number is not included, so this is bytes 288,000,000 to 291,999,999. Think of a bookmark pair in a thick book: two bookmarks mark chapter 73, and nobody has copied the chapter. The bytes are read from the disk when they are sent.

The road of piece 73

Inside the user's device, piece 73 is read from the disk into browser memory, encrypted, and copied into the socket send buffer. It crosses the network to the load balancer in our system, then to an upload server. The upload server first writes the bytes to object storage and then writes offset 292 to the session database.
Each arrow is a copy. The client hears from the far end only when a reply comes all the way back.

The stops on the way

  1. 1

    Disk to memory

    The browser reads a part of the file. A good client holds one piece, not the whole file.

  2. 2

    TLS

    The bytes are encrypted in records of at most 16,384 bytes of data, so that nobody on the way can read or change them.

  3. 3

    Send buffer

    The operating system accepts bytes into a buffer. The program continues, although nothing may have left the device yet.

  4. 4

    TCP

    Bytes leave as packets. Each is numbered, acknowledged, and sent again if the acknowledgment does not come.

  5. 5

    Load balancer

    It often ends the TCP and TLS connection and opens another one to a server. An acknowledgment on the first connection says nothing about the second.

  6. 6

    Upload server

    It reads the body in small steps, counts bytes, computes the checksum, and passes the bytes on.

  7. 7

    Storage, then the number

    First the bytes must be safely stored. Then the offset in the session moves. Then the reply is sent. The order matters.

How many small things are in one piece?

⌈4,000,00016,384⌉=245 TLS records⌈4,000,0001,460⌉=2,740 packets\left\lceil\frac{4{,}000{,}000}{16{,}384}\right\rceil = 245\ \text{TLS records} \qquad \left\lceil\frac{4{,}000{,}000}{1{,}460}\right\rceil = 2{,}740\ \text{packets}
Assumption: full records and 1,460 bytes of data in a packet, without TLS extras. The whole video is about 274,000 packets.

A strange sight

Why 100% is not always finished

You drop a letter into a letterbox on your street. From your side the job is 100% done. The letter is still in the box. A progress bar usually counts what left your side, not what was saved on the other side.

A browser's upload progress event counts bytes of the request body that were transmitted. Below it, a normal send on a socket gives no sign of a failed delivery: it only tells you about errors found locally. So the last bytes can sit in a send buffer, in the network, in a load balancer or in a server that has not stored them yet.

The bar runs ahead

The TCP acknowledgment comes from the load balancer, long before anything is stored.

What each 'OK' really promises

You hearIt meansIt does not mean
send returnedThe operating system took the bytesThey left the device
TCP acknowledgmentThe next machine's TCP has themThe program read them, or anything is stored
Progress event: 100%The body was handed overThe server answered
Server's reply: offset 292Pieces up to 292 MB are savedThe whole file is finished
Reply to finish: 200The file is joined, checked and visibleNothing is missing here. This is the one to wait for

The weak way

Why one long request is fragile

Carrying 100 plates in one tower is fast until you stumble. The same four dangers wait for a long request.

  • Timeouts

    Proxies and servers close requests that are too slow or silent. nginx by default waits 60 seconds between two reads of a body. Cloudflare's 524 error means that the origin did not answer within 125 seconds by default.

  • Size limits

    nginx accepts bodies up to 1 MB by default and answers 413 above that. Every box on the way may have its own limit.

  • Memory and disk

    Careless code holds the whole body. A proxy may first write it to a temporary file.

  • Mobile hand-over

    When a phone leaves Wi-Fi for the mobile network, its address changes. A TCP connection is tied to both addresses, so it ends.

How long does the video take?

400 MB×8 bit8 Mbit/s=400 s=6 min 40 s\frac{400\ \text{MB} \times 8\ \text{bit}}{8\ \text{Mbit/s}} = 400\ \text{s} = 6\ \text{min}\ 40\ \text{s}
Assumption: an upload speed of 8 Mbit/s, which is 1 MB per second. One piece takes 4 seconds. The break in piece 73 comes after 288 seconds.

How often does one request survive?

P=e−400/600≈51%P2 GB=e−2000/600≈3.6%P = e^{-400/600} \approx 51\% \qquad P_{2\,\text{GB}} = e^{-2000/600} \approx 3.6\%
Assumption: breaks come at random, one in 600 seconds on average. Then the chance of no break in t seconds is e to the power of minus t / 600.

The same line, with and without pieces

FileWithout any breakOne request, start againPieces of 4 MB
400 MB400 sabout 569 sabout 401 s
2 GB2,000 sabout 16,200 s, or 4.5 hoursabout 2,007 s
Same assumption. Expected time with restarts is 600 x (e^(T/600) - 1) for a transfer of T seconds. The last column uses T = 4 for every piece. It leaves out waiting and requests.

Memory on the server

1,000×400 MB=400 GB1,000×4 MB=4 GB1,000×64 KB=64 MB1{,}000 \times 400\ \text{MB} = 400\ \text{GB} \quad 1{,}000 \times 4\ \text{MB} = 4\ \text{GB} \quad 1{,}000 \times 64\ \text{KB} = 64\ \text{MB}
For 1,000 uploads at once: holding whole files, holding one piece each, or streaming through a 64 KB buffer each. Pieces help, and streaming helps more.

But TCP

What TCP repairs, and what it cannot

TCP is like a careful postal worker on one road. If a parcel is lost on that road, they carry it again. But if the road itself is gone, or you moved to another house, the worker's notebook is worth nothing.

TCP already does

  • Sends lost packets again
  • Puts packets into order and drops doubles
  • Slows down for a full network or a slow receiver
  • Finds most damage with a 16-bit checksum

TCP cannot

  • Continue after the connection has ended
  • Remember anything after a restart or a closed tab
  • Cross a load balancer that ends the connection
  • Say that your program stored the bytes
  • Know that two requests carry the same piece

It can also be too patient. On Linux, an established connection gives up by default after 15 tries, which the manual puts at roughly 13 to 30 minutes. Your program needs its own, shorter limit: see timeouts.

Step 1

Cut it into pieces

Where is piece N?

start(N)=(N−1)×4 MBstart(73)=72×4=288 MBend=292 MB\text{start}(N) = (N-1) \times 4\ \text{MB} \qquad \text{start}(73) = 72 \times 4 = 288\ \text{MB} \qquad \text{end} = 292\ \text{MB}
Pieces are numbered from 1. The end is the start of the next piece, so piece 73 holds the bytes 288,000,000 to 291,999,999. The last piece may be smaller.

Some pieces of the video

PieceStarts atEnds beforeServer has afterwards
10 MB4 MB4 MB, 1%
24 MB8 MB8 MB, 2%
72284 MB288 MB288 MB, 72%
73288 MB292 MB292 MB, 73%
74292 MB296 MB296 MB, 74%
100396 MB400 MB400 MB, 100%

Why not tiny pieces, or huge ones? Think of moving books in boxes. Very small boxes mean many walks. One huge box is dropped once and everything is on the floor.

Choosing the piece size for 400 MB at 1 MB per second

PiecePiecesWaiting for repliesA lost piece costs up to
100 KB4,000400 s: the upload takes twice as long0.1 s
1 MB40040 s1 s
4 MB10010 s, or 2.5% extra4 s
16 MB252.5 s16 s
64 MB70.7 s64 s
Assumptions: one piece after another, each waits 0.1 s for its reply. On a line that is 20 times faster, 4 MB takes 0.2 s and a larger piece is better. Rules of storage also count: S3 parts are at least 5 MiB except the last one.

Choosing a size

The limits of 1 and 30 seconds are our rules of thumb. Keep the size fixed inside one upload if you number the pieces.

Step 2

An upload ID and one number

A cloakroom gives you a ticket. You do not have to remember the hook, the room or the person who took your coat. An upload ID is that ticket. Behind it, the server keeps the session.

JSON
{  "uploadId": "up_9f3c1a7e",  "owner": "user_42",  "fileName": "school-play.mp4",  "totalSize": 400000000,  "offset": 288000000,  "pieceHashes": ["...72 values..."],  "state": "open",  "expiresAt": "2026-12-02T10:00:00Z"}
The session on the server after 72 pieces. All values are made up. The ID is long and random, so nobody can guess it.

A quiet upload

102 requests for 100 pieces: one to start, 100 pieces, one to finish. Every reply carries the server's number.

The session must live in a shared database or in the storage service, because the next piece may reach another server. The offset is not a guess made by the client. It is a fact known to the server.

The heart

Lost request or lost reply?

You send a friend a message: "Please water the plants." No answer comes. Did the message get lost, or did they water the plants and only the answer got lost? From your chair both look the same: silence. That is exactly the position of the client after the Wi-Fi died during piece 73.

The same silence, two truths

What happenedServer hasPercentWhat the client knows
The piece was lost on the way288 MB72%Nothing: no reply
The piece was saved, the reply was lost292 MB73%Nothing: no reply

Case 1: the piece was lost

Case 2: only the reply was lost

The client did the same thing in both cases, and got the same answer. That is why it does not need to guess.

What asking the server costs

  • Send the same piece again: at most 4 MB extra, 4 seconds here
  • Or ask first with one tiny request, and then send only what is missing
  • Both end at the server's number, and both are correct

What guessing costs

  • Guess "lost", and append blindly: the piece may be in the file twice, and everything after it is shifted by 4 MB
  • Guess "saved", and jump to piece 74: there may be a hole of 4 MB
  • Give up: the user sends 288 MB again

The rule

Why sending again is safe

What the server does with a piece

Every answer about offsets contains the server's number, also the answers that say no.
Python
MB = 1_000_000stored = 288 * MB                         # the server's one numberdef append(offset, length):    global stored    if offset == stored:        stored += length                  # (the bytes are written first)        return 200, "saved", stored // MB    if offset + length <= stored:        return 200, "already here", stored // MB    return 409, "continue from my number", stored // MBprint(append(288 * MB, 4 * MB))           # piece 73print(append(288 * MB, 4 * MB))           # piece 73 againprint(append(300 * MB, 4 * MB))           # piece 76: a holeprint(append(292 * MB, 4 * MB))           # piece 74
Eight lines decide everything. The full program is in the Code tab.
Edit and run it in your browser

Sending twice with one effect is called idempotency. Here no extra key is needed: the upload ID and the offset together already say exactly which bytes are meant. Two requests for the same place must be handled one after the other, so the server takes a lock for this upload ID or changes the number only if it is still the old one.

Retry

Wait, then try again

If a door does not open, you do not ring a thousand times a second. You wait a little, then a little longer. A client waits 1 second, then 2, then 4, with a random part, and stops at a highest wait. Without the random part, thousands of phones that lost the same network would come back in the same second.

Failed tries in a rowLongest waitWaited so far, at most
11 s1 s
22 s3 s
34 s7 s
48 s15 s
516 s31 s
6 and more30 s61 s after the sixth
Base 1 s, doubling, capped at 30 s. The real wait is a random time between 0 and the longest wait. One saved piece sets the counter back to zero.

Try again

  • No reply, or the connection ended
  • 408, 429, 500, 502, 503, 504: if there is a Retry-After, obey it
  • The device says it is online again: try now
  • A damaged piece: send that piece again

Do not repeat the same request

  • 400 or 413: the request itself is wrong
  • 401 or 403: sign in again first
  • 404 or 410: the session is gone, start a new upload
  • 409: not an error to repeat. Read the number and continue there

If the network stays away, pause and keep the session. A pause is not a failure. More about budgets and storms: retries.

Closed tab

Continue after a crash

You read a thick book and put it down for a week. A bookmark is enough to continue, but you need the bookmark and the book. The bookmark is the saved upload ID. The book is the file.

A closed tab loses everything in memory: the File object, the list of pieces, the current number. So the page saves a small note when the upload starts, for example in IndexedDB or localStorage. It holds the upload ID and the fingerprint of the file. It does not hold the video.

The next morning

Here the page asks first, because it has no idea how far it got. 292 / 4 = 73 pieces are stored, so piece 74 is next.

Can the page get the file back?

WayAfter the tab was closedNote
<input type="file">No. The user chooses againWorks in every browser. Plan for this one
File handle from showOpenFilePickerPerhaps. A handle can be kept in IndexedDB, and the browser asks for permission again unless the user allowed every visitMDN marks it experimental and not available in some widely used browsers. Chrome describes lasting permission from version 122
Copy into the browser's private storageYes, the copy is thereCosts 400 MB of disk and time, and the browser limits how much a site may keep
An installed desktop or phone appOften yes, within the system's rulesApps can have file access that a page has not
Even a file handle needs permission that the user gave. No ordinary page opens a path by itself.

Same file

Is it really the same video?

Two jars can have the same label and different jam. If the user chose another file, or edited the video overnight, pieces 74 to 100 of the new file would be glued to pieces 1 to 73 of the old one.

CheckCostMisses
NameNoneAnother file with the same name
Size in bytesNoneA changed file of equal size
Last modifiedNoneSome copies and tools change or keep the time. It is a hint
Hash of the first 1 MBReads 1 MBA change further on
Hashes of the stored piecesReads 292 MB from the local disk, sends none of itNothing that was stored, apart from accidents too unlikely to plan for
Use the first four at once to find the right note. Use the last one, or the final check, to be sure.
JavaScript
async function fingerprint(file) {  const head = await file.slice(0, 1_000_000).arrayBuffer();  const hash = await crypto.subtle.digest("SHA-256", head);  const hex = [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, "0")).join("");  return [file.name, file.size, file.lastModified, hex].join("|");}
Runs in the browser on a secure page. It reads one million bytes, whatever the size of the file.

The file can also change during the upload. A browser is asked to remember the state of the file at the moment it was chosen, and a read of a file that changed should fail with NotReadableError. Then the only honest answer is to start a new upload.

Integrity

Are these the right bytes?

The offset says where bytes belong. It does not say that they are the right bytes. A parcel with the right address can still be broken inside.

  1. 1

    Per piece

    The client sends the SHA-256 of the piece. The server computes it while reading. If they differ, nothing is saved, and only 4 MB travels again.

  2. 2

    For the whole file

    At the end the client sends one value for the complete file. This finds a missing piece, a wrong order, or pieces of two different files.

  3. 3

    At rest

    Storage keeps its own checksums and checks them when it reads. See object storage.

A hash of hashes

Hfile=SHA256(h1 ∥ h2 ∥ … ∥ h100),100×32 bytes=3,200 bytesH_{\text{file}} = \text{SHA256}\big(h_1 \,\|\, h_2 \,\|\, \dots \,\|\, h_{100}\big), \quad 100 \times 32\ \text{bytes} = 3{,}200\ \text{bytes}
Hash every piece, put the 100 results of 32 bytes in order, and hash that. The server does not have to read 400 MB again to check the order and the presence of every piece.

TLS already finds changes made on one encrypted connection. The extra checks are for everything outside it: a bug in the slicing code, a wrong offset, damaged memory, a proxy that cuts a body, a file that changed.

Speed

One offset or parallel parts?

Two ways to fill a sticker album. Either you always put the next sticker in the next place, so one number says how far you are. Or three friends fill different pages at once, and you need a list of the places that are full.

One offset, in orderNumbered parts, in parallel
State on the serverOne number: 288 MBA list: 1, 2, 3, 5, 8
After a breakContinue from the numberSend what is missing from the list
Sending piece 73 againOffset check: already hereSame part number: replaces or repeats the same part
Good whenOne connection fills the line, phones, simple clientsFast line, long distance, one connection is the limit
PricePieces wait for each otherMore state, more memory, joining in order

What can parallel parts save?

100×(4+0.1) s⏟one after another=410 s400 s+little⏟line always busy\underbrace{100 \times (4 + 0.1)\ \text{s}}_{\text{one after another}} = 410\ \text{s} \qquad \underbrace{400\ \text{s} + \text{little}}_{\text{line always busy}}
Same numbers as before: 1 MB per second and 0.1 s of waiting per piece. The line is the limit, so three pieces at once cannot make it 3 times faster. They only fill the gaps.

Products

Four protocols, one idea

Every product below cuts, remembers and continues. They differ in who names the place and in what happens when the same piece comes twice. Do not mix them up in an interview.

What happens if piece 73 is sent twice?

ProtocolHow the place is namedThe second copyAsk for progress
Dropbox upload session, in ordercursor with session_id and offsetError incorrect_offset with correct_offset: continue thereThe error itself tells you
tus 1.0Upload-Offset header409 Conflict, upload unchanged. Then HEADHEAD gives Upload-Offset
S3 multipartPart number 1 to 10,000Overwrites the earlier part with that numberList parts. Keep your own list of numbers and ETags
Google Cloud Storage resumableContent-Range: bytes first-last/totalBytes at offsets already saved are ignored. Never send different bytesEmpty PUT with bytes */total: 308 and Range
YouTube resumableContent-Range, the same styleOverlapping or skipped bytes: the upload fails. So ask firstEmpty PUT: 308 and Range
IETF draft 16Upload-Offset header409 with the right offset in the answerHEAD
Our own server on this page answers 200 and its number for a piece that is already stored. With Dropbox the same fact arrives as an error. In both cases the client's next step is identical.

Dropbox

How a Dropbox upload session does it

  1. 1

    upload_session/start

    Creates the session and returns a session_id. It may already carry the first data.

  2. 2

    upload_session/append_v2

    Sends data with a cursor: the session_id and the offset, which is how much has been uploaded so far.

  3. 3

    If the offset is wrong

    The answer is incorrect_offset, and it contains correct_offset. Dropbox's specification says this can happen when an earlier request was processed but the client did not get the response. That is our lost reply.

  4. 4

    upload_session/finish

    Takes the cursor and a commit with the path. Only now is there a file in Dropbox.

HTTP
POST /2/files/upload_session/append_v2 HTTP/1.1Host: content.dropboxapi.comAuthorization: Bearer <token>Content-Type: application/octet-streamDropbox-API-Arg: {"cursor": {"session_id": "<id>", "offset": 288000000}}<the bytes of piece 73>
Piece 73 with Dropbox. If its reply was lost, the same request again gets incorrect_offset with correct_offset 292000000. Treat it as good news and send piece 74.

Dropbox limits, from its documentation

LimitValue
One requestAt most 150 MiB
One file in a session2^41 - 2^22 = 2,199,019,061,248 bytes
Life of a session7 days. Then the ID is not_found
Piece sizeIts performance guide suggests multiples of 4 MB
Concurrent sessionSet session_type to concurrent at start. Pieces may then go in any order
Rules for concurrentNo data in start or finish. Offsets and lengths are multiples of 4,194,304 bytes, except the length of the last append, which sets close
4,194,304 bytes are 4 MiB, a little more than our 4 MB. Cut that way, 400,000,000 bytes make 96 pieces: 95 full ones and one of 1,541,120 bytes.

Check the 96 pieces

95×4,194,304=398,458,880400,000,000−398,458,880=1,541,12095 \times 4{,}194{,}304 = 398{,}458{,}880 \qquad 400{,}000{,}000 - 398{,}458{,}880 = 1{,}541{,}120
This is why a real client reads the size rules of its storage before it starts cutting.

Dropbox also documents a content_hash: SHA-256 of every 4 MiB block, joined, and hashed again. It is the hash of hashes from above. How a whole file-sync product is built around this: Design Dropbox. Video sites add processing after the upload: Design YouTube.

How the others differ

  • tus

    One PATCH may carry the rest of the file. The server should keep as much as it received, so its offset can be 290 MB, in the middle of our piece. The client continues from 290, not from 288.

  • S3 multipart

    A part has a number and an ETag. Parts may come in any order, and finish lists all pairs. With 5 MiB, the smallest size, our video has 77 parts. There is no expiry unless you add a lifecycle rule, and unfinished parts are billed.

  • Google's range style

    Pieces are multiples of 256 KiB except the last. A 308 answer means: not finished. Its Range header says the last byte saved. bytes=0-287999999 means continue at 288,000,000. A session lives for a week.

  • IETF draft

    A server may send interim answers with status 104 that report the offset while the body is still travelling. Still a draft, so do not promise that browsers support it.

Parts at the S3 minimum

⌈400,000,0005×1,048,576⌉=⌈76.3⌉=77 parts\left\lceil \frac{400{,}000{,}000}{5 \times 1{,}048{,}576} \right\rceil = \left\lceil 76.3 \right\rceil = 77\ \text{parts}
Our 4 MB pieces are too small for S3, except the last one.

Where

Straight to storage

The bytes do not have to pass through your own servers. Your API can check the user and hand out signed URLs, and the client sends the pieces straight to object storage. The state then lives in the storage service. Signed URLs, forms and the choice between methods are explained in file upload APIs.

Direct parts, and a job that cleans up

First the client asks the upload API to start or finish. Second the API writes the session with ID, owner and parts to the session database. Third the client sends the parts straight to object storage with signed URLs. The session database gives expired sessions to a clean-up job, after 7 days, and the job deletes their unfinished parts from object storage.
The API carries decisions. Storage carries bytes. The job removes what nobody finished.

Step 3

Finish in one step

A theatre does not open the curtain while the painters are still on stage. Until finish has succeeded, the file does not exist for anybody else.

The life of an upload

Paused is how the client sees it. For the server a paused upload is simply open and quiet. The 7 days are our choice here.

What finish does

  1. 1

    Check the length

    The offset must be exactly 400,000,000. If not, answer 409 and the offset.

  2. 2

    Check the hash

    Compare the client's hash of hashes with the one from the stored pieces.

  3. 3

    Join

    Put the pieces together in order, or write a list that names them in order. Storage services do this for you.

  4. 4

    Publish with one change

    Move one row from checking to ready, or rename one object. One small change is atomic. Copying 400 MB is not.

  5. 5

    Remember the result

    Finish can lose its reply too. A second finish with the same ID must return the same file, not make a second one.

Clean-up

The uploads nobody finished

Someone fills 73 shelves and never returns. The shelves are still full, and somebody pays for them.

What abandoned uploads store

10,000×292 MB=2,920,000 MB=2.92 TB10{,}000 \times 292\ \text{MB} = 2{,}920{,}000\ \text{MB} = 2.92\ \text{TB}
Assumption: 10,000 uploads that all stopped at piece 73. None of them shows up as a file.
  1. 1

    Give every session an end

    Dropbox sessions live 7 days, Google's one week. Tell the client the time, so that it does not offer a dead session.

  2. 2

    Delete in the right order

    Mark the session expired first, so that no new piece is accepted. Then delete the pieces. Then delete the row.

  3. 3

    Let storage help

    S3 has a lifecycle action for incomplete multipart uploads.

  4. 4

    Let the user cancel

    Cancel deletes at once. Deleting twice must be harmless.

Safety

Limits against misuse

DangerLimit
Somebody guesses or steals an upload IDLong random IDs, and check the owner on every request. Keep session links out of logs. Google says that a session URI works as its own proof of permission
Says 400 MB, sends 400 GBCount the bytes that really arrive. Stop at the declared size and at the limit of the plan
Opens a million sessionsLimit open sessions and reserved bytes per user
Sends one byte a minuteA shortest speed or longest time per piece, and a timeout between reads
Dangerous name or typeA key of your own, never a path from the client. Look at real bytes, scan, and serve files from another domain
Wrong checksum to waste workLimit failed pieces per session
Two tabs write togetherLock or compare-and-set on the offset. The loser gets 409 and the number
SQL
UPDATE uploads   SET offset_bytes = 292000000 WHERE id = 'up_9f3c1a7e'   AND owner = 'user_42'   AND state = 'open'   AND offset_bytes = 288000000;-- 1 row changed: this request moved the number.-- 0 rows changed: somebody else was faster. Read the number and answer it.
Compare and set in SQL. Each copy writes its bytes under a name of its own, for example piece 73 plus a random value, and the winner's name goes into the session in the same update. So the loser can never damage the winner's bytes.

All together

One upload from start to end

TimeWhat happensServer's number
0 sStart. The page saves the upload ID0
288 s72 pieces are stored288 MB, 72%
290 sThe Wi-Fi dies while piece 73 is in flight288 or 292 MB
295 sWait, then piece 73 again292 MB, 73%
300 sThe user closes the tab. Piece 74 has not been stored292 MB, 73%
Next daySame file chosen, ID found, the server says 292292 MB, 73%
+ 108 sPieces 74 to 100: 27 pieces of 4 s400 MB, 100%
ThenFinish: hash equal, joined, readyFile visible
At 1 MB per second, leaving out the waiting for replies and the exact retry times. Nothing that the server had saved travelled again after the tab was closed.

Summary

The whole topic in one minute.

Cut the file into pieces. Piece N starts at (N - 1) times the piece size. The server stores the pieces under an upload ID and keeps one number, the offset. Every reply contains that number, and the client always continues from it.

After a break the client cannot know whether the request or the reply was lost, and it does not need to. It sends the same piece again. If the server expected that offset, it saves the piece. If the piece is already stored, the server writes nothing and answers with its number. Wait a little longer before each new try.

A closed tab is the same problem with one extra step: the page must have saved the upload ID, and the user must choose the file again. At the end the pieces are checked, joined and published in one step, and uploads that nobody finished are deleted.

  • Piece N starts at (N - 1) x 4 MB. Piece 73 is 288 to 292 MB.
  • The server keeps an upload ID and one number: how much it has. Its number wins.
  • Silence can mean a lost request (288 MB) or a lost reply (292 MB). The client cannot tell.
  • Don't guess. Send it again, let the server decide: expected means save, already stored means write nothing and answer 292.
  • A closed tab needs a saved ID and the same file, chosen again by the user.
  • 100% sent is not 100% saved. Wait for the answer to finish.
  • TCP repairs packets inside one connection. It cannot remember an upload.
  • Check every piece and the whole, publish in one step, and delete what nobody finished.

Sources