
Process the Right File: Version-Aware S3 Workflows That Survive Retries
Build a version-aware S3 and Lambda text pipeline with deterministic output keys, conditional writes, recovery steps, and original Python code.
A supplier uploads
incoming/notes.txt . They correct a typo and upload the same key again. The notification for the first upload arrives after the notification for the second.If a worker simply calls
GetObject with the key, it may read the newest bytes while handling an older event. A retry can also overwrite an output that was already produced correctly.This article builds a small, concrete remedy: read an exact S3 object version, derive a result key from that version and the processor version, and create the result with a conditional write.
Scope: this is a UTF-8 text-processing tutorial, not a PDF/OCR platform. The sample counts words and lines in files up to 1 MiB. Code and illustrations were prepared with AI assistance. Six local tests passed using a fake S3 client; no AWS resources were deployed, and no cloud performance claims are made.

1. The real-world case: supplier document revisions
A small procurement team receives corrected delivery notes throughout the day. For this walkthrough, the documents are
.txt files. Each upload is a separate source version that needs its own traceable report.Our business rule is: a report belongs to one exact upload version and one processor version. Replaying the same identity should not replace the report. A correction gets a different report.

S3 event notifications are designed for at-least-once delivery, and they are not guaranteed to arrive in order. This design does not try to make delivery exactly once. It makes the result address stable and the write conditional. AWS: S3 event notifications
2. Architecture and the deliberate trade-off

Use a versioning-enabled general-purpose S3 source bucket, a Python Lambda function, and a separate output bucket. Configure only
ObjectCreated notifications for incoming/ keys ending in .txt .Two buckets keep result writes from retriggering the source pipeline. Neither bucket needs public access. An upstream authenticated upload service should enforce tenant and file boundaries; this example does not expose an upload endpoint.
The function can repeat computation on a replay. That is acceptable for this inexpensive transform. We are preventing duplicate persisted results, not promising that compute runs only once. An expensive OCR/ML job would need a durable job state machine and different failure handling.
3. Choose an identity that survives reordering
The result key hashes a JSON tuple:
[source bucket, decoded source key, source versionId, processor version]
The event's object key is form-URL-encoded, so use
unquote_plus : an encoded space can appear as + . Require a non-null versionId . Reject unversioned uploads instead of silently falling back to the current object.The
sequencer field can help order events for the same key; it is not a global clock for different keys. We do not need a latest-version pointer because we preserve each version independently. AWS: notification structure Changing the transform's meaning requires changing
PROCESSOR . Otherwise a deliberate software upgrade could collide with a previous result identity.4. Original implementation
Save this as
app.py , set the Lambda handler to app.handler , and configure SOURCE_BUCKET and OUTPUT_BUCKET environment variables. Use a current Boto3/Botocore version supporting IfNoneMatch on put_object ; for production, bundle and pin a tested SDK rather than relying on an unspecified runtime version.
"""Process immutable UTF-8 text versions into deterministic S3 reports."""import hashlibimport jsonimport osfrom urllib.parse import unquote_plus
MAX_BYTES = 1024 * 1024PROCESSOR = "wordcount-v1"
def identity(record, expected_bucket): if record.get("eventSource") != "aws:s3": raise ValueError("Expected S3 event") if not record.get("eventName", "").startswith("ObjectCreated:"): raise ValueError("Expected ObjectCreated") source = record["s3"] bucket = source["bucket"]["name"] key = unquote_plus(source["object"]["key"]) version = source["object"].get("versionId") if bucket != expected_bucket or not key.startswith("incoming/"): raise ValueError("Unexpected source") if not key.endswith(".txt") or not version or version == "null": raise ValueError("A versioned text object is required") raw = json.dumps([bucket, key, version, PROCESSOR], ensure_ascii=True, separators=(",", ":")) digest = hashlib.sha256(raw.encode()).hexdigest() return bucket, key, version, f"reports/{PROCESSOR}/{digest}.json"
def process_record(s3, record, source_bucket, output_bucket): bucket, key, version, result_key = identity(record, source_bucket) obj = s3.get_object(Bucket=bucket, Key=key, VersionId=version) stream = obj["Body"] try: if obj["ContentLength"] > MAX_BYTES: raise ValueError("Input too large") data = stream.read(MAX_BYTES + 1) finally: stream.close() if len(data) > MAX_BYTES: raise ValueError("Input too large") text = data.decode("utf-8") report = {"processor": PROCESSOR, "source_version_id": version, "source_sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data), "words": len(text.split()), "lines": len(text.splitlines())} body = json.dumps(report, sort_keys=True, separators=(",", ":")).encode() try: s3.put_object(Bucket=output_bucket, Key=result_key, Body=body, ContentType="application/json", IfNoneMatch="*") return "CREATED", result_key except Exception as error: response = getattr(error, "response", {}) if response.get("ResponseMetadata", {}).get("HTTPStatusCode") != 412: raise # Existing output is success only if it matches our exact result. old = s3.get_object(Bucket=output_bucket, Key=result_key) old_stream = old["Body"] try: existing = old_stream.read(len(body) + 1) finally: old_stream.close() if existing != body: raise ValueError("Existing result does not match") from error return "DUPLICATE", result_key
def handler(event, context): import boto3 s3 = boto3.client("s3") # Direct S3 invocation: exception fails the entire invocation, not one item. for record in event["Records"]: outcome, _ = process_record(s3, record, os.environ["SOURCE_BUCKET"], os.environ["OUTPUT_BUCKET"]) print(json.dumps({"outcome": outcome, "processor": PROCESSOR}))
Why the conditional write matters
IfNoneMatch="*" asks S3 to create the object only when the destination key is absent. If another worker already wrote it, S3 can return HTTP 412. We then compare the stored bytes with the deterministic report. A mismatch is a visible error, not a successful duplicate.A 409 conflict or another failure is raised for the asynchronous retry path. We do not suppress all exceptions as duplicates. AWS: conditional writes
This protection depends on retaining the result. Deleting it, or creating a current delete marker in a versioned result bucket, can make a future conditional creation succeed. Restrict deletion/overwrite permissions and design lifecycle retention around your replay horizon. Conditional writes are not an immutability policy by themselves.
5. Apply it in an AWS sandbox
The following is a deployment checklist, not a claim of a completed cloud run. Resources and requests can incur charges.
- Create two private general-purpose S3 buckets in one Region. Enable versioning on the source before uploading test data. Keep Block Public Access enabled.
- Create a Python 3.12 Lambda function with the code above and the two bucket environment variables. For this small workload, start with 256 MB and a 30-second timeout, then measure.
- Give its execution role CloudWatch Logs access,
s3:GetObjectVersionon the sourceincoming/*objects, ands3:PutObjectpluss3:GetObjecton outputreports/*objects. Scope resources to your buckets. SSE-KMS needs the corresponding key permissions; this walkthrough assumes the default S3 encryption arrangement.
- Add an S3 trigger for
ObjectCreatedwith prefixincoming/and suffix.txt. Verify Lambda's resource-based permission allows invocation from this source bucket/account. The console trigger workflow can create this permission; inspect it.
- Configure Lambda asynchronous failure handling deliberately: bounded event age/retry attempts and an on-failure SQS destination. Give the function role permission to send to that destination. A destination delivery failure also needs monitoring. This is direct S3 invocation, so SQS partial-batch response JSON would not apply.
- Configure alarms for Lambda errors/throttles, destination delivery failures, and visible failure-queue messages. Set a short log retention for the sandbox.
For a minimal IAM starting point, substitute your bucket names in these statements; add logging and destination permissions separately:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:GetObjectVersion", "Resource": "arn:aws:s3:::YOUR_SOURCE_BUCKET/incoming/*" }, { "Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject"], "Resource": "arn:aws:s3:::YOUR_OUTPUT_BUCKET/reports/*" } ]}Source version reads require
s3:GetObjectVersion . Review encryption and identity permissions against the GetObject API documentation . For invocation failure settings and destinations, see AWS: asynchronous error handling and AWS: asynchronous destinations .6. Demonstrate a revision and a replay
Use fictional input only. From Bash with AWS CLI v2 authenticated to your sandbox:
printf 'hello AWS\nretry safely\n' > notes.txtaws s3api put-object --bucket YOUR_SOURCE_BUCKET --key incoming/notes.txt --body notes.txtSave the returned
VersionId as v1. Change the contents, upload the same key again, and save the new version as v2. Wait for processing, then list reports/wordcount-v1/ in the output bucket.Expected: two distinct output keys. Each report includes its source version ID and a SHA-256 of the source bytes. For the first sample, the expected report has four whitespace-separated words, two lines, and 23 bytes. “Word” here means Python's whitespace splitting, not language-aware tokenization.
To test an actual replay, capture the original S3 event in a controlled sandbox (extract
requestPayload from a Lambda on-failure destination record before invoking this handler) or construct a Lambda test event with the same bucket, encoded key, and actual version ID. Invoke it twice. Both invocations should address the same report key; a matching existing report produces DUPLICATE .Do not claim that uploading the same bytes twice tests duplication: two uploads produce two different version IDs. A duplicate notification reuses the identity of one upload.

7. Local verification and honest limits

The companion tests cover URL decoding, distinct version identities, rejection of a null version, bucket restriction, duplicate output, and mismatched existing output. All six passed locally using an in-memory fake:
python -m unittest -vThey do not establish AWS IAM correctness, deployment success, service concurrency behavior, or production readiness. Before production, test simultaneous writes, a timeout after successful PUT, lost responses, malformed UTF-8, oversized inputs, expired source versions, and destination failures in a disposable account.
8. Recovery and operating boundaries
- Older versions must remain readable. Source lifecycle rules that remove noncurrent versions too soon can break delayed events and replay.
- A failure destination is evidence, not a cure. Investigate the original event, source-version availability, and result before retrying.
- No external side effects are hidden here. Adding email, payments, or database writes requires their own consistency/idempotency design.
- Avoid payload logging. The worker logs outcomes, not document contents. Add correlation IDs that respect your privacy requirements.
- Observe cost honestly. Every duplicate still reads the input and attempts a write; conditional failures can incur request charges. Version retention adds storage costs.
- Protect output invariants. Restrict other writers and destructive actions. If stronger retention controls are required, evaluate them explicitly instead of calling a conditional PUT “immutable storage.”
When done, remove the sandbox notification, function, failure queue, logs, and buckets after exporting anything needed. Versioned buckets require handling all object versions and delete markers before deletion; do not apply cleanup to production buckets.
The useful design decision is to make a report's source identity explicit. Events may arrive twice or late; a version-aware read and a conditional result write keep those delivery behaviors from silently changing what your report means.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article