Sub topic 15
Handling media and attachments
This chapter assumes you know the one-to-one message flow, the message data model, and basic object storage ideas such as buckets and keys.
Keep bytes off the chat path
Chat servers hold long-lived WebSocket connections and route small JSON messages. A 20 MB video sent through that connection would block other traffic on the same socket and use memory on a server that should stay light.
The usual design splits the work in two:
- The file goes to object storage, such as Amazon S3, and a CDN serves downloads.
- The chat message carries only a reference to the file, plus metadata.
This keeps the message flow, ordering, and acknowledgements unchanged. A message with an attachment is an ordinary message that happens to contain a pointer.
Upload flow with presigned URLs
A presigned URL is a temporary URL that lets a client upload one object directly to storage without holding storage credentials.
Steps in order:
- The client asks the API for an upload slot, declaring the content type and size.
- The API checks limits and returns a presigned URL that expires in a few minutes.
- The client uploads the bytes directly to storage.
- The client sends the chat message with the attachment ID, using the same client message ID and retry rules as a text message.
What the message stores
The message record stores metadata, not the file:
import json
MAX_BYTES = 25 * 1024 * 1024
ALLOWED_TYPES = {"image/jpeg", "image/png", "video/mp4", "application/pdf"}
def validate_upload(content_type, size):
if content_type not in ALLOWED_TYPES:
raise ValueError("unsupported type")
if size > MAX_BYTES:
raise ValueError("file too large")
def build_message(chat_id, client_msg_id, text, attachment):
return {
"type": "send",
"clientMsgId": client_msg_id,
"chatId": chat_id,
"text": text,
"attachment": attachment,
}
validate_upload("image/png", 400_000)
msg = build_message("c1", "m-7", "look!", {
"id": "att-91",
"key": "chats/c1/att-91.png",
"contentType": "image/png",
"size": 400_000,
"thumbKey": "chats/c1/att-91-thumb.jpg",
})
print(json.dumps(msg, indent=2))The thumbnail lets the chat list render quickly without downloading the full file.
Common errors
- Message sent before upload finishes. The recipient sees a broken link. Send the message only after storage confirms the upload.
- Orphaned uploads. A client uploads a file and never sends the message. Use a storage lifecycle rule to delete unreferenced objects after a day.
- Trusting the declared type. A client can claim
image/pngand upload an executable. Verify the real type after upload, and scan files for malware. - Public, permanent URLs. Anyone with the link can read the file forever. Serve downloads through short-lived signed CDN URLs, and check that the requester belongs to the chat.
- Large uploads over flaky mobile networks. Use multipart or resumable uploads so a dropped connection resumes instead of restarting.
Media processing, such as thumbnails and video transcoding, runs asynchronously in a worker triggered by the upload event. The message can show a placeholder until processing finishes.
Exercise
A user uploads a photo, but the app crashes before the chat message is sent. What happens to the stored file, and how do you keep it from piling up?
Show answer
The file stays in object storage with no message referencing it, so it is orphaned. Add a lifecycle rule or cleanup job that deletes attachments not linked to a message within a set time, such as 24 hours.