Video in progress
A mobile app uploads large files over an unreliable network. How do you design resumable uploads on the server side, continuing from the point of interruption?
First you open an upload session (ID, expected size, hash). The client sends the file in chunks with an offset; the server writes each chunk positionally and stores the confirmed offset. If the connection drops, the client asks for the offset and continues from there. At the end you verify the overall hash and put the file in place with an atomic move.
📖 Answer
With a single big POST, if a 2 GB file drops at 95%, everything starts from scratch. So you need a protocol: open protocols like tus.io have standardized this idea:
POST /uploads -> 201, Location: /uploads/{id} (size, sha256 in the metadata)
HEAD /uploads/{id} -> Upload-Offset: 73400320
PATCH /uploads/{id} Upload-Offset: 73400320, body: the next chunk
The main rule on the server side: a chunk is accepted only if it starts at the expected offset.
void appendChunk(UUID id, long clientOffset, InputStream body) throws IOException {
UploadSession s = sessions.lockForUpdate(id); // row lock in the DB
if (clientOffset != s.offset()) throw new OffsetMismatchException(s.offset()); // 409
try (FileChannel ch = FileChannel.open(s.partFile(), StandardOpenOption.WRITE)) {
long pos = clientOffset;
ByteBuffer buf = ByteBuffer.allocate(64 * 1024);
ReadableByteChannel src = Channels.newChannel(body);
while (src.read(buf) != -1) {
buf.flip();
while (buf.hasRemaining()) pos += ch.write(buf, pos);
buf.clear();
}
ch.force(false); // before confirming the offset
sessions.updateOffset(id, pos);
}
}
Design decisions:
- The offset is confirmed only after the data has reached the disk. Otherwise after a server crash it says "73 MB received" while the file has less.
- Parallel requests. A client that retries can send two PATCH requests at once: a lock on the session row or an optimistic version puts them in order.
- Multiple instances. A local
.partfile exists on only one pod. With multiple instances it is better to write the chunks straight into the object storage's multipart upload (on S3, every part except the last must be at least 5 MB), with the session state in the database. - Completion. After the last chunk the sha256 is checked, and if it doesn't match, the session becomes
FAILED. If it matches, an atomicmoveor the multipartcomplete, then the file ID is returned. - Cleanup. Sessions untouched for 24 hours and their chunks are deleted by a scheduled job, otherwise the disk fills up with abandoned uploads.
- Limits. The size is checked against a quota when the session is created, and there is a maximum size per chunk.
If clients can upload straight to the storage (presigned multipart URLs), a large part of this logic moves to the provider: the server only grants permission and confirms the completion.
Sign up to mark studied questions and save your progress.