Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions s3-multipart-getpart-sqs-lambda/typescript/cdk/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
cdk.out/
build/
cdk.context.json
package-lock.json
133 changes: 133 additions & 0 deletions s3-multipart-getpart-sqs-lambda/typescript/cdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Process Amazon S3 multipart upload parts while the upload is in progress with Amazon SQS and AWS Lambda

This pattern sends the Amazon S3 `s3:MultipartUpload:PartUploaded` event for each uploaded part to an Amazon SQS queue. An AWS Lambda function reads that part with the Amazon S3 GetPart API before the upload completes, hashes it, and records it in an Amazon DynamoDB part ledger, which is marked COMPLETE or ABORTED when the upload ends.

Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/s3-multipart-getpart-sqs-lambda-typescript-cdk

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. No resource in the stack has an hourly or provisioned charge: you pay for Amazon S3 requests and storage (each part read is a GET request), Amazon SQS requests, Lambda invocations and DynamoDB on-demand writes.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) installed
* [Node.js](https://nodejs.org/en/download/) installed (the AWS CDK app and the function are written in TypeScript)
* [AWS CDK v2](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html), with your account and Region bootstrapped (`npx cdk bootstrap`). The commands below use `npx cdk`, which runs the CDK CLI version this project installs, so no global install is needed. The function is bundled with esbuild from the project's dev dependencies, so Docker is not needed.

## Supported Regions

The [announcement](https://aws.amazon.com/about-aws/whats-new/2026/11/amazon-s3-supports-reading-parts-multipart-uploads/) lists all AWS Regions, but when this pattern was written (November 30, 2026) both `PartUploaded` events and GetPart on an in-progress upload were seen working only in us-east-1. In ap-south-1 GetPart worked but no `PartUploaded` events arrived. GetPart returned `405 MethodNotAllowed` in us-east-2, us-west-2, eu-central-1, eu-west-1 and ap-southeast-1, and in us-west-2 the bucket accepted the notification configuration but delivered no `PartUploaded` events. Deploy in us-east-1. In another Region, depending on the Region, part events either do not arrive, so no parts are recorded, or GetPart fails with `MethodNotAllowed` and the message goes to the dead-letter queue after five tries.

## How it works

1. A client starts a multipart upload and uploads parts. Amazon S3 sends one `s3:MultipartUpload:PartUploaded` event per uploaded part to the queue, with the upload ID, part number, part size and part ETag in a `multipartUploadEventData` block. It also sends `s3:ObjectCreated:CompleteMultipartUpload` and `s3:MultipartUpload:Aborted`, which carry the upload ID too.
2. The Lambda function reads the queue in batches of 10. For each part event it calls GetPart with the upload ID and part number and streams the part through a SHA-256 hash (parts can be up to 5 GiB, so they are not buffered). When the client sent a SHA-256 checksum, the function compares its hash with the SHA-256 checksum that GetPart returns.
3. The function creates an `UPLOAD` item with status `IN_PROGRESS` if there is none, then writes one item per part to the ledger (`pk` = upload ID, `sk` = `PART#00001`) with the hash, the checksum result and the upload status that GetPart reported (`IN_PROGRESS` or `COMPLETED`).
4. The completion and abort events set the `UPLOAD` item to `COMPLETE` (with the object size and ETag) or `ABORTED`.

Amazon S3 delivers event notifications at least once and not in order, so the ledger is written with conditions:

* A part number can be uploaded again while the upload is in progress, and GetPart returns the newest copy. When the event ETag differs from the GetPart ETag, the event describes replaced bytes: the function logs `superseded` and writes nothing.
* A part item is written only when it is new, or when the event is a newer upload of that part (different ETag, later `eventTime`). A repeated or older event is logged as `duplicate`.
* The completion event can arrive before the last part event. GetPart still works after completion, so the late part is recorded with `uploadStatusAtRead` `COMPLETED`, and a `COMPLETE` or `ABORTED` upload item is never moved back.
* `NoSuchUpload` (for example, an aborted upload) and `NoSuchPart` cannot succeed on a retry, so those records are skipped. Any other error returns the message as a batch item failure: Amazon SQS retries only that message and moves it to the dead-letter queue after five receives.

## Important Notes

* The queue sits between Amazon S3 and Lambda to absorb bursts of parallel part uploads, to batch them, to retry one failed part without the rest of the batch, and to keep failed parts in the dead-letter queue.
* GetPart works only for uploads started after November 29, 2026, 00:00 UTC, in general purpose buckets, without SSE-C and not through S3 Access Points. It does not work for uploads completed with non-consecutive part numbers, or for completed objects in S3 Glacier Flexible Retrieval, S3 Glacier Deep Archive or S3 Intelligent-Tiering. See the [GetPart API reference](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPart.html).
* Reading a part in progress needs `s3:GetIncompleteUpload` in addition to `s3:GetObject`. The function role has both, on this bucket's objects only.
* Parts written with UploadPartCopy send `s3:MultipartUpload:PartCopied`, which this stack does not subscribe to, so copied parts are not in the ledger.
* The Lambda runtime includes a fixed version of the AWS SDK for JavaScript that may not have GetPart yet, so the function bundles `@aws-sdk/client-s3` from `package.json`. aws-cdk-lib has no `s3.EventType` value for the part events yet, so the stack casts the documented event names.
* The function reads the records of a batch one after another, so its 2 minute timeout must cover a whole batch of up to 10 parts, not one part. A timeout returns every message of the batch to the queue, including parts already recorded, and after five timeouts all of them move to the dead-letter queue. For large parts, lower `batchSize`, or raise the timeout and the queue visibility timeout together.
* The bucket aborts incomplete uploads after one day, because their parts are billed until then. Besides the part reader, the stack has two CDK helper functions: one configures the bucket notifications and one empties the bucket on `cdk destroy`.

## Deployment Instructions

1. Clone the repository:
```bash
git clone https://github.com/aws-samples/serverless-patterns
cd serverless-patterns/s3-multipart-getpart-sqs-lambda/typescript/cdk
```
2. Install the dependencies:
```bash
npm install
```
3. Deploy the stack in us-east-1 (see Supported Regions; run `npx cdk bootstrap` first if the account and Region are not bootstrapped):
```bash
export AWS_REGION=us-east-1
npx cdk deploy
```
The outputs are `BucketName`, `TableName`, `DeadLetterQueueUrl` and `PartReaderLogGroupName`.

## Testing

1. Set the Region and read the stack outputs (run this again in a new terminal):
```bash
export AWS_REGION=us-east-1
out() { aws cloudformation describe-stacks --stack-name S3MultipartGetpartSqsLambdaStack --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue" --output text; }
BUCKET=$(out BucketName); TABLE=$(out TableName); DLQ=$(out DeadLetterQueueUrl); LOG_GROUP=$(out PartReaderLogGroupName)
```
2. Start an upload and upload two 5 MiB parts with SHA-256 checksums. Do not complete it yet. Run steps 2 to 6 in the same terminal, because they reuse `KEY`, `UPLOAD_ID` and `UPLOAD_ID2`:
```bash
head -c 5242880 /dev/urandom > /tmp/part1.bin; head -c 5242880 /dev/urandom > /tmp/part2.bin
KEY="uploads/sample-$(date +%s).bin"
UPLOAD_ID=$(aws s3api create-multipart-upload --bucket "$BUCKET" --key "$KEY" --checksum-algorithm SHA256 --query UploadId --output text)
for n in 1 2; do aws s3api upload-part --bucket "$BUCKET" --key "$KEY" --upload-id "$UPLOAD_ID" --part-number $n --body /tmp/part$n.bin --checksum-algorithm SHA256 --query ETag --output text; done
```
3. Wait about 10 seconds and read the ledger while the upload is still in progress, check that the object does not exist yet, then hash the files on your machine (on Linux, `sha256sum` prints the same):
```bash
sleep 10
aws dynamodb query --table-name "$TABLE" --key-condition-expression "pk = :u" --expression-attribute-values "{\":u\":{\"S\":\"$UPLOAD_ID\"}}" --query "Items[].[sk.S, uploadStatusAtRead.S, checksumMatch.BOOL, sha256Hex.S, status.S]" --output text
aws s3api head-object --bucket "$BUCKET" --key "$KEY"
shasum -a 256 /tmp/part1.bin /tmp/part2.bin
```
Expected: `PART#00001` and `PART#00002` with `IN_PROGRESS` and `True`, and a `sha256Hex` equal to the local hash of each file, plus an `UPLOAD` row with status `IN_PROGRESS`. `head-object` fails with `An error occurred (404) when calling the HeadObject operation: Not Found`, because the object exists only after the upload completes.
4. Complete the upload, wait about 10 seconds and read the upload item:
```bash
aws s3api list-parts --bucket "$BUCKET" --key "$KEY" --upload-id "$UPLOAD_ID" --query "{Parts: Parts[].{PartNumber: PartNumber, ETag: ETag, ChecksumSHA256: ChecksumSHA256}}" --output json > /tmp/parts.json
aws s3api complete-multipart-upload --bucket "$BUCKET" --key "$KEY" --upload-id "$UPLOAD_ID" --multipart-upload file:///tmp/parts.json
sleep 10
aws dynamodb get-item --table-name "$TABLE" --key "{\"pk\":{\"S\":\"$UPLOAD_ID\"},\"sk\":{\"S\":\"UPLOAD\"}}" --query "Item.[status.S, objectSize.N]" --output text
```
Expected: `COMPLETE` and `10485760`.
5. In a second upload, upload part 1 twice with different bytes, wait about 10 seconds, then read the ledger and the log:
```bash
head -c 5242880 /dev/urandom > /tmp/part1b.bin
UPLOAD_ID2=$(aws s3api create-multipart-upload --bucket "$BUCKET" --key uploads/reupload.bin --query UploadId --output text)
for f in part1 part1b; do aws s3api upload-part --bucket "$BUCKET" --key uploads/reupload.bin --upload-id "$UPLOAD_ID2" --part-number 1 --body /tmp/$f.bin --query ETag --output text; done
sleep 10
aws dynamodb query --table-name "$TABLE" --key-condition-expression "pk = :u" --expression-attribute-values "{\":u\":{\"S\":\"$UPLOAD_ID2\"}}" --query "Items[].[sk.S, partETag.S, status.S]" --output text
aws logs filter-log-events --log-group-name "$LOG_GROUP" --filter-pattern '"superseded"' --query "events[].message" --output text
```
Expected: `PART#00001` holds the second ETag that `upload-part` printed (without the quotes). The log shows `superseded` for the first event when it was processed after the second upload; if it was processed before, the item was written and then replaced, and the log shows nothing. On a second run the log also shows lines from earlier runs.
6. Abort the second upload, wait about 10 seconds, and check the upload item and the dead-letter queue:
```bash
aws s3api abort-multipart-upload --bucket "$BUCKET" --key uploads/reupload.bin --upload-id "$UPLOAD_ID2"
sleep 10
aws dynamodb get-item --table-name "$TABLE" --key "{\"pk\":{\"S\":\"$UPLOAD_ID2\"},\"sk\":{\"S\":\"UPLOAD\"}}" --query "Item.status.S" --output text
aws sqs get-queue-attributes --queue-url "$DLQ" --attribute-names ApproximateNumberOfMessages --query Attributes.ApproximateNumberOfMessages --output text
```
Expected: `ABORTED` and `0`.

## Cleanup

1. If you are in a new terminal, run Testing step 1 first so that `BUCKET` is set.
2. Abort every upload that is still open. The command prints nothing when there is none:
```bash
aws s3api list-multipart-uploads --bucket "$BUCKET" --query "Uploads[].[Key, UploadId]" --output text | while IFS=$'\t' read -r key id; do if [ -n "$id" ]; then aws s3api abort-multipart-upload --bucket "$BUCKET" --key "$key" --upload-id "$id" < /dev/null && echo "aborted $key"; fi; done
```
3. Delete the stack and remove the test files. `cdk destroy` deletes the bucket with its objects and the ledger table, so the data cannot be recovered:
```bash
npx cdk destroy
rm -f /tmp/part1.bin /tmp/part2.bin /tmp/part1b.bin /tmp/parts.json
```
4. The two CDK helper functions write to log groups that the stack does not manage. List them, check that each name belongs to this stack, and delete each one with `aws logs delete-log-group --log-group-name <name>`:
```bash
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/S3MultipartGetpart --query "logGroups[].logGroupName" --output text
```

----
Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
8 changes: 8 additions & 0 deletions s3-multipart-getpart-sqs-lambda/typescript/cdk/bin/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env node
import * as cdk from 'aws-cdk-lib';
import { S3MultipartGetpartSqsLambdaStack } from '../lib/s3-multipart-getpart-sqs-lambda-stack';

const app = new cdk.App();
new S3MultipartGetpartSqsLambdaStack(app, 'S3MultipartGetpartSqsLambdaStack', {
env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
});
3 changes: 3 additions & 0 deletions s3-multipart-getpart-sqs-lambda/typescript/cdk/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"app": "npx ts-node --prefer-ts-exts bin/app.ts"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"title": "Amazon S3 multipart upload parts to Amazon SQS and AWS Lambda with GetPart",
"description": "Amazon S3 sends each PartUploaded event to Amazon SQS. AWS Lambda reads the part with GetPart before the upload completes and records it in Amazon DynamoDB.",
"language": "TypeScript",
"level": "300",
"framework": "AWS CDK",
"introBox": {
"headline": "How it works",
"text": [
"A client uploads the parts of an Amazon S3 multipart upload. Amazon S3 sends an s3:MultipartUpload:PartUploaded event for each part, plus the completion and abort events, to an Amazon SQS queue with a dead-letter queue.",
"An AWS Lambda function reads the queue in batches, reads each part with the Amazon S3 GetPart API while the upload is still in progress, and streams it through a SHA-256 hash, which it compares with the SHA-256 checksum that Amazon S3 returns when the client sent one.",
"The function keeps a part ledger in Amazon DynamoDB. Conditional writes make it safe for duplicate, out-of-order and superseded part events, and the completion or abort event closes the upload item.",
"This pattern deploys one AWS Lambda function for the parts and two AWS CDK helper functions for the bucket notifications and for emptying the bucket on delete."
]
},
"gitHub": {
"template": {
"templateFile": "lib/s3-multipart-getpart-sqs-lambda-stack.ts"
}
},
"resources": {
"bullets": [
{
"text": "Amazon S3 GetPart API reference",
"link": "https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPart.html"
},
{
"text": "Amazon S3 event notification types and destinations",
"link": "https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-how-to-event-types-and-destinations.html"
},
{
"text": "Using AWS Lambda with Amazon SQS",
"link": "https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html"
}
]
},
"deploy": {
"text": [
"<code>npm install</code>",
"<code>npx cdk bootstrap</code> (once per account and Region)",
"<code>export AWS_REGION=us-east-1</code> (see Supported Regions in the README)",
"<code>npx cdk deploy</code>"
]
},
"testing": {
"text": [
"See the GitHub repo for detailed testing instructions."
]
},
"cleanup": {
"text": [
"Abort any open multipart upload first, as described in the Cleanup section of the README.",
"<code>npx cdk destroy</code>",
"Then delete the two CDK helper log groups, as described in the README."
]
},
"authors": [
{
"name": "Nithin Chandran R",
"image": "https://github.com/NithinChandranR-AWS.png",
"bio": "Technical Account Manager at AWS",
"linkedin": "nithin-chandran-r"
}
]
}
Loading