Private subnets, NAT gateway and VPC endpoints

App servers belong in private subnets with no public IP, but they still have to download updates and call outside APIs. An AWS NAT gateway gives them a way out without letting anyone in. It’s also one of the lines that most often surprises people on an AWS bill, so this lesson covers the cheaper option as well, VPC endpoints.

You’ll test from CloudShell running inside your private subnet, first with no internet and then with internet through the NAT gateway. The NAT gateway runs for under an hour and gets deleted at the end.

TimeYou needBy the end you can
60 minutes (NAT gateway running for under an hour)saat-vpc from Lesson 8 and C:\aws-lab\saat-vpc.json, plus your laptop signed in with aws login --profile saat-admin. It costs about USD 0.10 if you finish and clean up within an hour.Give private subnets outbound internet through a NAT gateway, keep the database subnets fully private, add an S3 gateway endpoint that costs nothing, and clean up the NAT resources without leaving charges behind.

What it is, in one line

An AWS NAT gateway lets servers in private subnets open connections to the internet, while nothing on the internet can open a connection to them.

In Simple Words

The building’s outgoing post office

In an office building, the staff on the upper floors don’t have their own street door. To send a letter they leave it at reception, which posts it with the building’s address on it, and when the reply arrives reception knows whose letter it was and takes it upstairs. People outside can send letters to the building, but reception won’t carry them up unless someone inside started the conversation, and that reception desk is the NAT gateway. For letters to one very busy neighbour (S3), the building puts in a private corridor with no stamps and no queue at reception, and that corridor is a gateway endpoint.

Engineer's View

How NAT and endpoints work

A public NAT gateway lives in a public subnet and has an Elastic IP address, and the private subnets route 0.0.0.0/0 to it. It swaps the source address of outgoing packets for its Elastic IP and keeps track of connections, so the only traffic coming back in is replies.

It scales on its own and is highly available within its zone, which is why production designs run one NAT gateway per zone (or use the newer regional NAT gateway mode).

Each NAT gateway is charged per hour, per GB of data it processes, and for its public IPv4 address. In Mumbai that comes to roughly USD 0.05 to 0.06 an hour plus a similar amount per GB, but check the Amazon VPC pricing page for current figures. It’s the per-GB part that catches people out.

Gateway endpoints (S3 and DynamoDB only) add a route to a prefix list (pl-...) in whichever route tables you pick. Traffic to S3 then goes directly to S3 instead of through the NAT, and gateway endpoints cost nothing. Interface endpoints (AWS PrivateLink) put a network interface into your subnets for services like SSM, KMS or STS. Those are charged per hour per zone and per GB, though the per-GB rate is lower than NAT.

The database subnets get a route table of their own with no internet route, because databases accept connections from app servers and never need to reach out.

How it works, step by step

Here’s how traffic flows once the lab is done.

1Split the route tables

The private subnets keep saat-rt-private, and the database subnets move to a new saat-rt-db that has only the local route, before any internet route exists.

AWS NAT gateway: how a private server reaches the internet

2Place the NAT gateway in a public subnet

It needs its own path to the internet gateway, so it has to sit in saat-public-a and not in the private subnet it serves.

3Point the private route table at it

0.0.0.0/0 → NAT gateway in saat-rt-private, while the local route carries on handling traffic inside the VPC.

4Add the S3 shortcut

Put an S3 gateway endpoint on both private route tables, so big S3 transfers never go near the NAT gateway.

This is how the three options compare.

AWS NAT gateway compared with gateway and interface VPC endpoints

As a rule of thumb, S3 and DynamoDB always get a gateway endpoint, and heavy traffic to a single AWS service gets an interface endpoint. The NAT gateway takes care of whatever’s left, and you keep an eye on its data processed metric.

✅ Checkpoint: You can say where a NAT gateway has to live and what it charges for, and why S3 traffic should go through a gateway endpoint.

Hands-on lab: an AWS NAT gateway tested from CloudShell

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

Start the usual way and load the network IDs:

cd C:\aws-lab
aws login --profile saat-admin
$env:AWS_PROFILE = 'saat-admin'
$v = Get-Content C:\aws-lab\saat-vpc.json | ConvertFrom-Json

1Give the database subnets their own route table

Paste this whole block:

$rtDb = aws ec2 create-route-table --vpc-id $v.VpcId --tag-specifications 'ResourceType=route-table,Tags=[{Key=Name,Value=saat-rt-db},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=09}]' --query RouteTable.RouteTableId --output text
foreach ($s in $v.DbA, $v.DbB) {
  $assoc = aws ec2 describe-route-tables --filters "Name=association.subnet-id,Values=$s" --query "RouteTables[0].Associations[?SubnetId=='$s'].RouteTableAssociationId" --output text
  aws ec2 replace-route-table-association --association-id $assoc --route-table-id $rtDb | Out-Null
}
$v | Add-Member -NotePropertyName RtDb -NotePropertyValue $rtDb -Force
$v | ConvertTo-Json | Set-Content C:\aws-lab\saat-vpc.json
$rtDb

You should see something like this:

rtb-0c9d8e7f6a5b4c3d2

2Create a security group for CloudShell

Run this. The group has no inbound rules and allows all outbound traffic:

$sgCs = aws ec2 create-security-group --group-name saat-cloudshell-sg --description "CloudShell VPC environment" --vpc-id $v.VpcId --tag-specifications 'ResourceType=security-group,Tags=[{Key=Name,Value=saat-cloudshell-sg},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=09}]' --query GroupId --output text
$v | Add-Member -NotePropertyName CloudShellSg -NotePropertyValue $sgCs -Force
$v | ConvertTo-Json | Set-Content C:\aws-lab\saat-vpc.json

3Open CloudShell inside the private subnet

In the console (Mumbai), open CloudShell, choose the + menu and then Create VPC environment. Call it saat-private, and pick saat-vpc, subnet saat-private-a and security group saat-cloudshell-sg.

A VPC environment doesn’t keep a home folder, so whatever you create in it disappears when you close it.

Type this at the CloudShell prompt:

curl -m 5 https://checkip.amazonaws.com

You’ll get an error something like this:

curl: (28) Connection timed out after 5001 milliseconds

That’s what should happen, because the private subnet has no route out yet.

4Create the NAT gateway (the clock starts now)

Back in PowerShell, paste this whole block. The wait line takes between one and three minutes:

$eip = aws ec2 allocate-address --domain vpc --tag-specifications 'ResourceType=elastic-ip,Tags=[{Key=Name,Value=saat-nat-eip},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=09}]' --query AllocationId --output text
$nat = aws ec2 create-nat-gateway --subnet-id $v.PublicA --allocation-id $eip --tag-specifications 'ResourceType=natgateway,Tags=[{Key=Name,Value=saat-nat-a},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=09}]' --query NatGateway.NatGatewayId --output text
aws ec2 wait nat-gateway-available --nat-gateway-ids $nat
aws ec2 create-route --route-table-id $v.RtPrivate --destination-cidr-block 0.0.0.0/0 --nat-gateway-id $nat
aws ec2 describe-addresses --allocation-ids $eip --query 'Addresses[0].PublicIp' --output text

You should see something like this:

{
    "Return": true
}
13.204.88.142

5Test again from CloudShell

In the CloudShell VPC environment, run:

curl -m 5 https://checkip.amazonaws.com
aws sts get-caller-identity --query Arn --output text

You should see something like this:

13.204.88.142
arn:aws:iam::123456789012:user/yourname.admin

The address the internet sees is the NAT gateway’s Elastic IP and nothing from inside your VPC. The CLI works now as well, since it can reach the STS endpoint.

AWS NAT gateway lab: CloudShell in a private subnet before and after NAT
CloudShell in the private subnet, before and after the NAT gateway. It’ll look something like this.

6Add the S3 gateway endpoint (no charge, keep it)

Paste this whole block in PowerShell:

$vpce = aws ec2 create-vpc-endpoint --vpc-id $v.VpcId --vpc-endpoint-type Gateway --service-name com.amazonaws.ap-south-1.s3 --route-table-ids $v.RtPrivate $rtDb --tag-specifications 'ResourceType=vpc-endpoint,Tags=[{Key=Name,Value=saat-s3-endpoint},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=09}]' --query VpcEndpoint.VpcEndpointId --output text
aws ec2 describe-route-tables --route-table-ids $rtDb --query "RouteTables[].Routes[].[DestinationPrefixListId,GatewayId]" --output text

You should see something like this:

None    local
pl-78a54011     vpce-0f9e8d7c6b5a43210

The pl- route sends S3 traffic from both private route tables directly to S3.

7Clean up the NAT gateway

You’ll do this through the Break It lab below, which shows what happens when cleanup is done in the wrong order and then finishes it properly. Close the CloudShell VPC environment now (Actions, then Delete).

✅ Checkpoint: CloudShell in the private subnet timed out before the NAT and showed the Elastic IP afterwards, saat-rt-db has no internet route, and the S3 endpoint shows up as a pl- route.

Break It, Then Fix It

People in a hurry delete NAT gateways every day and forget these two leftovers. This break lab doubles as your cleanup.

1Break it: delete only the NAT gateway

Run this:

aws ec2 delete-nat-gateway --nat-gateway-id $nat
aws ec2 wait nat-gateway-deleted --nat-gateway-ids $nat
aws ec2 describe-route-tables --route-table-ids $v.RtPrivate --query "RouteTables[].Routes[?DestinationCidrBlock=='0.0.0.0/0'].[NatGatewayId,State]" --output text
aws ec2 describe-addresses --filters Name=tag:lesson,Values=09 --query "Addresses[].[PublicIp,AssociationId]" --output text

You should see something like this:

nat-0a1b2c3d4e5f60718   blackhole
13.204.88.142   None
AWS NAT gateway break lab: blackhole route and a leftover Elastic IP
What’s left after deleting only the NAT gateway, and the fix. It’ll look something like this.

That leaves you with two problems. The route now points at nothing (blackhole), so private servers fail with timeouts that look like “the internet is down”, and the Elastic IP isn’t attached to anything any more but still costs money every hour.

2Fix it: remove the route and release the address

Run this:

aws ec2 delete-route --route-table-id $v.RtPrivate --destination-cidr-block 0.0.0.0/0
aws ec2 release-address --allocation-id $eip
.\Find-LabResources.ps1 | Where-Object Resource -match 'elastic-ip|natgateway'

The last command should print nothing. The full finder will still show the things you’re keeping on purpose, saat-rt-db, saat-cloudshell-sg and the S3 endpoint, none of which cost anything.

✅ Checkpoint: There’s no 0.0.0.0/0 route left in saat-rt-private, no Elastic IP is left over, and the NAT gateway is gone.

This happened at work

The NAT bill that beat the servers

A fintech company ran nightly jobs in private subnets that read customer statements from S3, processed them and wrote the results back. All of it went through one NAT gateway, because “that’s how private subnets reach the internet”.

Those jobs moved about 30 TB a month to and from S3, and at Mumbai’s per-GB NAT processing charge that worked out to well over USD 1,500 a month, more than all the EC2 instances doing the actual work. For three months nobody noticed, since the bill line only said “NatGateway-Bytes”.

Fixing it took ten minutes: an S3 gateway endpoint on the private route tables. The next day the NAT charge fell by more than 90%, without any code change. These days the team adds S3 and DynamoDB gateway endpoints to every new VPC by default and keeps a CloudWatch alarm on the NAT gateway’s BytesOutToDestination metric.

Common mistakes and troubleshooting

MistakeWhat happensWhat to do
NAT gateway placed in a private subnetIt has no way out, so everything times outAlways put it in a public subnet
S3 traffic through NATLarge per-GB chargesAdd an S3 gateway endpoint (no charge)
One NAT gateway for all zones in productionIf a zone fails, every private subnet loses the internetOne per zone, or the regional NAT mode
Deleting the NAT but not the routeA blackhole route and confusing timeoutsDelete the 0.0.0.0/0 route too
Forgetting the Elastic IPHourly charge for an unused addressRelease it and run Find-LabResources.ps1
Giving database subnets internet accessA bigger attack surface for no good reasonA separate route table with only the local route

Interview questions

Click a question to open it. Each one is worded the way an interviewer might ask it, and underneath you’ll find why they ask it and one way you could answer in your own words.

Fresher level

1. Can you explain in simple words what a NAT gateway does for servers in a private subnet?

Why they ask this: They’re checking you understand what NAT is for, since it’s the reason private servers can still get their updates.

How you might answer: A NAT gateway lets servers in private subnets open connections out to the internet, for things like updates and external APIs, but it blocks any connection that starts from the internet, so the servers stay private.

2. You created a NAT gateway, but private servers still can’t reach the internet. Where should the NAT gateway have been placed?

Why they ask this: They want to see you avoid a very common beginner mistake, because NAT in the wrong subnet breaks outbound access completely.

How you might answer: It has to sit in a public subnet, one whose route table goes to an internet gateway, and the private subnets then route 0.0.0.0/0 to the NAT gateway. Put it in a private subnet and its own traffic has nowhere to go.

3. Your private servers read a lot from S3. Is there a cheaper way than sending that traffic through the NAT gateway?

Why they ask this: They want to know you’re aware of the cheap alternative, because lots of teams pay NAT charges they don’t need to.

How you might answer: Yes, I’d add a gateway endpoint for S3. It’s a route-table entry that sends S3 traffic directly to the service inside AWS, skipping the NAT gateway and the internet gateway. It works for S3 and DynamoDB and costs nothing.

2–5 years experience

4. Your app runs in three Availability Zones. How would you make outbound internet access survive a zone failure?

Why they ask this: They’re looking for production design thinking, because a single NAT gateway is a hidden single point of failure.

How you might answer: I’d put a NAT gateway in each zone’s public subnet and give every zone its own private route table pointing at its own NAT, so a zone failure only hits that zone. The other option is the regional NAT gateway mode, which spans zones.

5. Finance asks why the NAT gateway charges jumped this month. How would you find the cause?

Why they ask this: They want methodical cost troubleshooting, and they want to hear how you’d fix the problem as well as find it.

How you might answer: I’d start with the NAT gateway’s CloudWatch byte metrics to see when it jumped, then use VPC Flow Logs to find which instances and destinations send the most data. Quite often it turns out to be S3 or another AWS service, which I’d fix with gateway or interface endpoints, and now and then it’s a download loop nobody expected.

6. What’s the difference between a gateway endpoint and an interface endpoint, and when would you pick each?

Why they ask this: They’re checking you know both endpoint types and what they cost, because picking the right one saves money and also solves access from on-premises.

How you might answer: A gateway endpoint is a route, only for S3 and DynamoDB, and it costs nothing. An interface endpoint is a network interface with a private IP in my subnets, and it covers most of the other services. Interface endpoints are charged per hour and per GB, but they also work from on-premises over VPN.

Senior level

7. The security team says private subnets must have no internet access at all. How do servers still get patches and use AWS services?

Why they ask this: They want to see you can design a fully private environment, which is common in banks and other strict industries.

How you might answer: I’d add interface endpoints for SSM, SSM messages, EC2 messages, CloudWatch Logs, KMS, STS and ECR, along with a gateway endpoint for S3, and point the patch baselines at repositories reachable through S3 or an internal mirror. For the handful of approved outside sites, traffic goes through a proxy or Network Firewall that filters it.

8. Say an auditor asks what your private servers talk to on the internet. How would you control that and prove it?

Why they ask this: They want to see egress control and auditing skills, because senior engineers have to answer these questions with logs rather than guesses.

How you might answer: I’d send outbound traffic through AWS Network Firewall or a proxy with domain allow-lists, log all of it and alert on any new destination. VPC Flow Logs and Route 53 Resolver DNS query logging would then show exactly who talked to what.

Quick quiz

Q1. In which kind of subnet must a NAT gateway be created?

  1. Private
  2. Public
  3. Database
  4. Any subnet
Show answer

B: the NAT gateway needs a route to the internet gateway, and only public subnets have one.

Q2. Which services can use a gateway endpoint?

  1. All AWS services
  2. S3 and DynamoDB
  3. EC2 and RDS
  4. Only STS
Show answer

B: gateway endpoints only exist for S3 and DynamoDB.

Q3. After deleting a NAT gateway, the route shows “blackhole”. What does that mean?

  1. The route works but slowly
  2. The route points at something that no longer exists
  3. The route is encrypted
  4. AWS deleted the route table
Show answer

B: a blackhole route drops traffic because its target has gone, so delete or replace it.

Q4. What keeps charging after a NAT gateway is deleted, if you forget it?

  1. The route table
  2. The Elastic IP address
  3. The subnet
  4. The VPC
Show answer

B: an Elastic IP that isn’t attached still has an hourly charge until you release it.

Q5. Why do database subnets get their own route table without 0.0.0.0/0?

  1. To make them faster
  2. They don’t need outbound internet, so removing it shrinks the attack surface
  3. AWS requires it
  4. To save IP addresses
Show answer

B: databases receive connections and have no need to reach the internet.

Quick recap

  • A NAT gateway sits in a public subnet with an Elastic IP and gives private subnets outbound-only internet.
  • It’s charged per hour and per GB processed, so keep an eye on it.
  • Send S3 and DynamoDB traffic through gateway endpoints, which cost nothing.
  • Database subnets now use saat-rt-db with no internet route.
  • Clean up in this order: the NAT gateway, then the 0.0.0.0/0 route, then release the Elastic IP.

Next lesson

Lesson 10: Security groups and network ACLs → Next you’ll control which traffic may reach each server, and see why “it works from my laptop” doesn’t prove anything.

Further reading: AWS NAT gateway

If you want to go further with the AWS NAT gateway, read NAT gateways and Gateway endpoints for Amazon S3 in the AWS documentation. The full plan for this course is on the AWS Cloud Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.