Sub topic 4
Uploading directly to storage and keeping your servers out of the data path
This chapter assumes you know HTTP methods and headers, the client, API server, and database layout of a web app, and what object storage such as Amazon S3 is. It also assumes you have read the previous chapter on proxied uploads and on object storage and key design.
Why proxying hurts
In a proxied upload, the file travels from the client to your API server, and then from the server to storage. Every byte crosses your servers twice. This causes three problems:
- Bandwidth and memory. A 500 MB video holds a connection, and often a buffer or temp file, for the whole transfer.
- Slow clients. A phone on a weak network keeps an application worker busy for minutes. Those workers are the scarce resource for your real API traffic.
- Scaling. You must scale API servers to match upload volume, not request volume.
In a direct upload, the client sends the file straight to the storage service. Your server only decides whether the upload is allowed, and it does that with a small request.
The three-step flow
- The client asks your API for permission to upload, sending metadata such as file name, declared type, and size.
- The API checks the user and the metadata. It then returns a short-lived, narrowly scoped grant, which is a presigned URL or a presigned POST policy (covered in the next chapter).
- The client sends the file to the storage endpoint using that grant. Afterward it tells your API the upload is done, or storage emits an event.
The server side
The server generates the grant with its own credentials. The client never sees them.
import boto3
s3 = boto3.client("s3")
post = s3.generate_presigned_post(
Bucket="example-uploads",
Key="incoming/3f2a9c/avatar.jpg",
Fields={"Content-Type": "image/jpeg"},
Conditions=[
{"Content-Type": "image/jpeg"},
["content-length-range", 1, 5 * 1024 * 1024],
],
ExpiresIn=300,
)
# Return post["url"] and post["fields"] to the client.The server picks the key. Never let the client choose it, or users could overwrite each other's files.
The client side
The browser sends the returned fields and then the file in a multipart/form-data POST.
async function upload(post, file) {
const form = new FormData();
for (const [name, value] of Object.entries(post.fields)) {
form.append(name, value);
}
form.append("file", file); // the file field must come last
const res = await fetch(post.url, { method: "POST", body: form });
if (!res.ok) {
throw new Error(`Upload failed with status ${res.status}`);
}
}What you give up
Moving the data path away from your servers also removes the place where you could inspect the file. Plan for these gaps:
| Concern | Proxied upload | Direct upload |
|---|---|---|
| Server load | High | Low |
| Inspect bytes before storing | Yes | No, validate after |
| Size and type limits | In your code | In the signed policy |
| Knowing the upload finished | Immediate | Needs a callback or event |
| Database record | Created with the file | Can point at a missing object |
Because the server never sees the bytes, treat every directly uploaded object as untrusted. Write it to a staging prefix such as incoming/, and verify it later with signature checks and scanning. Create the database record in a "pending" state, and mark it ready only when the upload-complete event arrives. If the client never finishes, the record stays pending, and a cleanup job can remove it.
Common errors
- File field not last. S3 ignores form fields that come after
file, so the policy check fails. - Mismatched fields. The
Content-Typesent must match the policy condition exactly. - Expired grant. A five-minute expiry is short on slow networks. Request a fresh grant if the upload has not started in time.
- Trusting the client's "done" call. A client can claim success without uploading. Confirm with the storage event or a
HEADrequest.
Exercise
Your API issues a presigned POST for an avatar upload. A user reports that the upload returns 403 even though the grant is fresh. The client code appends the file to the form first and then adds the policy fields. What is the likely cause, and how do you fix it?
Show answer
S3 requires the file field to be the last field in the multipart form, and it ignores fields after it. With the policy fields placed after the file, the signature and policy fields are missing from the check, so S3 rejects the request. Append all returned fields first and append the file last.