Amazon S3 · 2026-11-12 · S3 advanced operations arc
S3 Advanced Operations for MCP Servers: Multipart Upload, Presigned URLs, Lifecycle Policies, and Batch Operations
MCP server tools that only know PutObject and GetObject will hit a wall fast: a 2 GB model weight upload times out, a presigned URL stops working in an hour because it was signed by a Lambda, objects accumulate in S3 Standard and costs grow unchecked, and bulk-processing 500,000 objects requires a custom distributed worker nobody wants to build. This guide synthesizes four advanced S3 patterns — multipart upload, presigned URLs, lifecycle policies, and Batch Operations — into a production playbook that eliminates those failure modes end-to-end.
TL;DR
- Multipart upload: files > 100 MB require the three-phase
CreateMultipartUpload→UploadPart× N →CompleteMultipartUploadprotocol. Minimum part size is 5 MB (except the last). Upload 4–8 parts concurrently for throughput. AlwaysAbortMultipartUploadon failure — incomplete parts bill for every stored byte. Add anAbortIncompleteMultipartUploadslifecycle rule as a safety net. Resume interrupted uploads by listing already-uploaded parts withListParts(UploadIdstays valid for 7 days). - Presigned URLs: maximum expiry for IAM user credentials is 7 days. For assumed-role credentials (Lambda, ECS, instance profile) the expiry is capped at the role session duration — typically 1 hour — regardless of your
expiresInvalue.ContentTypeis embedded in the signature for PUT URLs; a client that sends a differentContent-TypegetsSignatureDoesNotMatch. Never log presigned URLs; treat them as short-lived secrets. - Lifecycle policies:
PutBucketLifecycleConfigurationCommandreplaces the entire config — read first, then write back. Minimum billing duration before first transition: 30 days for Standard→IA, 90 days for Standard→Glacier IR or Glacier Flexible, 180 days for Deep Archive. Use Intelligent-Tiering for unpredictable access patterns; add anObjectSizeGreaterThan: 131072filter to avoid paying monitoring fees on small objects. - S3 Batch Operations: set
ConfirmationRequired: falseto auto-start. Supply theETagof your manifest CSV. The job role trust policy must namebatchoperations.s3.amazonaws.comas the principal — not just your calling IAM user. Lambda handlers must return{ resultCode: 'Succeeded' | 'TemporaryFailure' | 'PermanentFailure' }per task; a missing or invalid result marks the whole invocation failed.
Pattern 1: Multipart upload for large files
S3's single PutObject call handles files up to 5 GB in theory, but anything over ~100 MB benefits from multipart upload in practice. The three-phase protocol splits the file into independently uploadable parts, transmits them concurrently, and assembles them server-side. A failed part retries without restarting from zero, concurrent parts saturate available bandwidth, and you can report upload progress part-by-part to the calling agent.
The full protocol walkthrough is in the S3 multipart upload guide. The key operations:
// Phase 1 — get an UploadId (commit content type, storage class, encryption here)
const { UploadId } = await s3.send(
new CreateMultipartUploadCommand({ Bucket, Key, ContentType, ServerSideEncryption: 'aws:kms' })
);
// Phase 2 — upload each part, collect ETags (ContentLength required for stream body)
const { ETag } = await s3.send(
new UploadPartCommand({ Bucket, Key, UploadId, PartNumber, Body: stream, ContentLength })
);
// Phase 3 — assemble (sort parts by PartNumber before passing)
await s3.send(
new CompleteMultipartUploadCommand({
Bucket, Key, UploadId,
MultipartUpload: { Parts: parts.sort((a, b) => a.PartNumber - b.PartNumber) },
})
);
// Always abort on any failure — incomplete parts bill per stored byte
await s3.send(new AbortMultipartUploadCommand({ Bucket, Key, UploadId }));
Concurrency and the 5 MB floor
The minimum part size is 5 MB for every part except the last one. EntityTooSmall is the error when you violate this. For throughput, 4–8 concurrent uploads is the sweet spot: fewer and you underutilize bandwidth; more and you risk S3 SlowDown (HTTP 503) throttling and exhausting file descriptors. Use a semaphore — the p-queue package or a manual promise pool — to cap concurrency.
Presigned part URLs for browser-direct upload
When the client is a browser or external service, generate presigned URLs for each part. The client PUT-uploads each part directly to its URL, extracts the ETag from the response header, sends the ETags back to your server, and your server calls CompleteMultipartUpload. Your server never touches the binary payload — only metadata flows through it.
Browsers block access to ETag on cross-origin responses by default. Add ExposeHeaders: ['ETag'] to the S3 bucket CORS configuration or the client can't collect the ETags it needs to report back.
Abort, lifecycle rules, and resume
Incomplete multipart uploads — uploads that were started but never completed or aborted — accumulate storage charges silently. S3 bills per stored part even if the upload was never assembled. Two mitigations:
- Always call
AbortMultipartUploadCommandin yourcatchblock. No exceptions. - Add an
AbortIncompleteMultipartUploads: { DaysAfterInitiation: 7 }rule to your bucket lifecycle configuration as a safety net for crashes that skip the catch.
If your MCP server crashes mid-upload, persist the UploadId to your database and resume by calling ListPartsCommand. It returns the already-uploaded parts and their ETags. Skip those part numbers, upload the remaining ones, and complete. The UploadId remains valid for 7 days after the last activity — after that, ListParts returns NoSuchUpload and you must start over.
When to use the high-level Upload class
The @aws-sdk/lib-storage package ships a first-party Upload class that handles part splitting, concurrent uploads, retries, progress events, and abort on failure automatically. Use it for straightforward server-side uploads where you don't need fine-grained part control. Use the low-level API when you need presigned part URLs for browser-direct upload, pause/resume, or per-part progress reporting to callers.
Pattern 2: Presigned URLs — expiry traps and security rules
Presigned URLs are time-limited, cryptographically signed URLs that grant temporary access to a specific S3 object without exposing AWS credentials. MCP server tools use GET URLs to give calling agents temporary read access to private files, and PUT URLs so clients can upload directly to S3 without routing large binary payloads through your server.
See the S3 presigned URLs guide for complete code samples. The critical production details follow.
The credential-type expiry trap
The single most common production incident with presigned URLs: you generate a URL with expiresIn: 86400 (24 hours) in a Lambda function and it stops working after 1 hour. Here's why.
The maximum validity depends on the credential type used to sign the URL:
| Credential type | Max expiry | Notes |
|---|---|---|
| IAM user long-term key | 7 days (604800s) | Avoid in production — long-term credentials are a security risk |
| AssumeRole (Lambda, ECS, EC2 instance profile) | Role session duration | Default 1h; max 12h configured in role trust policy; URL dies when session expires |
| Federated identity / web identity | Session duration of assumed role | Same constraint as AssumeRole |
When Lambda signs a presigned URL, the URL is backed by a session token that expires independently of the expiresIn you specified. Even if you request a 24-hour URL, it becomes invalid when the Lambda's 1-hour session expires — which is whenever Lambda's underlying instance rotates credentials. To get longer-lived presigned URLs from Lambda, either: (a) create a dedicated IAM user with S3-only permissions and use a separate S3Client configured with those long-term credentials just for presigning, or (b) extend the role session duration in the IAM role trust policy up to the 12-hour maximum.
ContentType is embedded in the signature
When you generate a presigned PUT URL with a ContentType in the PutObjectCommand, that content type is embedded in the cryptographic signature. If the client sends a different Content-Type header, S3 returns SignatureDoesNotMatch immediately — no upload happens. Instruct clients to use exactly the content type your server specified. If you can't predict the content type at URL generation time, use createPresignedPost (from @aws-sdk/s3-presigned-post) instead, which supports richer condition expressions.
CORS for browser PUT uploads
Browser PUT uploads to presigned URLs trigger a CORS preflight. Without CORS, the preflight OPTIONS request fails and the upload never starts. Required configuration:
CORSRules: [{
AllowedOrigins: ['https://your-app.com'], // never '*' for PUT
AllowedMethods: ['GET', 'PUT', 'HEAD'],
AllowedHeaders: ['*'],
ExposeHeaders: ['ETag'], // required for multipart upload ETags
MaxAgeSeconds: 3600,
}]
Never set AllowedOrigins: ['*'] for PUT operations — it allows any website to upload to your bucket using a presigned URL you generated.
Post-upload validation
Presigned PUT URLs don't enforce file size or content type validation — the client can upload anything within the URL's validity window. Validate after upload with HeadObjectCommand: check ContentType and ContentLength, then delete the object if either fails expectations. For stricter server-side enforcement before any bytes are accepted, use createPresignedPost with a content-length-range condition.
Security checklist
- Keep PUT presigned URLs to 15 minutes or less. If the user misses the window, generate a new URL.
- Scope keys to the user or session:
uploads/{userId}/{uuid}/{filename}. - Use a dedicated
uploads-incomingbucket with aggressive lifecycle rules. After validation, move approved files to your serving bucket. - Never log presigned URLs — treat them as short-lived secrets that must be redacted from application logs.
- Require SSE-KMS on presigned PUT by including
ServerSideEncryption: 'aws:kms'in thePutObjectCommand. The client must send thex-amz-server-side-encryption: aws:kmsheader or S3 rejects withSignatureDoesNotMatch.
Pattern 3: Lifecycle policies — automated cost control
Without lifecycle policies, every object an MCP server ever writes sits in S3 Standard at full price indefinitely. Lifecycle policies automate three operations: transitioning objects to cheaper storage classes as they age, expiring objects permanently, and aborting incomplete multipart uploads.
Full guide with all code samples: S3 lifecycle policies guide.
The replace-not-append trap
PutBucketLifecycleConfigurationCommand replaces the entire lifecycle configuration, not appends to it. If you call it without reading first, you silently delete every existing rule. The correct pattern:
try {
const { Rules } = await s3.send(
new GetBucketLifecycleConfigurationCommand({ Bucket })
);
existingRules = Rules ?? [];
} catch (err: any) {
if (err.name !== 'NoSuchLifecycleConfiguration') throw err;
// no config yet — start fresh
}
await s3.send(
new PutBucketLifecycleConfigurationCommand({
Bucket,
LifecycleConfiguration: {
Rules: [...existingRules.filter(r => r.ID !== newRule.ID), newRule],
},
})
);
Storage class transition graph and minimum billing durations
Every storage class below Standard has a minimum billing duration. Transition an object too early, delete it before the minimum, and you still pay for the full minimum. Factor this into cost modeling for short-lived objects — a temporary processing artifact that you need for 10 days should stay in Standard, not transition to IA at day 7.
| Transition | Minimum days | Retrieval cost | When to use |
|---|---|---|---|
| Standard → Standard-IA | 30 days | Per-GB fee | Infrequently accessed objects retrieved in full |
| Standard → Glacier Instant Retrieval | 90 days | Per-GB fee, millisecond retrieval | Quarterly access pattern |
| Standard → Glacier Flexible | 90 days | Per-GB fee, 1–5 min retrieval | Archives not needed immediately |
| Standard → Deep Archive | 180 days | Per-GB fee, 12h retrieval | Compliance retention, rarely accessed |
Tag-based filtering for multi-tenant MCP tools
Prefix-based rules work for predictable key structures. For rules that cut across prefixes — by tenant, data classification, or retention class — use tag filters. Set the tag on upload with the Tagging parameter on PutObjectCommand (URL-encoded: retention=90days&classification=audit) and reference it in lifecycle rules with a Filter.Tag or Filter.And (prefix + tag combined). Lifecycle evaluation is an async background job that runs nightly — expect a 1–2 day delay, and never rely on lifecycle expiry for time-sensitive deletion.
Versioned bucket rules: cap version depth
Versioned buckets accumulate noncurrent object versions indefinitely without explicit lifecycle rules. Add both NoncurrentVersionTransitions (move old versions to cheaper classes) and NoncurrentVersionExpiration (expire old versions) to prevent unbounded growth. The NewerNoncurrentVersions: 3 option — added in 2022 — is the cleanest lever: it keeps the current version plus the 3 most recent noncurrent versions and expires everything older, without requiring you to pick a fixed day count. Add Expiration: { ExpiredObjectDeleteMarker: true } to the same rule to automatically clean up delete markers left behind after all versions expire.
Intelligent-Tiering for unpredictable access
For AI-generated content that might be accessed once or a hundred times, S3 Intelligent-Tiering automatically moves objects between Frequent Access, Infrequent Access, Archive Instant Access, and Deep Archive Access tiers based on observed access patterns — no predictions needed. The tradeoff: a per-object monitoring fee (applies to objects > 128 KB). Add an ObjectSizeGreaterThan: 131072 filter to your Intelligent-Tiering configuration to exclude small objects where the monitoring fee would exceed any savings.
Pattern 4: S3 Batch Operations for billion-object bulk processing
When an MCP server tool needs to process more than a few thousand S3 objects, a pagination loop with ListObjectsV2 + per-object worker threads can be built, but it takes days to build correctly with error handling, retries, partial failure reporting, and horizontal scaling. S3 Batch Operations is the managed alternative: supply a manifest of object keys, choose an operation, and S3 runs it at billions-of-objects scale — parallelizing across AWS infrastructure, writing per-object success/failure reports, and handling retries without you managing any workers.
Supported operations: S3PutObjectCopy (bulk copy, re-encrypt), S3InitiateRestoreObject (bulk Glacier restore), LambdaInvoke (custom processing), S3PutObjectTagging (bulk tagging), S3PutObjectAcl, and S3DeleteObjectTagging. Full guide with IAM policies: S3 Batch Operations guide.
Creating a job from a CSV manifest
The simplest manifest is a CSV you upload to S3 with one row per object: bucket,key (no header). Note that S3ControlClient and CreateJobCommand are from @aws-sdk/client-s3-control, not @aws-sdk/client-s3. The AccountId parameter is required and must be fetched from STS:
import { S3ControlClient, CreateJobCommand } from '@aws-sdk/client-s3-control';
import { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';
const { Account: accountId } = await new STSClient({}).send(new GetCallerIdentityCommand({}));
const { JobId } = await new S3ControlClient({ region }).send(
new CreateJobCommand({
AccountId: accountId!,
ConfirmationRequired: false, // auto-start; default is true (Suspended)
Priority: 10,
RoleArn: 'arn:aws:iam::123456789012:role/s3-batch-job-role',
Manifest: {
Spec: { Format: 'S3BatchOperations_CSV_20180820', Fields: ['Bucket', 'Key'] },
Location: {
ObjectArn: 'arn:aws:s3:::manifest-bucket/manifest.csv',
ETag: manifestETag, // required — prevents stale manifests
},
},
Operation: {
LambdaInvoke: {
FunctionArn: 'arn:aws:lambda:us-east-1:123456789012:function:process-s3-object',
InvocationSchemaVersion: '2.0',
},
},
Report: {
Bucket: 'arn:aws:s3:::report-bucket',
Prefix: 'batch-reports/',
Format: 'Report_CSV_20180820',
Enabled: true,
ReportScope: 'FailedTasksOnly',
},
ClientRequestToken: `batch-job-${Date.now()}`, // idempotency key
})
);
Always fetch the manifest's ETag via HeadObjectCommand immediately before creating the job. The ETag prevents the job from accidentally using a replaced manifest if someone uploads a new version between your upload and job creation.
Lambda handler contract
For LambdaInvoke operations, S3 Batch Operations calls your Lambda once per object. Your function receives an event with a tasks array (typically one task per invocation at schema version 2.0) and must return a specific shape or Batch Operations marks the entire invocation as failed:
export async function handler(event) {
const results = [];
for (const task of event.tasks) {
const bucket = task.s3BucketArn.split(':::')[1]; // extract bucket name from ARN
const key = task.s3Key;
try {
// ... your processing logic ...
results.push({ taskId: task.taskId, resultCode: 'Succeeded', resultString: `OK: ${key}` });
} catch (err) {
const isTransient = err.name === 'ThrottlingException' || err.name === 'ServiceUnavailable';
results.push({
taskId: task.taskId,
resultCode: isTransient ? 'TemporaryFailure' : 'PermanentFailure', // TemporaryFailure = retry
resultString: `Error: ${err.message}`,
});
}
}
return {
invocationSchemaVersion: event.invocationSchemaVersion,
treatMissingKeysAs: 'PermanentFailure',
invocationId: event.invocationId,
results,
};
}
TemporaryFailure tells Batch Operations to retry the object (up to the job's retry limit). PermanentFailure skips the object and writes it to the failure report. Use TemporaryFailure for transient errors (throttling, network timeouts) and PermanentFailure for unrecoverable errors (corrupt data, missing dependency, invalid key).
IAM role requirements
The batch job role needs three things that are commonly missed:
- Trust policy principal:
batchoperations.s3.amazonaws.commust be listed as a trusted service in the role trust policy. Many teams forget to add this and wonder whyAccessDeniedappears at job creation time. - Manifest read permission:
s3:GetObjecton the manifest bucket in addition to the source bucket. - Lambda invoke permission:
lambda:InvokeFunctionon the target function. The Lambda's resource-based policy must also allowbatchoperations.s3.amazonaws.comas a principal — without this, the invocations silently fail.
Job states and monitoring
Batch jobs flow through: New → Preparing (manifest scan) → Suspended (if ConfirmationRequired: true) → Active (processing) → Completing → Complete. Poll DescribeJobCommand every 10 seconds for small jobs. For long-running jobs (millions of objects), use EventBridge: S3 Batch Operations emits aws.s3 events on state transitions that you can route to Lambda or SQS without polling.
Using S3 Inventory as manifest source
For recurring batch jobs over an entire bucket, configure S3 Inventory to generate daily CSV reports of all objects. When creating a Batch job from an inventory report, use format S3InventoryReport_CSV_20161130 and point Manifest.Location to the manifest.json file that S3 Inventory generates — not the data CSV files themselves. The manifest.json acts as a pointer that lists all the data CSV files; Batch Operations reads it to find the actual object manifests.
Putting the patterns together
These four S3 patterns compose into a production-grade object storage layer for MCP server tools. A realistic workflow for an MCP server that handles large file uploads from agents:
- Agent calls an MCP tool that generates a presigned PUT URL (15-minute expiry, SSE-KMS, userId-scoped key). The signing credential must have a session duration long enough to cover the URL's intended lifetime — not Lambda's default 1-hour session.
- For files > 100 MB, the client initiates a multipart upload: the MCP server generates presigned part URLs, the client uploads parts directly with CORS (
ExposeHeaders: ['ETag']), and the MCP server completes the upload once it receives all ETags. - The bucket has lifecycle rules: 24-hour expiry for
tmp/, Standard→IA transition at 30 days + Glacier IR at 90 days foruploads/, and anAbortIncompleteMultipartUploadssafety net at 7 days. All rules are written via read-then-write to avoid clobbering existing rules. - When a bulk re-processing job is needed (re-encrypt with new KMS key, apply metadata tags at scale), an MCP tool creates an S3 Batch Operations job from an inventory manifest. The Lambda handler uses
TemporaryFailure/PermanentFailureresult codes correctly and returns the full response shape, and the job role trust policy listsbatchoperations.s3.amazonaws.com.
MCP server health monitoring matters here too: if any step in this pipeline produces an unexpected error (failed multipart uploads accumulating, Batch job stuck in Suspended, presigned URLs returning 403), you want to know immediately — not discover it when costs spike or a user reports broken uploads. MCP server uptime monitoring gives you the visibility to catch those failures before they compound.
Common error reference
| Error | Source | Fix |
|---|---|---|
EntityTooSmall | Multipart upload | Part < 5 MB (except last). Increase PART_SIZE constant. |
InvalidPart | Multipart upload | ETag mismatch in CompleteMultipartUpload. Pass ETags exactly as returned (quotes included). Sort by PartNumber. |
NoSuchUpload | Multipart upload | UploadId expired (7 days inactivity) or never created. Add lifecycle rule for auto-abort. |
TooManyParts | Multipart upload | More than 10,000 parts. Use Math.ceil(fileSize / 10000) as minimum part size. |
SignatureDoesNotMatch | Presigned URL | Client sent a header not in the signed request (Content-Type mismatch, extra headers). Match exactly. |
AccessDenied before expiry | Presigned URL | Role session expired before URL expiry. Reduce expiresIn or use longer-lived signing credentials. |
| CORS preflight fails | Presigned URL | Missing AllowedOrigins / AllowedMethods / AllowedHeaders. Add origin, PUT method, and Content-Type header. |
| Objects not expiring on schedule | Lifecycle | Lifecycle evaluation is async nightly. Expect 1–2 day delay. |
| Standard-IA transition rejected | Lifecycle | Object < 128 KB. Add ObjectSizeGreaterThan: 131072 filter. |
InvalidManifest | Batch Operations | ETag in job request doesn't match manifest object. Fetch ETag immediately before CreateJobCommand. |
Job stuck in Suspended | Batch Operations | ConfirmationRequired: true (the default). Set ConfirmationRequired: false. |
| Lambda tasks all fail | Batch Operations | Response missing required fields. Return exactly { invocationSchemaVersion, treatMissingKeysAs, invocationId, results: [{taskId, resultCode, resultString}] }. |
Related guides
- S3 multipart upload: three-phase API, concurrent parts, presigned part URLs, resume
- S3 presigned URLs: temporary GET/PUT access, credential-type expiry limits, security
- S3 lifecycle policies: storage class transitions, versioned bucket rules, Intelligent-Tiering
- S3 Batch Operations: CSV manifest, Lambda handler contract, IAM, job monitoring
- S3 for MCP servers: buckets, IAM, versioning, encryption overview
- MCP server uptime monitoring — detect failures before users do