Sub topic 9
Reacting to Completed Uploads with an Asynchronous Pipeline
This chapter assumes you know what the previous chapters covered: a client uploads straight to object storage with a presigned URL or POST policy, and the object lands under an incoming/ prefix. Your API server never sees the bytes. This chapter covers how it finds out that the upload finished and what work it starts. The examples use Amazon S3 and Python. The same ideas apply to other object stores that emit events.
Why the work must be asynchronous
After an upload, you usually need to scan for malware, check the file signature, make image variants, transcode video, extract metadata, and update the database. Some of these steps take seconds and some take minutes. Doing them inside a web request ties up a connection. It also loses the work if the request times out.
An asynchronous pipeline separates three concerns:
- Detection: the storage service announces that an object exists.
- Buffering: a queue holds the announcement until a worker is ready.
- Processing: workers do the slow work and record the result.
The client does not wait for any of this. It gets a status such as processing and checks again later, or it receives a notification when the job is done.
The flow
Choosing how to receive events
S3 can send an ObjectCreated event to several targets. Each has different trade-offs.
| Target | Strengths | Weaknesses |
|---|---|---|
| Lambda function directly | Fewest parts. Scales automatically. | Failures are retried a limited number of times. Bursts hit the function with no buffer. |
| SQS queue | Buffers bursts. Gives you retries, a visibility timeout, and a dead-letter queue. | One more component to configure. |
| EventBridge | Rich filtering and routing to many targets. | Slightly higher latency. More configuration. |
For anything beyond a simple thumbnail, an SQS queue between the bucket and the workers is a good default. It lets you control concurrency, so a burst of 10,000 uploads does not start 10,000 simultaneous transcodes. It also keeps failed work for inspection.
What the event contains
The event tells you the bucket, the key, the size, and the ETag. It does not contain the file. A notification delivered through SQS has this shape (trimmed):
{
"Records": [
{
"eventName": "ObjectCreated:Post",
"s3": {
"bucket": { "name": "example-uploads" },
"object": {
"key": "incoming/3f2a9c/my+avatar.jpg",
"size": 48213,
"eTag": "0123456789abcdef0123456789abcdef",
"sequencer": "0055AED6DCD90281E5"
}
}
}
]
}Two details cause frequent bugs. First, the key is URL-encoded, and a space appears as +. You must decode it before calling the storage API, or you will get "not found" for any file name with special characters. Second, a multipart upload produces ObjectCreated:CompleteMultipartUpload, a presigned POST produces ObjectCreated:Post, and a presigned PUT produces ObjectCreated:Put. Subscribe to ObjectCreated:* unless you have a reason to separate them.
A worker with idempotent processing
Event delivery is at-least-once. The same event can arrive twice, and a worker can crash halfway through a job. Your worker must be safe to run repeatedly on the same object. Two habits make this work:
- Write outputs to deterministic keys, so a second run overwrites the first with identical data.
- Record completion in a table, so a repeat delivery can skip the work.
The example below is a Lambda handler for an SQS trigger. It decodes keys, ignores the test event S3 sends when you configure notifications, checks the file signature using a ranged read of the first bytes, copies valid files to a processed/ prefix, and records the result. It reports failures per message, so one bad message does not force the whole batch to be retried. This requires ReportBatchItemFailures to be enabled on the event source mapping.
import json
from urllib.parse import unquote_plus
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client("s3")
dynamodb = boto3.client("dynamodb")
JOBS_TABLE = "upload-jobs"
SIGNATURES = {
"image/jpeg": b"\xff\xd8\xff",
"image/png": b"\x89PNG\r\n\x1a\n",
}
def parse_uploads(body: str):
message = json.loads(body)
for record in message.get("Records", []): # test events have no Records
if not record["eventName"].startswith("ObjectCreated:"):
continue
obj = record["s3"]["object"]
yield {
"bucket": record["s3"]["bucket"]["name"],
"key": unquote_plus(obj["key"]),
"etag": obj.get("eTag", ""),
}
def is_done(job_id: str) -> bool:
item = dynamodb.get_item(
TableName=JOBS_TABLE, Key={"job_id": {"S": job_id}}
).get("Item")
return item is not None and item["status"]["S"] in ("ready", "rejected")
def set_status(job_id: str, status: str) -> None:
dynamodb.put_item(
TableName=JOBS_TABLE,
Item={"job_id": {"S": job_id}, "status": {"S": status}},
)
def process(upload: dict) -> None:
bucket, key = upload["bucket"], upload["key"]
if not key.startswith("incoming/"):
return # never react to our own outputs
job_id = f"{key}#{upload['etag']}"
if is_done(job_id):
return # duplicate delivery
head = s3.get_object(Bucket=bucket, Key=key, Range="bytes=0-15")["Body"].read()
declared = s3.head_object(Bucket=bucket, Key=key)["ContentType"]
signature = SIGNATURES.get(declared)
if signature is None or not head.startswith(signature):
set_status(job_id, "rejected")
return
target = "processed/" + key[len("incoming/"):]
s3.copy_object(
Bucket=bucket,
Key=target,
CopySource={"Bucket": bucket, "Key": key},
)
set_status(job_id, "ready")
def handler(event, context):
failures = []
for sqs_record in event["Records"]:
try:
for upload in parse_uploads(sqs_record["body"]):
process(upload)
except ClientError:
failures.append({"itemIdentifier": sqs_record["messageId"]})
return {"batchItemFailures": failures}In a real pipeline, the copy step is where you would call your image resizer or submit a transcoding job. The structure around it stays the same.
Failure modes to design for
Infinite loops. If the worker writes its output into the same bucket and prefix that triggers it, each output creates a new event, which creates another output. Prevent this by writing to a different prefix or bucket, and by configuring the notification with a prefix filter such as incoming/. The startswith check in the code is a second safeguard.
Visibility timeout shorter than the job. If a message becomes visible again while a worker is still processing it, a second worker takes it. Set the queue's visibility timeout to more than the longest expected job. For long jobs, extend the timeout while working.
Poison messages. A corrupt file that always crashes the worker will be retried forever without a limit. Configure a dead-letter queue with a maxReceiveCount of 3 to 5, and alert when it has messages. Keep the original object so you can replay the message after fixing the bug.
Lost events. Notifications are reliable but not guaranteed to be instantaneous or in order. A pipeline that depends on events alone can leave an object unprocessed if the configuration was broken at the time. Run a periodic reconciliation job that lists objects in incoming/ older than some threshold, and enqueue the ones with no completed job record.
Out-of-order events. If a user overwrites a key quickly, you may see the events for the two versions in either order. Using the ETag in the job ID, as above, keeps the versions separate. Better still, give every upload a unique key, which is the key design recommended earlier in this tutorial.
Racing the client. The client can finish its upload and ask for the file before the pipeline has run. The API should return the status, not assume the processed file exists.
Tracking status
The job table is the source of truth for the user interface. A small set of states is enough:
uploading: the server issued a presigned URL, but no event has arrived.processing: the event arrived and a worker has claimed the job.ready: all outputs exist.rejected: validation or scanning failed, with a reason code.failed: processing gave up after retries, and the message is in the dead-letter queue.
Write the uploading row when you issue the presigned URL, and store the user ID and intended key. When the worker finishes, it updates that row. Clients can poll GET /uploads/{id} or receive a push over WebSocket or server-sent events. Polling every few seconds with backoff is simple and works well for jobs of this size.
Chaining stages
When you add malware scanning (covered in the quarantine chapter), the order matters. The first stage reacts to incoming/, scans, and moves clean files to a clean/ prefix. The second stage reacts to clean/ and builds variants. A file that fails scanning never reaches the stage that makes it publicly available. Because each stage reads from a prefix and writes to a different one, the loop problem cannot occur.
Exercise
Your worker receives the same S3 event twice and processes the file twice, creating two thumbnail records in the database. Name two changes that make the pipeline safe against duplicate delivery.
Show answer
First, write outputs to deterministic keys (derived from the source key and ETag), so a repeat run overwrites the same object with the same data. Second, record job completion in a table keyed by a job ID, such as the key plus ETag, and skip the work if the job is already finished. Making the database write an upsert or a conditional insert also prevents duplicate thumbnail rows.
Exercise
Users report that uploaded files with spaces in their names stay in the "processing" state forever, and the queue shows repeated errors from the worker. What is the most likely cause, and what is the fix?
Show answer
The S3 event delivers the key URL-encoded, with spaces as "+". The worker passes the encoded key to getobject, so the object is not found and the message is retried until it reaches the dead-letter queue. Decode the key with urllib.parse.unquoteplus before using it. A better long-term fix is to generate server-side keys without user-supplied file names.