All posts
BackendSystem DesignNode.js

Going back to code that already worked: three levels of file uploads

File uploads in my chat app worked on day one. Within a week I had rebuilt them twice, and fixed a pagination bug that showed users duplicate messages.

S
Sandip Godhani
19 Jul 2026 · 5 min read

One thing I've really enjoyed while building ChatApp is revisiting features I had already finished. Getting something to work is satisfying. Going back and improving how it's built has taught me far more than moving on to the next feature. File uploads are the clearest example.

The easiest way to understand the difference between the three levels is a movie. You can download the whole 2 GB file and then watch it, or you can stream it: start watching the first few seconds while the rest loads in the background. Uploads work the same way.

Level 1: the server holds the whole file

ClientServer RAM (buffer)Cloudinary

My first version used Multer with memory storage. The backend received the entire file from the browser, kept it in RAM (req.file.buffer), and then uploaded it to Cloudinary.

This is the easiest version to write, and it works fine for small files. But do the maths: if 10 users upload a 100 MB video at the same time, the server needs 1 GB of RAM just to hold those files for a few seconds. That is how small servers crash.

Level 1 was fine for what I first built it for: profile pictures. Those are small images that Cloudinary resizes to 300 × 300 anyway. Four days later I added file sharing inside chats, and chat media is a different animal: videos, voice notes, files. The same code that was fine for avatars was now the weakest part of the server. That's what pushed me to keep going.

Level 2: stream it through

ClientServer (pipe)Cloudinary

A few days later I switched to streaming. As soon as the server receives the first small chunk from the browser, it forwards it on to the cloud. The server acts like a pipe, so the file is never fully held in memory, no matter how big it is.

Much better for RAM. But the file still travels through my server, so it still costs CPU and network bandwidth for every upload.

Level 3: the server never touches the file

Client asks for a signatureServer signs locallyClient uploads directly to Cloudinary

This is what ChatApp uses now. The trick is that my server and Cloudinary share a secret: the API secret. The server uses it to sign the upload parameters, and it does this locally, without even contacting Cloudinary.

backend/controllers/chatController.js (trimmed)js
export async function getUploadSignature(req, res, next) {
  const timestamp = Math.round(new Date().getTime() / 1000)
  const folder = 'chatapp-media'

  // Generate api signature
  const signature = cloudinary.utils.api_sign_request(
    { timestamp, folder },
    process.env.CLOUDINARY_API_SECRET
  )

  res.json({
    signature,
    timestamp,
    apiKey: process.env.CLOUDINARY_API_KEY,
    cloudName: process.env.CLOUDINARY_CLOUD_NAME,
    folder,
  })
}

The browser then sends the file, the signature and the public API key straight to Cloudinary. Using XHR instead of fetch here gives a real upload progress bar, and an AbortSignal lets the user cancel.

frontend/src/services/chatService.js (trimmed)js
export function uploadDirectToCloudinary(file, signatureData, onProgress, abortSignal) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    const formData = new FormData()
    const { signature, timestamp, apiKey, cloudName, folder } = signatureData

    formData.append('file', file)
    formData.append('api_key', apiKey)
    formData.append('timestamp', timestamp)
    formData.append('signature', signature)
    formData.append('folder', folder)

    xhr.open('POST', `https://api.cloudinary.com/v1_1/${cloudName}/${resourceType}/upload`)
    xhr.upload.onprogress = (e) => onProgress(Math.round((e.loaded * 100) / e.total))
    abortSignal?.addEventListener('abort', () => xhr.abort())
    // ...resolve on 2xx, reject otherwise
    xhr.send(formData)
  })
}

Cloudinary recalculates the signature on its side using the same secret. If the two match, the file is saved and a URL comes back. If anyone tampers with the folder or the timestamp, the signatures won't match and the upload is rejected with a 401.

  • No file buffering on the backend, and no Multer on the chat routes at all.
  • Zero upload traffic through my server: 0 RAM, 0 CPU, 0 bandwidth for the file itself.
  • The signature endpoint is rate-limited (10 per minute per IP), so it can't be used to spam uploads.

The same idea, applied to the data model

Around the same time I refactored how chats are stored. None of these changes added a feature anyone would notice, but they make the app far easier to scale and extend:

  • A dedicated Conversation model with members and roles, instead of deriving chats from messages. The sidebar no longer scans every message to build the chat list.
  • A Message schema built around ObjectId references to the conversation and sender, with receiverId nullable so the same schema works for group chats.
  • Compound indexes for how chats are actually read: { chatId: 1, createdAt: 1 } and { chatId: 1, _id: -1 }.
  • Cursor-based pagination instead of offset pagination.

The "moving goalpost" bug

That last one fixed a real bug. With skip()-based pagination, loading older messages could show you messages you'd already seen. Here's why:

  1. 1The chat has messages [989, 988, 987, 986, 985, 984...]. Page 1 (limit 5, skip 0) returns 989 to 985.
  2. 2Two new messages arrive: 991 and 990. Everything older shifts down by two.
  3. 3You scroll up for page 2 (limit 5, skip 5). MongoDB skips 991 to 987 and returns 986, 985, 984, 983, 982.
  4. 4You see 986 and 985 twice.

In a chat, new messages arrive all the time, so the boundary keeps moving. The fix is to stop counting positions and ask for messages older than the oldest one you already have. A message's _id never changes, so the cursor stays stable no matter what arrives:

backend/controllers/chatController.js (trimmed)js
// Build keyset pagination query
const query = { chatId: targetChatId, deletedBy: { $ne: currentUserId } }
if (cursor && mongoose.Types.ObjectId.isValid(cursor)) {
  query._id = { $lt: cursor }
}

// Newest first, then reversed in memory so the client gets them oldest first
const messages = await Message.find(query).sort({ _id: -1 }).limit(parsedLimit)
messages.reverse()

With the { chatId: 1, _id: -1 } index, MongoDB jumps straight to the cursor position and reads only that slice, so loading page 50 is as fast as loading page 1.

Writing code is only half the job. Designing systems that keep working as they grow is the other half.

Advice I only understood later

Months ago, Balkrishna Agarwal sir told me to refactor my code. That day I was thinking: why? It already works. Now I understand what refactoring is worth, and why improving code a little every day matters.

Read next
I built auth from scratch. Then I deleted it.