Sub topic 9
Reacting to Completed Uploads with an Asynchronous Pipeline
This chapter assumes you know how presigned uploads work, that you have a bucket with a quarantine prefix, and that you have used a queue or a serverless function before. Once the browser has sent a file straight to storage, your API server never sees the bytes. Something else has to notice the upload and act on it.
Why not do the work in the request?
Scanning, resizing, and transcoding can take seconds or minutes. If the client waits for them, requests time out and one slow file ties up a worker. The common design is to accept the upload quickly, record it as pending, and do the heavy work in the background.
The working model
Object storage can emit an event when an object is created. That event goes to a queue, and workers read from the queue at their own pace.
The queue is the important part. Without it, a burst of uploads or a failing worker loses events. With it, messages wait and can be retried.
A worker
This worker reads S3 event notifications delivered to an SQS queue. It reads the object key from each message, processes the file, and deletes the message only after it succeeds.
import json
from urllib.parse import unquote_plus
import boto3
sqs = boto3.client("sqs")
QUEUE_URL = "https://sqs.eu-west-1.amazonaws.com/123456789012/uploads-events"
def process(bucket: str, key: str) -> None:
# Scan, validate, create variants, update the database.
# Must be safe to run twice for the same key.
print(f"processing {bucket}/{key}")
def poll_once() -> None:
resp = sqs.receive_message(
QueueUrl=QUEUE_URL, MaxNumberOfMessages=10, WaitTimeSeconds=20
)
for msg in resp.get("Messages", []):
body = json.loads(msg["Body"])
for record in body.get("Records", []):
bucket = record["s3"]["bucket"]["name"]
key = unquote_plus(record["s3"]["object"]["key"])
process(bucket, key)
sqs.delete_message(
QueueUrl=QUEUE_URL, ReceiptHandle=msg["ReceiptHandle"]
)
if __name__ == "__main__":
while True:
poll_once()Event keys are URL-encoded, so a space arrives as +. Decode them before use.
Common errors
- Not being idempotent. Delivery is at least once, so the same event can arrive twice. Use the object key or a database status check so a second run does no harm.
- Deleting the message too early. If you delete before the work finishes, a crash loses the job. Delete last.
- Writing output under the trigger prefix. If the worker writes thumbnails into
incoming/, each output fires a new event and you get a loop. Write to a different prefix, and filter the trigger by prefix. - No dead-letter queue. A corrupt file can fail forever. Set a maximum receive count and move failures to a dead-letter queue that you monitor.
- Trusting the event's claims. Re-read the object's size and content type from storage, and check the file's signature, before processing.
Tracking state
Store a status for each upload, such as pending, processing, ready, or rejected. The client shows a placeholder until the status is ready. Update it with a conditional write, so two workers do not both claim the same file.
Exercise
Your worker writes resized images to the same incoming/ prefix that triggers the upload event. What happens, and how do you fix it?
Show answer
Each resized image creates a new event, so the worker processes its own output in a loop. Write outputs to a different prefix such as media/, and restrict the event trigger to the incoming/ prefix.
Exercise
Why must the worker be idempotent, and why should it delete the queue message only after processing succeeds?
Show answer
The queue delivers messages at least once, so duplicates happen and a repeat run must not cause harm. Deleting only after success means a crash leaves the message in the queue to be retried instead of losing the job.