Sub topic 4
Uploading directly to storage and keeping your servers out of the data path
This chapter assumes you know the proxied upload path from the earlier chapter, where the browser sends multipart/form-data to your API server and the server forwards the file to storage. It also assumes you know what an object store such as Amazon S3 is. Here you will learn the direct-to-storage pattern, why it changes your architecture, and which errors show up most often when you adopt it. The next chapter covers how presigned URLs and POST policies are built and constrained. This chapter covers the system around them.
The working model: control plane and data plane
A proxied upload puts your API server in the data path. Every byte of every file passes through its network interface, memory, and request timeouts. A direct upload splits the work into two planes:
- The control plane is your API. It decides who may upload what, allocates a key, and records the result. It handles small JSON requests.
- The data plane is the object store. It receives the file bytes, which is the job it is built for.
Your server never touches the file. It hands the client a short-lived permission, and the client uses that permission to talk to storage itself. The permission is a presigned URL or a presigned POST policy.
What you gain
- Predictable server load. API capacity scales with request count, not with total bytes uploaded. A 2 GB video costs your API the same as a 20 KB avatar.
- No long-held connections. A slow mobile client uploading for ten minutes no longer holds a worker, a thread, or a proxy buffer on your side.
- Storage-grade throughput and durability. The store accepts parallel uploads and retries, and it writes the object durably before it acknowledges.
- Lower bandwidth cost on your tier. You stop paying for every file to enter your network and then leave it again to reach storage.
What you give up
- Less inline control. You cannot inspect bytes as they stream through your code. Validation moves to the policy (before the upload) and to post-upload checks (after it).
- A completion gap. Your server does not see the upload finish unless something tells it.
- More moving parts. You now need bucket CORS rules, a state machine for uploads, and cleanup for uploads that never finish.
The three-step flow
- The client asks your API for permission, sending metadata only: file name, declared type, size.
- The API validates the request, allocates a key, saves a
pendingrecord, and returns the presigned data. - The client sends the file directly to storage, then tells your API it is done (or storage tells your API through an event).
A server-side implementation
The sketch below uses Flask and a dictionary as a stand-in for a database table. It shows the two endpoints that matter: one that creates the upload, and one that confirms it.
import uuid
import boto3
from botocore.exceptions import ClientError
from flask import Flask, abort, jsonify, request
app = Flask(__name__)
s3 = boto3.client("s3")
BUCKET = "example-uploads"
MAX_BYTES = 5 * 1024 * 1024
ALLOWED_TYPES = {"image/jpeg", "image/png"}
uploads = {} # stand-in for a database table
@app.post("/uploads")
def create_upload():
body = request.get_json(force=True)
content_type = body.get("content_type")
size = body.get("size")
if content_type not in ALLOWED_TYPES:
abort(400, "type not allowed")
if not isinstance(size, int) or not 0 < size <= MAX_BYTES:
abort(400, "bad size")
upload_id = uuid.uuid4().hex
key = f"incoming/{upload_id}" # the server chooses the key, never the client
post = s3.generate_presigned_post(
Bucket=BUCKET,
Key=key,
Fields={"Content-Type": content_type},
Conditions=[
{"Content-Type": content_type},
["content-length-range", 1, MAX_BYTES],
],
ExpiresIn=300,
)
uploads[upload_id] = {"key": key, "status": "pending", "type": content_type}
return jsonify({"id": upload_id, "url": post["url"], "fields": post["fields"]})
@app.post("/uploads/<upload_id>/complete")
def complete_upload(upload_id):
record = uploads.get(upload_id)
if record is None:
abort(404)
try:
head = s3.head_object(Bucket=BUCKET, Key=record["key"])
except ClientError as err:
if err.response["Error"]["Code"] in ("404", "NoSuchKey", "NotFound"):
abort(409, "object not found in storage")
raise
if head["ContentLength"] > MAX_BYTES:
abort(422, "object too large")
record["status"] = "uploaded"
return jsonify({"id": upload_id, "status": record["status"]})Three design choices in this code are worth copying.
- The server picks the key. If the client chose it, a user could overwrite another user's file or write outside the prefix you intended. A random identifier also keeps user-supplied file names out of your key space.
- The record is created before the upload. The
pendingrow gives you something to reconcile and clean up later. - Completion is verified, not trusted. The
completeendpoint asks storage what actually exists. A client that callscompletewithout uploading gets a409, not a ready file.
On the client, send the signed fields first and the file last, as shown in the earlier code example for the browser upload. S3 ignores form fields that come after the file field, so a misplaced file makes the policy check fail.
Telling your backend an upload finished
There are two ways to learn that the object exists.
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Client callback | Client calls `/complete` after the storage response | Simple, immediate user feedback | Client may crash or go offline before calling it |
| Storage event | Storage emits an event (for example an S3 event notification to a queue) on object creation | Reliable, independent of the client | Slight delay, and you must handle duplicate and out-of-order events |
Use both for important flows. The callback gives the UI a fast answer. The event is the source of truth that moves the record forward and triggers processing, which later chapters build on. Make the transition to uploaded idempotent, so running it twice has the same result as running it once.
Configuring the bucket for browser uploads
Browsers enforce the same-origin policy, so a page on app.example.com cannot POST to the storage endpoint unless the bucket allows it through CORS (cross-origin resource sharing). A minimal rule looks like this:
{
"CORSRules": [
{
"AllowedOrigins": ["https://app.example.com"],
"AllowedMethods": ["POST", "PUT"],
"AllowedHeaders": ["*"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 3000
}
]
}List exact origins, not *, for any bucket that accepts writes. ExposeHeaders includes ETag because browser JavaScript can read a cross-origin response header only if the server exposes it, and resumable uploads (a later chapter) depend on reading it.
Common errors
- CORS failure that looks like a network error. The browser reports a generic failure and hides the real status. Check the bucket CORS rules and open the browser's network tab for the preflight request.
403after a delay. The signed data expired, or the client's clock and the signature disagree. Request fresh data close to the moment of upload, and use short lifetimes.403on a policy mismatch. TheContent-Typesent in the form differs from the one pinned in the policy. Send exactly what the server signed.400from a misplacedfilefield. Append the file last.- Trusting the client's reported size or type. Declared metadata is a hint. The policy enforces the size range, and content signature checks run after upload.
- Treating
uploadedassafe. The object exists in your bucket, but nobody has scanned or inspected it. Keep it under a private, non-public prefix and out of delivery paths until validation passes. - Abandoned uploads. Users close the tab. Pending records and partial objects accumulate. Expire old
pendingrows, and add lifecycle rules that clean up the leftovers (covered in the final chapter).
When to keep the proxy
Direct upload is not always the better choice. Stay with a proxied upload when files are tiny and bounded, when you must transform or reject bytes inline before they are stored, or when your environment cannot expose a storage endpoint to clients. A small avatar form behind an existing API gateway may not justify the extra state machine. Choose direct upload when file sizes are large or unbounded, when upload volume is spiky, or when long, slow transfers would otherwise tie up your servers.
Exercise
A client calls your /uploads/{id}/complete endpoint, but its upload to storage failed and no object exists. Which response should the endpoint return, and which part of the design guarantees it?
Show answer
It should return an error such as 409 Conflict. The endpoint does not trust the client's claim. It calls head_object against storage, receives a not-found error, and refuses to move the record from pending to uploaded.
Exercise
Name two reasons the server, not the client, should choose the object key in a direct upload, and one reason to create the pending database record before returning the signed data.
Show answer
The server should choose the key because a client-chosen key could overwrite another user's object or escape the intended prefix, and because user-supplied file names would enter your key space. The pending record gives you a row to reconcile against storage events and to expire if the upload is abandoned, so incomplete uploads can be found and cleaned up.