
Your S3 Traffic Is Paying a Toll It Doesn't Owe: A Free Gateway Endpoint Cut NAT Data Processing by 93% in One Production VPC
A free S3 gateway endpoint cut NAT data processing by about 93% in one production VPC. Measure your own NAT cost, add the endpoint with Terraform, avoid the aws:SourceIp bucket policy trap, prove the saving, and take home a 10-point checklist.
The toll booth on the way to your own warehouse
Picture a small shop. The godown (warehouse) is right across the street. Every time a worker carries a box over, he walks through a toll booth and pays by the kilo.
Nobody built that booth for this trip. It was built for the highway. The road to the godown just happens to pass through it. Nobody looked, because the boxes always arrived.
That is close to what I found in a production VPC. The team had two VPCs. The older one already had S3 gateway endpoints, so "our S3 traffic stays inside AWS" was true there. The newer VPC, the one running the EKS workloads, had none. So every byte moving between pods and S3 went out through a NAT gateway and paid data processing on the way. One service alone was about a fifth of that NAT traffic, and nobody had measured the rest.
The result: one week after the change, NAT data processing in that VPC was down by about 93%. Nothing in the applications changed.
The fix was a resource that costs nothing. The real work was proving two things before touching production: that it was safe, and that it would actually save money. This article walks you through both, step by step.
What you will do
- Find out how much your NAT gateways are charging you, using numbers that match your bill.
- Build a small lab where S3 traffic from a private subnet pays NAT data processing.
- Add an S3 gateway endpoint with Terraform and watch the NAT bytes drop to almost zero.
- Break a bucket policy on purpose (the
aws:SourceIptrap), then fix it.
- Use the same checklist I used to roll this out to production.
- Clean everything up.
- Take home a 10-point checklist for your own accounts.
Lab repo (full Terraform + scripts): https://github.com/JoshiAbhishek866/nat-tax-lab . The article shows the important parts; the repo has every file so you can run it as-is.
Lab cost: about $0.06 per hour while it runs, plus about $0.14 of NAT data processing for the baseline test. Under $1 if you destroy it the same day. Prices in this article are for us-east-1. Check your Region's pricing page.
You need: a sandbox AWS account, Terraform 1.5 or newer, AWS CLI v2,
jq , and a Linux or WSL shell (the scripts use GNU date ).
The idea in plain words
Three pieces matter here.
NAT gateway = the toll booth. Instances in a private subnet have no public IP. To reach anything outside the VPC, including S3, they send traffic through a NAT gateway. AWS charges the NAT gateway by the hour and for every GB it processes, in both directions. In us-east-1 that is $0.045 per hour and $0.045 per GB.
Route table = the road map. Each subnet has a route table that says "for this destination, go this way". A private subnet usually has one big rule:
0.0.0.0/0 → NAT gateway . Everything that isn't local goes to the toll booth.S3 gateway endpoint = a free private lane, written into the map. When you create a gateway endpoint and attach it to a route table, AWS adds one extra route. Its destination is a prefix list, which is simply AWS's list of S3 IP ranges for that Region. Its target is the endpoint. Those S3 ranges are more specific than
0.0.0.0/0 , so the most specific route wins and S3 traffic takes the private lane. Gateway endpoints for S3 have no hourly charge and no data processing charge.Some quick maths to show why this matters:
Monthly S3 traffic through NAT | NAT data processing per month |
|---|---|
100 GB | ~$4.50 |
1 TB | ~$46 |
10 TB | ~$460 |
50 TB | ~$2,300 |
There is a second, quieter toll. If a private subnet in one Availability Zone routes to a NAT gateway in a different AZ, you also pay cross-AZ data transfer, $0.01 per GB in each direction. The gateway endpoint removes that hop for S3 traffic too.
One question came up early. Would an app using old path-style URLs like
https://s3.amazonaws.com/bucket/key use the endpoint? It does. Routing is decided by the destination IP and the prefix list. The SDK, the URL style and the app code don't matter, as long as the bucket is in the same Region as the VPC.
Part 1: Find your toll (in your real account, read-only)
Do this before you change anything. Everything in this part is read-only.
Run in: the AWS account that owns the VPC you want to check.
Set two variables first:
export AWS_REGION=us-east-1VPC_ID=vpc-xxxxxxxx # the VPC you suspectStep 1: Does the VPC already have an S3 gateway endpoint?
aws ec2 describe-vpc-endpoints \ --filters Name=vpc-id,Values=$VPC_ID Name=service-name,Values=com.amazonaws.$AWS_REGION.s3 \ --query 'VpcEndpoints[].{Id:VpcEndpointId,Type:VpcEndpointType,RouteTables:RouteTableIds}'An empty list
[] means no endpoint. Also check which route tables it is attached to. An endpoint that exists but isn't attached to the busy private route tables does nothing for them.This is exactly where my assumption broke. One VPC had endpoints, so it was easy to believe they all did. Check every VPC separately.
Step 2: Which route tables send traffic to a NAT gateway?
aws ec2 describe-route-tables \ --filters Name=vpc-id,Values=$VPC_ID \ --query 'RouteTables[?Routes[?NatGatewayId]].{RouteTable:RouteTableId,NAT:Routes[?NatGatewayId].NatGatewayId|[0],Subnets:Associations[].SubnetId}'Write these route table IDs down. They are the ones the endpoint must be attached to.
Step 3: Is any subnet crossing an AZ to reach its NAT?
# Where does each NAT gateway live?aws ec2 describe-nat-gateways --filter Name=vpc-id,Values=$VPC_ID \ --query 'NatGateways[].{NAT:NatGatewayId,Subnet:SubnetId}' --output table
# Which AZ is each subnet in?aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID \ --query 'Subnets[].{Subnet:SubnetId,AZ:AvailabilityZone,Name:Tags[?Key==`Name`].Value|[0]}' --output tableMatch each private subnet's AZ with the AZ of the NAT it routes to (from Step 2). In my case, two private subnets in different AZs shared one route table, and that route table pointed at a NAT gateway in only one of those AZs. About a third of the measured service's traffic ran in the other AZ, so it paid the cross-AZ hop on top of NAT processing.
Step 4: How many bytes does each NAT gateway process?
The NAT gateway publishes CloudWatch metrics. The two that match what you are billed for are:
-
BytesInFromSource: bytes coming from your VPC into the NAT (uploads, requests).
-
BytesInFromDestination: bytes coming back from the destination into the NAT (downloads, responses).
Add them up and you have the data the NAT processed. I wrapped this in a small script (it's in the lab repo):
#!/usr/bin/env bash# scripts/nat-bytes.sh <nat-gateway-id> <start-utc> <end-utc> [price-per-GB]set -euo pipefail
NAT_ID="$1"; START="$2"; END="$3"; PRICE="${4:-0.045}"REGION="${AWS_REGION:-us-east-1}"
WINDOW=$(( $(date -u -d "$END" +%s) - $(date -u -d "$START" +%s) ))# CloudWatch returns at most 1,440 datapoints per call. Pick a period that fits.if [ "$WINDOW" -le 86400 ]; then PERIOD=60elif [ "$WINDOW" -le 432000 ]; then PERIOD=300else PERIOD=3600fi
sum_metric() { aws cloudwatch get-metric-statistics --region "$REGION" \ --namespace AWS/NATGateway --metric-name "$1" \ --dimensions Name=NatGatewayId,Value="$NAT_ID" \ --start-time "$START" --end-time "$END" \ --period "$PERIOD" --statistics Sum \ --query 'sum(Datapoints[].Sum)' --output text}
FROM_SOURCE="$(sum_metric BytesInFromSource)"FROM_DEST="$(sum_metric BytesInFromDestination)"[ "$FROM_SOURCE" = "None" ] && FROM_SOURCE=0[ "$FROM_DEST" = "None" ] && FROM_DEST=0
awk -v s="$FROM_SOURCE" -v d="$FROM_DEST" -v p="$PRICE" 'BEGIN { gib = (s + d) / (1024 ^ 3) printf "Sent out by your VPC (BytesInFromSource): %10.2f GiB\n", s / (1024 ^ 3) printf "Came back from internet (BytesInFromDestination): %10.2f GiB\n", d / (1024 ^ 3) printf "Total processed by NAT: %10.2f GiB\n", gib printf "Data processing cost at $%s/GB: $%9.2f\n", p, gib * p}'Run it for the last 30 days, once per NAT gateway:
./scripts/nat-bytes.sh nat-xxxxxxxx "$(date -u -d '30 days ago' +%FT%TZ)" "$(date -u +%FT%TZ)"Step 5: Check your numbers against the bill
A number is only useful if you trust it. Before I showed anyone a saving, I checked that the CloudWatch counters matched what AWS actually billed.
Cost Explorer shows NAT data processing under the usage type
NatGateway-Bytes (other Regions add a prefix, like APS1-NatGateway-Bytes ):# Note: each Cost Explorer API call costs $0.01.aws ce get-cost-and-usage \ --time-period Start=2026-10-01,End=2026-11-01 \ --granularity MONTHLY \ --metrics UsageQuantity UnblendedCost \ --filter '{"Dimensions":{"Key":"SERVICE","Values":["EC2 - Other"]}}' \ --group-by Type=DIMENSION,Key=USAGE_TYPE \ --query 'ResultsByTime[0].Groups[?contains(Keys[0], `NatGateway-Bytes`)]'Now run
nat-bytes.sh for the same calendar month (UTC) on every NAT gateway in the account and add the totals. In my case, the CloudWatch sum and the Cost Explorer quantity were less than 0.01% apart. That small check gave me two things:- Proof that
BytesInFromSource + BytesInFromDestinationis the right formula.
- Proof that the "GB" on the bill behaves like GiB (1024³ bytes), so my maths used the right unit.
Now the savings maths rests on the same numbers the bill uses.
Step 6: How much of that is S3?
This is the hard part. Honestly, I couldn't measure it exactly. The VPC had no flow logs, and S3 request metrics were off on the buckets. So I estimated it for the biggest service: I took the pods' network counters and subtracted traffic to destinations inside the VPC (the cache cluster and the database). That left traffic that had to leave through the NAT. A sample of the service's input URLs showed they were S3 objects, and the buckets carrying almost all of the requests were in the same Region as the VPC.
If you need an exact split, turn on VPC Flow Logs for a short window and group by destination. In my case I didn't need perfect numbers. A gateway endpoint is free and serves the whole VPC, so the decision didn't depend on the per-service estimate being exact.
Part 2: Build the lab and pay the toll on purpose
Now let's see the toll with our own eyes, in a sandbox account.
Run in: your personal sandbox account. Never in a client or production account.
git clone https://github.com/JoshiAbhishek866/nat-tax-lab.gitcd nat-tax-labexport AWS_REGION=us-east-1terraform initterraform applyThis builds a VPC with one public subnet (NAT gateway) and one private subnet. In the private subnet there is a small
t4g.micro instance with no public IP and no SSH. We drive it with SSM Run Command. There is also an S3 bucket in the same Region.Here is the important part of the network. The private route table sends everything to the NAT:
resource "aws_route_table" "private" { vpc_id = aws_vpc.lab.id
route { cidr_block = "0.0.0.0/0" nat_gateway_id = aws_nat_gateway.lab.id }}Let's look at the road map before the change:
aws ec2 describe-route-tables \ --route-table-ids "$(terraform output -raw private_route_table_id)" \ --query 'RouteTables[0].Routes[].{Destination:DestinationCidrBlock||DestinationPrefixListId,Target:NatGatewayId||GatewayId}' \ --output tableYou should see two routes:
10.20.0.0/16 → local and 0.0.0.0/0 → nat-... . No private lane yet.Generate S3 traffic from the private subnet
The script below asks the instance (through SSM) to create a 1 GiB file, upload it to the bucket once, and download it twice. That is about 3 GiB through the NAT.
./scripts/generate-traffic.shThe core of what runs on the instance:
dd if=/dev/urandom of=lab-1g.bin bs=1M count=1024 status=noneaws s3 cp lab-1g.bin s3://$BUCKET/lab-1g.binfor i in 1 2; do aws s3 cp s3://$BUCKET/lab-1g.bin /tmp/dl.bindoneThe first run waits until the instance has registered with SSM, which can take a few minutes after
terraform apply . The script then prints a Start (UTC) and an End (UTC) time. Wait 3 to 5 minutes (NAT metrics arrive with a small delay), then measure that window:./scripts/nat-bytes.sh "$(terraform output -raw nat_gateway_id)" <start> <end>You should see about 1 GiB in
BytesInFromSource (the upload), about 2 GiB in BytesInFromDestination (the two downloads), and a total of roughly 3 GiB.It looks roughly like this (your numbers will differ a little because of TLS and protocol overhead):
Sent out by your VPC (BytesInFromSource): 1.0x GiBCame back from internet (BytesInFromDestination): 2.0x GiBTotal processed by NAT: 3.0x GiBData processing cost at $0.045/GB: $ 0.14That is the toll. About $0.14 in the lab. Now multiply by your production traffic.
Part 3: Add the free private lane
Here is the whole fix:
resource "aws_vpc_endpoint" "s3" { count = var.enable_s3_endpoint ? 1 : 0
vpc_id = aws_vpc.lab.id service_name = "com.amazonaws.${var.region}.s3" vpc_endpoint_type = "Gateway"
# Every private route table that sends 0.0.0.0/0 to a NAT gateway goes here. route_table_ids = [aws_route_table.private.id]}A few things to notice:
-
vpc_endpoint_type = "Gateway". S3 also has interface endpoints, which cost money per hour and per GB. For traffic from inside the VPC to same-Region S3, the gateway type is free and is what we want.
- No
policyblock means the default policy (full access). If you write a narrower endpoint policy later, remember buckets owned by other accounts that your apps read or write. They need to be allowed too, or those calls start failing.
-
route_table_idsis the part people forget. The endpoint only works for subnets whose route tables are listed here.
Apply it:
terraform apply -var enable_s3_endpoint=trueVerify the road map changed
Run the same route table command again:
aws ec2 describe-route-tables \ --route-table-ids "$(terraform output -raw private_route_table_id)" \ --query 'RouteTables[0].Routes[].{Destination:DestinationCidrBlock||DestinationPrefixListId,Target:NatGatewayId||GatewayId}' \ --output tableYou now have a third route:
pl-xxxxxxxx → vpce-xxxxxxxx . That pl- is the S3 prefix list. Look inside it:aws ec2 describe-prefix-lists \ --prefix-list-ids "$(terraform output -raw s3_prefix_list_id)" \ --query 'PrefixLists[0].Cidrs'These are S3's IP ranges for the Region. Each one is more specific than
0.0.0.0/0 , so S3 traffic now goes to the endpoint and everything else still goes to the NAT.Measure again
./scripts/generate-traffic.sh# wait 3 to 5 minutes./scripts/nat-bytes.sh "$(terraform output -raw nat_gateway_id)" <start> <end>Same 3 GiB of S3 work. The NAT total should now be close to zero. What is left is small background traffic like the SSM agent talking to its service.
Roughly:
Total processed by NAT: 0.0x GiBData processing cost at $0.045/GB: $ 0.00No app change. No restart. No new IAM permissions. The instance simply took a different road.
Part 4: The trap that can break production ( aws:SourceIp )
This is the one pre-check I would never skip.
Some bucket policies lock a bucket to "requests from our NAT gateway's public IP only". It looks like this:
{ "Effect": "Deny", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Condition": { "NotIpAddress": { "aws:SourceIp": ["203.0.113.10/32"] } }}It works for years. Then you add a gateway endpoint, and S3 traffic stops going through the NAT. AWS documents that the
aws:SourceIp key is not available when a request comes through a VPC endpoint. For a rule that says "deny unless the IP matches", a missing key counts as "doesn't match", so the deny applies to every request that now uses the endpoint. Your app gets 403 Forbidden.Let's break it on purpose:
terraform apply -var enable_s3_endpoint=true -var bucket_policy_mode=sourceip_only./scripts/generate-traffic.shThe upload still works (the lab policy only denies
GetObject ), but the download fails with a 403. In production, this would look like a sudden spike of access-denied errors right after a "harmless, free" network change.In the SSM output you will see an error like this:
fatal error: An error occurred (403) when calling the HeadObject operation: ForbiddenThe fix
Allow the request if it comes from the NAT IP or through your endpoint:
{ "Effect": "Deny", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Condition": { "NotIpAddress": { "aws:SourceIp": ["203.0.113.10/32"] }, "StringNotEquals": { "aws:SourceVpce": "vpce-xxxxxxxx" } }}Why this works: conditions inside one statement are joined with AND. The deny only applies when the request is not from the NAT IP and not through our endpoint. A request through the endpoint fails the second condition, so it isn't denied.
If you have several endpoints,
aws:SourceVpc (the VPC ID) is often simpler than listing each endpoint ID.terraform apply -var enable_s3_endpoint=true -var bucket_policy_mode=sourceip_or_vpce./scripts/generate-traffic.sh # downloads work againCheck your real buckets before rollout
Run in: each account that owns buckets your VPC talks to. Read-only.
for b in $(aws s3api list-buckets --query 'Buckets[].Name' --output text); do if aws s3api get-bucket-policy --bucket "$b" --query Policy --output text 2>/dev/null \ | grep -qi 'aws:SourceIp'; then echo "CHECK: $b has an aws:SourceIp condition" fidoneFor buckets in other accounts, ask the owners. IAM policies can use
aws:SourceIp too, so search those as well.Run this check before the change. Finding an
aws:SourceIp condition after rollout means finding it through failed requests.
Part 5: How I rolled it out in production
The lab is the easy part. In a shared production VPC, I followed this order.
1. Pre-checks, written into the ticket before any change.
- Bucket policies checked for
aws:SourceIpon the NAT public IPs.
- Endpoint policy: default full access, so cross-account buckets keep working.
- Route tables: the endpoint adds one prefix-list route per table. Check you are not near the route table entry limit.
- Region: the buckets carrying most of the traffic were in the same Region as the VPC. A gateway endpoint does nothing for a bucket in another Region; that traffic still goes through NAT.
- App impact: none expected. Nothing in the app referenced a NAT or an endpoint.
2. Terraform, not the console. The endpoint lives in the same Terraform code as the VPC, attached to every private route table that default-routes to a NAT:
resource "aws_vpc_endpoint" "s3" { vpc_id = var.vpc_id service_name = "com.amazonaws.${var.region}.s3" vpc_endpoint_type = "Gateway" route_table_ids = var.private_route_table_ids
tags = { Name = "${var.env}-s3-gateway" }}3. Non-production first. I applied it to dev, test and QA first and watched the NAT bytes metric. NAT traffic dropped and nothing broke.
4. Production in off-hours, with a narrow plan. I applied it in production in a low-traffic window, using a targeted plan so the change touched only the endpoint:
terraform plan -target=aws_vpc_endpoint.s3 -out=s3-endpoint.planterraform apply s3-endpoint.plan-target is a sharp tool. Use it to keep a change small, then run a normal full terraform plan afterwards to confirm the state is clean.5. Watch during and after.
- NAT gateway
BytesInFromSourceandBytesInFromDestinationin CloudWatch: they should drop within minutes.
- Your app's error rate and job failure metrics: they should stay flat.
- Any 403s in app logs: that is the
aws:SourceIptrap.
One thing to know: when the route changes, connections that were already open through the NAT at that moment may reset, because the traffic suddenly takes a different path. Most AWS SDKs retry, so apps usually don't notice. Keep an eye on error metrics for the first few minutes anyway.
Part 6: Prove the saving
A free change is easy to approve. A saving is only real when the bill shows it.
After a week, compare the same NAT gateways for 7 days before and 7 days after the change:
# 7 days before the change./scripts/nat-bytes.sh nat-xxxxxxxx <change-minus-7-days> <change-time># 7 days after the change./scripts/nat-bytes.sh nat-xxxxxxxx <change-time> <change-plus-7-days># times in UTC, for example 2026-01-08T00:00:00ZThen confirm in Cost Explorer: filter the usage type
NatGateway-Bytes , daily granularity, and look for the step down on the change date.My result after one week: NAT data processed in that VPC dropped by about 93%. I compared the 7 days before the change with the 7 days after, same VPC, same NAT gateways, no application change. How much you save depends on how much of your NAT traffic is S3. In this VPC it was most of it.
What this doesn't fix (and what I'd do differently)
- My per-service number was an estimate. No flow logs and no S3 request metrics meant I could only estimate the split. If I did it again, I would turn on flow logs for one day before the change to get a clean before-and-after by destination.
- Same Region only. Cross-Region S3 traffic still goes through the NAT.
- Only S3 (and DynamoDB, which has its own gateway endpoint). Other AWS APIs like STS or CloudWatch need interface endpoints, which have an hourly charge per AZ plus a per-GB charge. Do the maths before adding them. They only pay off when the traffic is big enough.
- Container image pulls get a bonus. Amazon ECR stores image layers in S3, so layer downloads from private subnets also take the free lane once the S3 gateway endpoint exists. The ECR API calls themselves still go through NAT unless you add interface endpoints.
Try it yourself
Everything in this article, ready to run:
git clone https://github.com/JoshiAbhishek866/nat-tax-lab.gitcd nat-tax-labterraform init && terraform applyThe README walks through the same steps as Parts 2 to 4. If something doesn't work for you, open an issue on the repo.
Clean up
terraform destroy -var enable_s3_endpoint=true -var bucket_policy_mode=sourceip_or_vpceThis deletes the NAT gateway, releases the Elastic IP, removes the instance and empties and deletes the bucket (
force_destroy = true , lab only). Check the VPC console afterwards to confirm no NAT gateway is left. That is the one resource that keeps charging by the hour.
Take it to your own organization: a 10-point NAT cost checklist
You can reuse this skeleton for any AWS account. It has no commands on purpose, because the commands are in Parts 1 to 6. Copy the list into a ticket and tick it off.
One honest note first. Your saving depends on how much of your NAT traffic is S3. In my VPC it was most of it. In yours it may be less, so measure before you promise a number.
Find
- List every VPC that has a NAT gateway, and check each one for an S3 gateway endpoint. One VPC having it tells you nothing about the others.
- Rank your NAT gateways by data processed over 30 days. Start with the biggest one.
- Match those numbers to your bill before you quote any saving. If CloudWatch and Cost Explorer disagree, find out why first.
- Look for the cross-AZ hop. A private subnet that sends traffic to a NAT gateway in another Availability Zone pays extra for it.
Check
- Search bucket policies and IAM policies for
aws:SourceIprules that depend on your NAT's public IP. Ask the owners of buckets in other accounts too.
- Confirm the buckets are in the same Region as the VPC. Cross-Region traffic still goes through the NAT.
- Decide what else needs an endpoint. DynamoDB has a free gateway endpoint too. Other AWS APIs need interface endpoints that cost money by the hour, so add them only when the traffic is big enough.
Change
- Put it in Terraform, non-production first, production in a quiet window. Keep the change small, and know your rollback before you start: removing the endpoint sends S3 traffic back through the NAT.
Keep
- Measure 7 days before and 7 days after, then write the percentage on the ticket.
- Make it the default. Add the S3 gateway endpoint to your VPC template so new VPCs get it on day one, and look at NAT bytes once a month so a surprise doesn't sit there for a year.
Closing thought
The toll booth was never the problem. The problem was that nobody had looked at which road the S3 traffic was taking. One
describe-vpc-endpoints call per VPC is enough to find out.Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article