Storage

Resumable uploads without server-side session state

By Nuz ·

How my file storage app sends large files in pieces and picks up where it left off after a dropped connection.

Sending a large file in a single request is fragile. If the connection drops near the end, everything has to be sent again. My storage app splits each file into chunks so that a failure only costs the part that had not arrived.

  1. Ask to start an upload
  2. Receive a sealed token
  3. Send 8 MB chunks
  4. On failure, ask for status
  5. Continue from that offset

The shape of the protocol

There are three requests. The first announces the file's name, size and type, and the server answers with a token and a chunk size. The second sends one chunk along with the token. The third, used only on retry, asks how many bytes the storage backend actually holds.

The last one matters most. A browser can lose its connection after a chunk was saved but before the reply arrived. If the client trusted its own count, it would send the wrong bytes next. So on retry it asks, and uses the answer.

Keeping state in the token

The server needs to remember which upload a chunk belongs to, the final size and the current offset. Instead of keeping a session table for this, it puts those facts into the token itself and encrypts them with AES-GCM through the Web Crypto API.

const iv = crypto.getRandomValues(new Uint8Array(12));
const body = await crypto.subtle.encrypt(
  { name: 'AES-GCM', iv },
  key,
  new TextEncoder().encode(JSON.stringify(state)),
);

AES-GCM is authenticated encryption. A client cannot read the contents, and any edit makes decryption fail, so it cannot raise the size limit or move the offset. Each token also carries an expiry time. Every successful chunk returns a fresh token with the new offset.

Rules for each chunk

The server checks that a chunk is not larger than the agreed size and does not run past the declared total. Every chunk except the last must also be a multiple of 256 KiB, because the Google Drive resumable upload API requires it. Rejecting a bad chunk early gives a clearer error than letting it fail further down.

On the browser side

The browser uses file.slice(), which creates a view of part of the file without reading all of it into memory. Chunks are sent with XMLHttpRequest rather than fetch, because it reports upload progress. The progress bar adds the bytes already confirmed to the bytes sent in the current chunk, and holds at 99 percent until the server says the file is complete.

The trade-off

A token cannot be revoked individually the way a database row can be deleted. A short lifetime limits that, and for this app the simpler server is worth it.

More build notes

← All build notes