AWS Builder Center
API Gateway to Amazon S3: Bulk Data Ingestion Patterns Using Pre-Signed URLs, CloudFront OAC, and ECS Fargate

API Gateway to Amazon S3: Bulk Data Ingestion Patterns Using Pre-Signed URLs, CloudFront OAC, and ECS Fargate

API Gateway and Lambda cap request payloads at 10 MB and 6 MB, which breaks integrations once partners start sending large files. This post explains a land-first pattern: write the raw file durably to Amazon S3, then process it event-driven with AWS Lambda. It compares four ingestion options (cross-account S3, pre-signed URLs, CloudFront with OAC and WAF, and ECS Fargate streaming) and covers their trade-offs, security controls, and when to use each.

Your API Hit a Payload Limit. Now What? Four Patterns for Receiving Large Files from a Third Party on AWS

TL;DR: If a partner sends you data as an HTTP POST to API Gateway or a Lambda Function URL, you'll hit a hard payload ceiling sooner or later (10 MB for API Gateway, 6 MB for synchronous Lambda invocations). The fix is nearly always the same: stop pushing the bytes through your compute layer and put them in Amazon S3 first. What changes from one pattern to the next is how the partner gets the bytes into S3. This post walks through four ways to do it, from "they're already on AWS" to "they can only send a plain HTTPS POST", with the tradeoffs of each.



The scenario

Picture a common integration. An external data provider (a device vendor, a SaaS platform, a research partner, a government agency) sends you data on a schedule or whenever an event happens. You're building the platform that receives that data, transforms it, and loads it into a data lake for analytics and an operational database for your application.
The first version is built the obvious way. You expose a REST endpoint, the provider POSTs JSON to it, API Gateway passes the request to a Lambda function, and the function transforms the data and writes it out:
Current state: the provider POSTs the file through API Gateway into a Lambda ETL function, which fails above the payload limit

This works well during the pilot, when each payload is a few hundred KB. Then real usage arrives:
  • More users or devices are onboarded, so each export covers more records.
  • The provider starts sending batches (a day's worth of readings, a full sync, a backfill) instead of single events.
  • Richer data shows up, such as high-frequency sensor samples, attachments, and images.
Payloads grow from KB to tens of MB, and the integration starts failing with  413 Request Entity Too Large . Nothing in your code has changed. The architecture has simply outgrown itself.

Why the API pattern breaks: the limitations

Raising a setting won't fix this. The limits come from how the services are designed, and most can't be increased.

1. Hard payload ceilings

Entry point
Max request payload
Adjustable?
Amazon API Gateway (REST and HTTP APIs)
10 MB
No
AWS Lambda synchronous invoke (incl. Function URLs, API Gateway proxy)
6 MB request / 6 MB response
No
AWS Lambda asynchronous invoke
1 MB
No
Application Load Balancer → Lambda target
1 MB
No
Pay attention to the lowest limit in the chain. API Gateway may accept 10 MB, but if it proxies to Lambda, the request still has to fit in Lambda's 6 MB invocation payload.

2. Encoding overhead shrinks the effective limit

Binary payloads such as zip, Parquet, and images are base64-encoded when they pass through API Gateway to Lambda, which adds about 33% to their size. A 6 MB limit really means roughly 4.5 MB of raw binary. JSON envelopes, escaping, and headers reduce it further.

3. Timeouts couple the provider to your processing

API Gateway integrations default to a ~29–30 second timeout. With a synchronous API, the provider's HTTP connection stays open while your ETL parses, transforms, and writes to two destinations. As files grow, processing takes longer, and you start hitting timeouts even below the size limit. The provider sees a  504  and has no idea whether the data was saved.

4. No durability between receipt and processing

In the API pattern, the request body exists only in the Lambda's memory. If the function crashes, times out, or the database is down, the data is gone. The only recovery is to ask the provider to resend, and that assumes they kept a copy and know which requests failed.

5. Retries are expensive and risky

When a large POST fails, the provider resends the whole payload, and that request may fail the same way. Without idempotency, a request that timed out but actually succeeded gets processed twice.

6. You pay compute for network time

A Lambda function receiving a body over a slow link is billed for every second it waits. You're paying for data in transit, not data processing.

7. Workarounds create new problems

The usual workarounds are to compress the payload (a temporary fix until it grows again), have the provider chunk it into many smaller requests (now you need reassembly, ordering, and partial-failure handling on both sides), or move to a bigger compute front end. None of them address the underlying issue.

The core idea: land first, process second

The underlying issue is that you're using a request/response API to move files. APIs are good for commands and small messages. Bulk data is better handled by an object store. So separate receiving the data from processing it:
  1. Land. Write the raw file durably to Amazon S3, which accepts up to 5 GB in a single PUT and 5 TB with multipart upload.
  1. Trigger. S3 emits an  ObjectCreated  event to Lambda, SQS, or EventBridge. The event carries a pointer to the object (bucket and key), not the file contents.
  1. Process. The consumer reads the object from S3 at its own pace, with its own retries and its own timeout of up to 15 minutes for Lambda, or longer if you hand off to Fargate, Glue, or Step Functions.
  1. Store. Write the results to the data lake and the database as before.
The land-first pattern: any ingress path writes to an S3 ingest bucket, an event triggers the ETL, and failures go to a DLQ that can be replayed from S3

This gives you a few things right away:
  • No payload ceiling. The event carries a pointer to the file, not the file itself.
  • Durability before processing. If the ETL, database, or anything downstream fails, the original file is still in S3, so you can replay it.
  • Almost no ETL rewrite. The only change is where the handler reads the data from ( s3.get_object  instead of  event["body"] ).
  • Event-driven. No polling, and processing starts within seconds of arrival.
  • Provider and processor are decoupled. The provider gets a success response as soon as the file is stored, and your ETL can be slow, retry, or be redeployed without affecting them.
  • Audit trail for free. Every file received is kept, versioned, and timestamped, which helps when someone asks "what did we receive on the 14th?"

Why four options?

The downstream half (event → ETL → destinations) is the same in every option. What differs is the ingress path, meaning how the provider's bytes get into your bucket. In practice, you rarely get to choose that alone. It depends on what the provider can and will do:
Question about your provider
Why it matters
Are they on AWS, and can they use IAM roles?
If so, the simplest path is to let them write directly to S3 with IAM.
Can they make two HTTP calls (get a URL, then upload)?
If so, you can keep your API as the control point and still bypass its size limit.
Can they only send one request to a fixed URL?
Many legacy systems, SaaS webhooks, and low-code tools can't handle a token or URL exchange.
Are they forced to use  POST , or are files larger than 5 GB?
S3 needs  PUT , so  POST  requires something that translates between them.
Do you need custom logic on the way in (auth, validation, virus scanning, renaming)?
Then you need compute in the path, ideally compute that streams.
The four options run from least to most infrastructure. Each one adds a component only when the provider's constraints require it:
  1. Option A: shared bucket. Nothing between the provider and S3 except IAM.
  1. Option B: pre-signed URL. A small API that hands out short-lived upload permissions.
  1. Option C: CloudFront + WAF → S3. A fixed public URL with edge security, and still no compute.
  1. Option D: CloudFront + WAF → ALB → Fargate → S3. A streaming ingest service for full flexibility.
Start at the top and only move down when the provider can't do what the option above needs.



Option A: Shared S3 bucket (cross-account write)

Best when: the provider is on AWS and can use the AWS SDK/CLI.
Option A: the provider's IAM role writes cross-account into the S3 ingest bucket, and an ObjectCreated event triggers the ETL Lambda

The provider's IAM role writes directly to your bucket. You grant access with a bucket policy scoped to a single prefix:
{
"Effect": "Allow",
"Principal": { "AWS": "arn:aws:iam::<PROVIDER_ACCOUNT_ID>:role/<ProviderUploadRole>" },
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::<ingest-bucket>/incoming/*"
}
Then add an S3 Event Notification on  s3:ObjectCreated:*  for the  incoming/  prefix that targets your ETL Lambda.
Setup
You
Provider
Create the ingest bucket and  incoming/  prefix
Create an IAM role with  s3:PutObject  on your bucket/prefix
Attach a cross-account bucket policy (PutObject on the prefix only)
Replace the HTTP POST with a single  PutObject  call
Configure the S3 event notification and update the Lambda to read from S3

Pros: fewest moving parts, no new infrastructure, standard IAM. Cons: the provider must be on AWS (or able to hold and rotate AWS credentials).
Tip: Set  BucketOwnerEnforced  object ownership so objects written by the other account are owned by your account. Otherwise you can run into ACL headaches.



Option B: Pre-signed URL (two-step upload)

Best when: the provider isn't on AWS but can make two HTTP calls. It's the smallest behavioural change from "POST to an API".
Option B: the provider gets a pre-signed URL from API Gateway and a Lambda function, then PUTs the file directly to S3

Your existing API stays the front door, but now it only handles a few KB of metadata. The large upload goes straight to S3.
import boto3, uuid

s3 = boto3.client("s3")

def handler(event, context):
key = f"incoming/{uuid.uuid4()}.json"
url = s3.generate_presigned_url(
"put_object",
Params={"Bucket": "<ingest-bucket>", "Key": key, "ContentType": "application/json"},
ExpiresIn=300, # 5 minutes
)
return {"statusCode": 200, "body": f'{{"uploadUrl": "{url}", "key": "{key}"}}'}
Security notes
  • The URL is locked to one key and expires quickly. Keep  ExpiresIn  short.
  • Pre-signed URLs are not single-use by default. Until it expires, a URL can be reused. If you need strict one-time semantics, generate a unique key per request and reject or ignore duplicates downstream, or enable S3 conditional writes ( If-None-Match: * ) so the same key can't be overwritten.
  • Keep your existing API authentication (API key, IAM, Cognito, Lambda authorizer) on step 1. The pre-signed URL itself needs no credentials.
Pros: works for non-AWS providers; keeps your API as the control point. Cons: two calls instead of one, and the provider has to handle URL expiry.



Option C: CloudFront + WAF + S3 (single static upload URL)

Best when: the provider can only do one plain HTTPS PUT with no AWS SDK, no token exchange, and no URL refresh logic.
Option C: the provider PUTs to CloudFront, WAF inspects the request, and OAC signs the write to a private S3 bucket in your chosen Region

How it works:
  1. CloudFront terminates TLS at the nearest edge. A dedicated cache behavior on  uploads/*  allows  PUT , disables caching, and forwards the body. The default behavior is  GET / HEAD  only, so a stray path can't write.
  1. AWS WAF (CLOUDFRONT scope) evaluates rules in order, with a default action of Block:
  • Size cap on the  Content-Length  header (WAF only inspects the first part of the body, so check the header)
  • Rate limit per IP (e.g. 1,000 requests per 5 minutes)
  • Allow only if the path is  /uploads/*  and (source IP is in the allowlist or the shared-secret header matches). You can require both.
  1. Origin Access Control signs the origin request with SigV4. The provider never sees AWS credentials.
  1. The S3 bucket policy allows  s3:PutObject  only from  cloudfront.amazonaws.com  with  AWS:SourceArn  equal to this distribution, and only on  uploads/* :
{
"Effect": "Allow",
"Principal": { "Service": "cloudfront.amazonaws.com" },
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::<ingest-bucket>/uploads/*",
"Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::<ACCOUNT_ID>:distribution/<DIST_ID>" } }
}
Path scoping is enforced in three places (the CloudFront behavior, the WAF rule, and the bucket policy), so an attacker would have to get past all three to write anywhere else.
Data residency: CloudFront and WAF are global (managed from us-east-1), but the bucket, and therefore the data at rest, lives in whichever Region you choose.
Pros: no compute in the hot path; one static URL for the provider; abuse is stopped at the edge before it reaches S3. Cons:  PUT  only (OAC writes map onto S3  PutObject  semantics); single-PUT limit of 5 GB; CloudFront's origin response timeout (30 seconds by default) can affect slow uploads of large files.



Option D: CloudFront + WAF + ALB + Fargate (streaming ingest service)

Best when: the provider must use  POST  (or  PATCH ) because their framework forces it, or files are very large, or you want custom logic (validation, key naming, auth) on the ingest path.
Option D: CloudFront and WAF forward to an ALB and ECS Fargate in a VPC, which streams a multipart upload to S3 through a gateway endpoint

A small container sits behind the ALB, re-validates the shared secret, sanitises the object key, and streams the request body into S3 using multipart upload. Memory stays flat no matter how big the file is:
@app.route("/uploads/<path:key>", methods=["POST", "PUT", "PATCH"])
def upload(key):
if request.headers.get("x-upload-secret") != SECRET:
abort(403)
key = f"uploads/{sanitize(key)}"
mpu = s3.create_multipart_upload(Bucket=BUCKET, Key=key)
parts, n = [], 1
try:
while chunk := request.stream.read(PART_SIZE): # 8 MiB
r = s3.upload_part(Bucket=BUCKET, Key=key, UploadId=mpu["UploadId"],
PartNumber=n, Body=chunk)
parts.append({"ETag": r["ETag"], "PartNumber": n}); n += 1
s3.complete_multipart_upload(Bucket=BUCKET, Key=key, UploadId=mpu["UploadId"],
MultipartUpload={"Parts": parts})
except Exception:
s3.abort_multipart_upload(Bucket=BUCKET, Key=key, UploadId=mpu["UploadId"])
raise
return {"key": key}, 201
(The snippet is simplified. Real code should handle a final part under 5 MiB, check that the key is valid, and return structured errors.)
Hardening checklist
  • Fargate tasks in private subnets with no public IP; S3 reached through a VPC gateway endpoint (no NAT).
  • The task role gets only  s3:PutObject ,  s3:AbortMultipartUpload , and  s3:ListMultipartUploadParts  on  uploads/* .
  • Lock the ALB so it only accepts traffic from CloudFront: use the CloudFront managed prefix list in the ALB security group, plus a secret custom origin header checked by an ALB listener rule. Better still, use CloudFront VPC origins so the ALB can be fully internal.
  • Set the ALB idle timeout and CloudFront  OriginReadTimeout  to fit your largest expected upload.
  • Add a bucket lifecycle rule to abort incomplete multipart uploads after 7 days as a safety net.
Pros: any HTTP write method; size limited only by S3 (5 TB); full control over validation and auth. Cons: you now run a service (VPC, ECS, ALB, container image). It has the most moving parts and the highest baseline cost.



Choosing between them


A. Shared bucket
B. Pre-signed URL
C. CloudFront → S3
D. CloudFront → Fargate → S3
Provider needs AWS creds/SDK
Yes
Step 1 auth only
No
No
Calls per upload
1
2
1
1
HTTP methods
S3 API
PUT
PUT
POST / PUT / PATCH
Max file size
5 GB (PUT) / 5 TB (multipart)
5 GB per URL
5 GB
5 TB
Compute in upload path
None
Small Lambda (URL only)
None
Fargate service
Operational overhead
Lowest
Low
Low–Medium
Highest
Edge protection (WAF)
—
Optional on API
Yes
Yes
A simple way to decide:
  1. Is the provider on AWS? Use Option A.
  1. Can they make two HTTP calls? Use Option B.
  1. Can they only do a single PUT to a fixed URL? Use Option C.
  1. Do they need POST, files over 5 GB, or custom ingest logic? Use Option D.

Error handling (same for all four)

Because the file is in S3 before any processing starts, recovery is simple:
Failure
What happens
Recovery
Upload fails or drops midway
S3 never exposes partial objects
Provider retries
Pre-signed URL expired (B)
S3 returns 403
Request a new URL and retry
Blocked by WAF (C/D)
403 at the edge, nothing reaches S3
Fix the IP or secret, or adjust the rule
ETL Lambda fails
Lambda async invoke retries up to 2 times
Failed events go to an on-failure destination / DLQ; replay from S3
Downstream DB is down
Same as above
Reprocess from the DLQ once the DB recovers
Corrupt or invalid file
Handler validates and logs the error
File stays in S3 for inspection; raise a CloudWatch alarm
Production tip: For higher throughput or finer control over retries, route S3 events to SQS (or EventBridge) and have Lambda consume from the queue. You get batching, visibility timeouts, a redrive policy, and a clear backlog metric.

Baseline bucket hardening (all options)

  • S3 Block Public Access: all four settings on
  • A bucket policy that denies non-TLS requests ( aws:SecureTransport = false )
  • Default encryption (SSE-S3 or SSE-KMS), versioning, and  BucketOwnerEnforced 
  • Lifecycle rules: abort incomplete multipart uploads; expire noncurrent versions
  •  DeletionPolicy: Retain  on the bucket in your IaC
  • Optional: GuardDuty Malware Protection for S3 to scan files from third parties

Where this approach fits best

The land-first approach works best when the data being sent behaves more like a file than a message. Typical cases:
  • Partner and B2B data feeds. A third party pushes periodic exports, such as daily transactions, inventory snapshots, claims, or reports, and you don't control their stack.
  • Device and wearable data sync. IoT gateways, medical devices, fitness trackers, or vehicles upload batches of buffered readings when they reconnect. Payload sizes vary widely and spike after an outage.
  • Research and clinical data collection. Universities, hospitals, or study partners submit datasets that need to be kept exactly as received (for audit, reproducibility, or compliance) before anything is transformed.
  • Media and document intake. Images, scans, PDFs, audio, or video submitted by users or partners.
  • Backfills and bulk migrations. One-off or occasional large transfers that would overwhelm an API built for small, steady traffic.
  • Data that must stay in a particular country. You can keep data at rest in a chosen Region (e.g. Singapore) while still offering a global, low-latency upload endpoint (Options C and D).
Signs you need it: payloads above roughly 5 MB, or growing; unpredictable bursts; a need to replay or audit raw input; a slow or failure-prone downstream system; or a provider who can't easily retry.

When not to use it

  • Small, real-time messages that need an answer immediately. For payloads of a few KB where the caller needs a result in the response (e.g. "validate this order"), a normal API Gateway + Lambda API is still the right choice.
  • High-frequency streams. Thousands of small events per second fit Amazon Kinesis Data Streams / Amazon Data Firehose or Amazon MSK better than one file per event.
  • Providers that already use file-transfer protocols. If the partner sends files over SFTP/FTPS/AS2, AWS Transfer Family gives you a managed endpoint that also writes to S3, and the downstream is the same.
  • SaaS sources with built-in connectors. Amazon AppFlow can pull from many SaaS applications on a schedule, so you don't need to build an ingest endpoint at all.

Wrapping up

Payload limits on API Gateway and Lambda aren't a bug to work around. They're a sign that large files shouldn't go through synchronous compute. Treat S3 as the front door, make processing event-driven, and pick the ingress path that matches what your provider can actually do. In every case your ETL logic barely changes, and you get durability, replay, and much more payload headroom.


Have you solved large-payload ingestion differently? Share your approach in the comments.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article