Sub topic 15
Handling media and attachments
This chapter covers how a chat system sends images, video, voice notes, and files. It assumes you know HTTP, object storage basics, and the message model and delivery flow from earlier chapters. The main idea is simple: the chat path carries small messages, and the media path carries large bytes. Keeping the two apart protects the real-time servers.
Why media needs its own path
A text message is a few hundred bytes. A photo is 2 to 5 MB. A video can be hundreds of MB. If those bytes travel over the WebSocket to a chat server, three problems appear:
- A single upload blocks the connection. Other messages for that user queue behind it (head-of-line blocking).
- Chat servers hold memory for in-flight uploads. They are stateful and hold many connections, so memory is scarce.
- Retrying a failed 200 MB upload by resending the whole message is wasteful.
The standard design uploads the file to object storage (a service such as Amazon S3 that stores blobs by key) first. The chat message then carries only a reference to the file, such as an ID, a size, and a content type. The message stays small, so the ordering, acknowledgement, and idempotency rules from earlier chapters apply unchanged.
The upload flow
Clients upload straight to object storage with a pre-signed URL. This is a URL that the API server signs with its credentials. It grants permission to upload one specific object for a short time (for example 15 minutes).
The steps in order:
- The client asks the API for an upload slot. It states the content type, size, and optionally a SHA-256 checksum.
- The API checks size and type limits, creates an attachment record with status
pending, and returns anattachmentIdand a pre-signed URL. - The client uploads the bytes directly to storage.
- Storage emits a completion event. The API verifies the object exists and marks the record
ready. - The client sends the chat message with the
attachmentId. The chat server checks that the attachment isreadyand belongs to the sender before accepting the message.
Step 5 matters. Without the ownership check, a user could attach someone else's file by guessing an ID. Use random, unguessable IDs and check ownership anyway.
What the message stores
The message row keeps a small descriptor. It does not keep the bytes.
{
"chatId": "c1",
"seq": 42,
"senderId": "alice",
"clientMsgId": "m-77",
"type": "image",
"text": "Look at this",
"attachment": {
"id": "att_9f3a",
"contentType": "image/jpeg",
"sizeBytes": 3145728,
"width": 4032,
"height": 3024,
"thumbnailId": "att_9f3a_thumb",
"blurHash": "LEHV6nWB2yk8pyo0adR*.7kCMdnj"
}
}The width, height, and a tiny placeholder such as a blur hash let the client lay out the conversation before any image loads. This prevents the list from jumping as images arrive.
Resumable and chunked uploads
Mobile networks drop. A 200 MB upload that restarts from zero after a tunnel is a bad experience. Two common fixes:
- Multipart upload. The client splits the file into parts (for example 5 to 10 MB), uploads each with its own pre-signed URL, then asks storage to assemble them. A failed part is retried alone.
- Resumable protocols. Protocols such as tus let the client ask the server how many bytes it already has and continue from that offset.
Both rely on the same idea you saw in the delivery guarantees chapter: make retries safe. A part upload with the same part number overwrites the earlier attempt, so repeating it does no harm. Incomplete multipart uploads should be cleaned up by a lifecycle rule, or they consume storage silently.
Processing after upload
Raw uploads are rarely what recipients should download. A background pipeline, triggered by the upload event, produces better versions.
| Step | Purpose | Notes |
|---|---|---|
| Virus and malware scan | Protect recipients | Keep the attachment `pending` until the scan passes |
| Thumbnail generation | Fast previews in the chat list | Small files, often under 20 KB |
| Resize or transcode | Save bandwidth | Images to several widths, video to adaptive bitrates |
| Strip metadata | Privacy | Remove EXIF data such as GPS location from photos |
| Content moderation | Abuse control | Hash matching against known-bad content, plus classifiers |
Run this pipeline asynchronously through a queue. The sender should not wait for transcoding. A common compromise is to let the sender's message go out once the original is stored and scanned. Recipients first see the thumbnail, and better renditions appear when ready.
Stripping EXIF data is easy to forget. A photo posted to a group can reveal a home address through its GPS tags.
Downloading: CDN and access control
Recipients should not download from the origin bucket. Put a CDN (content delivery network, a set of edge caches close to users) in front of storage. Popular files, such as a photo in a large group, are then fetched from the origin once and served many times from the edge.
Access control creates a tension, because chat media is private. Public, permanent URLs are risky: anyone who gets the link can read the file. Options:
- Signed download URLs with short expiry. The client asks the API for a URL when it renders a message. The API checks that the requester is a member of the chat. This is the safest option, but each URL is unique, so caching by URL works poorly unless the CDN is configured to ignore the signature in its cache key.
- Signed cookies at the CDN. One cookie covers many files, which suits a screen full of thumbnails.
- End-to-end encrypted media. The sender encrypts the file with a random key and uploads the ciphertext. The key travels inside the encrypted chat message. Storage and CDN never see plaintext, but the server cannot generate thumbnails or scan content. You must do that work on the client.
Deduplication and storage cost
Media dominates storage. Text for a billion messages is measured in hundreds of GB. Photos for the same volume would be measured in petabytes. That is why the estimation chapter treated media as a separate line item.
Content-addressed storage helps. Name each object by the hash of its bytes. If a user forwards a file to ten groups, the system stores it once and the ten messages share one reference. Forwarding then costs a message write and no upload.
Two cautions apply. First, deduplication across users can leak information: if an upload completes instantly, the user learns that someone already stored that file. Restrict dedup to the same user or tenant if that matters. Second, deleting requires reference counting. A shared object can be removed only when no message points to it.
Lifecycle rules reduce cost further. Move media older than 30 days to a cheaper storage tier. Some systems expire media after a retention window and show "media no longer available", which is a product decision to settle during requirements.
Common errors
- Sending bytes through the chat server. This hurts latency for every user on that node.
- Announcing the message before the upload finishes. Recipients see a broken attachment. Only send the message once the attachment is
ready. - No size or type limits. Enforce limits when issuing the pre-signed URL, and re-check after upload, because clients can lie about the content type. Inspect the actual bytes.
- Orphaned uploads. Users start uploads and never send the message. Garbage-collect
pendingattachments older than a day. - Serving user files from your main domain. An uploaded HTML file could run scripts with your site's cookies. Serve media from a separate domain and set
Content-DispositionandX-Content-Type-Options: nosniff.
A minimal server-side sketch
This Python sketch shows the validation logic when issuing an upload slot and when accepting a message that references an attachment. Storage calls are left out so the logic can run as shown.
import uuid
MAX_SIZE = {"image": 10 * 1024 * 1024, "video": 200 * 1024 * 1024}
ALLOWED = {
"image/jpeg": "image",
"image/png": "image",
"video/mp4": "video",
}
attachments = {}
def request_upload(user_id, content_type, size):
kind = ALLOWED.get(content_type)
if kind is None:
raise ValueError("type not allowed")
if size > MAX_SIZE[kind]:
raise ValueError("file too large")
att_id = "att_" + uuid.uuid4().hex
attachments[att_id] = {
"owner": user_id,
"kind": kind,
"size": size,
"status": "pending",
}
return att_id
def mark_ready(att_id):
attachments[att_id]["status"] = "ready"
def accept_message(sender_id, att_id):
att = attachments.get(att_id)
if att is None or att["owner"] != sender_id:
raise PermissionError("unknown attachment")
if att["status"] != "ready":
raise ValueError("attachment not ready")
return True
a = request_upload("alice", "image/jpeg", 3_000_000)
mark_ready(a)
assert accept_message("alice", a)
try:
accept_message("bob", a)
except PermissionError:
print("bob blocked")Exercise
A user forwards a 50 MB video to 20 groups. Describe how the system should handle the upload, storage, and later deletion, and name one privacy risk of the approach you choose.
Show answer
The client uploads the video once and gets one attachmentId. If storage is content-addressed, the 20 forward messages each carry a reference to the same object, so no new upload or copy is made, and each message is sent through the normal chat path. Each message increments a reference count on the object. When messages are deleted or expire, the count drops, and the object is deleted only at zero. The privacy risk is cross-user deduplication: if a different user's upload of the same file completes instantly, that user learns the file already exists in the system. Limiting dedup to a single user or tenant avoids this.
Exercise
Why should the chat server reject a message whose attachment is still "pending", and why should it also check that the sender owns the attachment?
Show answer
A pending attachment may not be fully uploaded or scanned, so recipients could see a broken or unsafe file. The ownership check stops a user from attaching another user's file by guessing or learning its ID, which would expose that file to the new chat's members.