Explain it simply
Explain it simply
Imagine your private subnets are an office with no front door to the street. Today, every trip to S3 or SQS goes out through a paid side gate, the NAT Gateway, which charges for every box you carry.
A gateway endpoint is a free private corridor from your office straight into the S3 or DynamoDB building. An interface endpoint is a small service desk placed inside your office: you talk to the desk at a local address, and it carries the request to the AWS service privately.
PrivateLink uses the same service-desk idea for services you or a vendor build. Another team can place a desk for your API inside their office, without the two buildings ever being joined by a road.
Problem → Why → Solution
The problem: paying NAT prices to reach AWS itself
In the previous lessons, private-app subnets reach the outside world through a NAT Gateway. That includes every call to S3, DynamoDB, SQS and Secrets Manager, because those APIs live at public endpoints. A nightly export that writes 20 TB a month to S3 pays NAT data processing on every gigabyte, and the NAT line quietly becomes one of the largest items on the bill.
The private-data tier has the opposite problem: it has no internet route at all, so a database migration task there cannot even fetch a secret from Secrets Manager. Security teams also want proof that sensitive buckets are only reachable from inside approved networks.
# Bytes the NAT Gateway sent toward destinations last month.
# If most of it is S3/DynamoDB traffic, you are paying NAT prices for nothing.
aws cloudwatch get-metric-statistics \
--namespace AWS/NATGateway --metric-name BytesOutToDestination \
--dimensions Name=NatGatewayId,Value=nat-0a1b2c3d4e5f67890 \
--start-time 2026-10-01T00:00:00Z --end-time 2026-11-01T00:00:00Z \
--period 2678400 --statistics SumWhy it matters
Traffic from your VPC to an AWS service in the same Region does not need to leave a private path. Without endpoints you pay per-GB NAT processing for it, isolated subnets cannot reach AWS APIs at all, and bucket policies have no reliable network identity to check.
Core concept: two kinds of endpoint, one private path
- VPC endpoint
- A private entry point in your VPC to an AWS service or a PrivateLink service, so traffic reaches it without an internet gateway, NAT Gateway, VPN or public IP.
| Aspect | Gateway endpoint | Interface endpoint |
|---|---|---|
| Services | S3 and DynamoDB only | Most AWS services, plus PrivateLink services |
| Mechanism | Prefix-list route in chosen route tables | ENI with a private IP in each chosen subnet |
| DNS | Public name; the route catches the traffic | Private DNS maps the public name to the ENI IPs |
| Reachable from on-prem or other VPCs | No | Yes, over VPN, Direct Connect, peering or TGW |
| Cost | No hourly or data charge | Per hour in each AZ plus per GB processed |
| Controls | Endpoint policy | Endpoint policy and security groups |
Gateway endpoints are the easy win. Adding one inserts a route whose destination is the service's managed prefix list, so traffic to S3 or DynamoDB in the same Region takes the endpoint instead of the NAT Gateway, with no code changes and no charge. There is almost no reason not to add both to every VPC.
Interface endpoints are powered by PrivateLink. With private DNS enabled (and the VPC's DNS support and DNS hostnames turned on), the normal SDK hostname such as sqs.us-east-1.amazonaws.com resolves to the endpoint's private IPs, so applications again need no changes. Because each endpoint is billed per AZ-hour, a low-volume service in a VPC that already has a NAT Gateway may cost more through an endpoint than through NAT; high-volume services and isolated subnets are where interface endpoints clearly pay off.
Both kinds accept an endpoint policy, a resource policy attached to the endpoint itself. It never grants permissions; it is an extra filter on top of IAM and bucket policies. A common use is allowing the S3 endpoint to reach only your organization's buckets, which blocks a compromised instance from copying data into an attacker's bucket.
The reverse direction uses the condition key aws:SourceVpce in a bucket policy: deny object access unless the request arrived through a specific endpoint. Together they form a small data perimeter, with the network and the resource each checking the other.
TWO PRIVATE PATHS OUT OF AN ISOLATED SUBNET
-------------------------------------------
private subnet 10.30.0.0/22 (no NAT, no internet gateway)
+---------------------------------------------------+
| [app] |
| | s3.us-east-1.amazonaws.com (public name) |
| | route table: pl-(S3 list) -> vpce (gateway) +----> Amazon S3
| | |
| | sqs.us-east-1.amazonaws.com |
| | private DNS -> 10.30.1.25 |
| +--> [ENI vpce (interface), SG allows 443] ----+----> Amazon SQS
+---------------------------------------------------+- S3/DynamoDB: gateway route, free
- Other APIs: interface ENI + DNS
- Endpoint policy filters the path
- SourceVpce pins the resource
Ask two questions for every AWS API your private subnets call: how many GB per month, and does it need to be reachable from outside this VPC? The answers pick the endpoint type.
Pattern: creating both endpoint types
VPC_ID=vpc-0a1b2c3d4e5f67890
# Gateway endpoint: a prefix-list route in each listed route table
aws ec2 create-vpc-endpoint --vpc-id $VPC_ID \
--vpc-endpoint-type Gateway \
--service-name com.amazonaws.us-east-1.s3 \
--route-table-ids rtb-0a1b2c3d4e5f6c001 rtb-0a1b2c3d4e5f6c002
# Interface endpoint: one ENI per subnet, private DNS for the public name
aws ec2 create-vpc-endpoint --vpc-id $VPC_ID \
--vpc-endpoint-type Interface \
--service-name com.amazonaws.us-east-1.sqs \
--subnet-ids subnet-0a1b2c3d4e5f6a001 subnet-0a1b2c3d4e5f6b001 \
--security-group-ids sg-0a1b2c3d4e5f67890 \
--private-dns-enabled
# What did the gateway endpoint add?
aws ec2 describe-route-tables --route-table-ids rtb-0a1b2c3d4e5f6c001 \
--query 'RouteTables[0].Routes[?DestinationPrefixListId]'Service names follow com.amazonaws.<region>.<service>. A gateway endpoint takes route table IDs; an interface endpoint takes subnets (one per AZ) and security groups that must allow HTTPS from your clients. The last command shows the pl- route that now steers S3 traffic.
Working example: a VPC with no NAT that still reaches AWS
This CDK app builds a VPC with only isolated subnets. Gateway endpoints give it S3 and DynamoDB, interface endpoints give it SQS and Secrets Manager, the S3 endpoint policy limits it to one bucket, and the bucket policy refuses object reads and writes that did not come through that endpoint.
import { App, CfnOutput, Stack } from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as iam from "aws-cdk-lib/aws-iam";
import * as s3 from "aws-cdk-lib/aws-s3";
const app = new App();
const stack = new Stack(app, "PrivateAccessStack");
// No NAT Gateway at all: the only way out is through endpoints
const vpc = new ec2.Vpc(stack, "Vpc", {
ipAddresses: ec2.IpAddresses.cidr("10.30.0.0/20"),
maxAzs: 2,
natGateways: 0,
subnetConfiguration: [
{ name: "app", subnetType: ec2.SubnetType.PRIVATE_ISOLATED, cidrMask: 22 },
],
});
// 1. Gateway endpoints: route-table entries, no hourly charge
const s3Endpoint = vpc.addGatewayEndpoint("S3", {
service: ec2.GatewayVpcEndpointAwsService.S3,
});
vpc.addGatewayEndpoint("DynamoDb", {
service: ec2.GatewayVpcEndpointAwsService.DYNAMODB,
});
// 2. Interface endpoints: ENIs + private DNS, billed per AZ-hour and per GB
vpc.addInterfaceEndpoint("Sqs", {
service: ec2.InterfaceVpcEndpointAwsService.SQS,
privateDnsEnabled: true,
});
vpc.addInterfaceEndpoint("Secrets", {
service: ec2.InterfaceVpcEndpointAwsService.SECRETS_MANAGER,
privateDnsEnabled: true,
});
const data = new s3.Bucket(stack, "Data", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
});
// 3. Endpoint policy: through this endpoint, only this bucket
s3Endpoint.addToPolicy(
new iam.PolicyStatement({
principals: [new iam.AnyPrincipal()],
actions: ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
resources: [data.bucketArn, data.arnForObjects("*")],
}),
);
// 4. Bucket policy: object reads/writes only via this endpoint
data.addToResourcePolicy(
new iam.PolicyStatement({
effect: iam.Effect.DENY,
principals: [new iam.AnyPrincipal()],
actions: ["s3:GetObject", "s3:PutObject"],
resources: [data.arnForObjects("*")],
conditions: {
StringNotEquals: { "aws:SourceVpce": s3Endpoint.vpcEndpointId },
},
}),
);
new CfnOutput(stack, "S3EndpointId", { value: s3Endpoint.vpcEndpointId });
app.synth();Not runnable in the browser
This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.
Code breakdown
- natGateways: 0
natGateways: 0,The subnets are PRIVATE_ISOLATED: no NAT Gateway, no default route. Anything that works afterwards works only because of an endpoint, which makes the design easy to reason about.
- Gateway endpoints
vpc.addGatewayEndpoint("S3", { ... })CDK adds the prefix-list route to every subnet's route table by default. These two endpoints are free, so they belong in every VPC you build.
- Interface endpoints
privateDnsEnabled: true,CDK creates an ENI in each isolated subnet and a security group that allows HTTPS from the VPC CIDR. Private DNS lets the unchanged SDK hostnames resolve to those ENIs.
- Endpoint policy
s3Endpoint.addToPolicy(...)Replaces the default full-access policy. Requests through this endpoint to any other bucket are denied, even if the caller's IAM role would allow them.
- aws:SourceVpce
StringNotEquals: { "aws:SourceVpce": s3Endpoint.vpcEndpointId }Object reads and writes from anywhere else, including the console and laptops, are denied. Scoping the Deny to object actions keeps bucket management possible for administrators.
cdk synth produces one stack with the VPC, two isolated subnets and their route tables, two gateway endpoints (S3, DynamoDB), two interface endpoints (SQS, Secrets Manager) with their security groups, the bucket with its policy, and an S3EndpointId output. After cdk deploy, the private subnets' route tables show a pl- route pointing at the S3 gateway endpoint.Publishing your own service with PrivateLink
The same technology lets you be the provider. Put your service behind a Network Load Balancer, create an endpoint service from that NLB, and allow specific AWS principals to connect. Consumers create an interface endpoint to your service name in their own VPC and talk to a private IP in their own subnet.
The connection is one-directional: consumers can open connections to your NLB, but your service cannot reach into their VPC. No route tables change on either side, so overlapping CIDRs do not matter. That makes PrivateLink the standard way for SaaS vendors and internal platform teams to offer an API to hundreds of accounts without peering or Transit Gateway access to all of them.
Provider: create the endpoint service
From an existing internal NLB, with acceptance required so you approve each consumer.
Provider: allow principals
Only allowed accounts or roles can even request a connection.
Consumer: create an interface endpoint
Using the service name com.amazonaws.vpce.<region>.vpce-svc-...
Provider: accept the connection
After acceptance the consumer's endpoint becomes available.
# --- provider account (111122223333) ---
NLB_ARN=arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer
NLB_ARN=$NLB_ARN/net/pricing-api/0a1b2c3d4e5f6789
SVC_ID=$(aws ec2 create-vpc-endpoint-service-configuration \
--network-load-balancer-arns $NLB_ARN --acceptance-required \
--query 'ServiceConfiguration.ServiceId' --output text)
aws ec2 modify-vpc-endpoint-service-permissions --service-id $SVC_ID \
--add-allowed-principals arn:aws:iam::444455556666:root
# --- consumer account (444455556666) ---
aws ec2 create-vpc-endpoint --vpc-id vpc-0f9e8d7c6b5a43210 \
--vpc-endpoint-type Interface \
--service-name com.amazonaws.vpce.us-east-1.$SVC_ID \
--subnet-ids subnet-0f9e8d7c6b5a4a001 subnet-0f9e8d7c6b5a4b001 \
--security-group-ids sg-0f9e8d7c6b5a43210
# --- provider again: approve the pending connection ---
aws ec2 accept-vpc-endpoint-connections --service-id $SVC_ID \
--vpc-endpoint-ids vpce-0f1e2d3c4b5a69788Endpoint policies and bucket policies together
A request through an endpoint must pass three checks: the caller's IAM policy, the endpoint policy and the bucket policy. The bucket policy below is the classic perimeter statement. Note that aws:SourceIp does not work for requests arriving through a VPC endpoint, because the source is a private address; use aws:SourceVpce for a specific endpoint, aws:SourceVpc for any endpoint in a VPC, or aws:VpcSourceIp for the private IP.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyObjectAccessOutsideTheEndpoint",
"Effect": "Deny",
"Principal": "*",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": "arn:aws:s3:::orders-data-111122223333/*",
"Condition": {
"StringNotEquals": { "aws:SourceVpce": "vpce-0a1b2c3d4e5f67890" }
}
}
]
}Test the Deny before you apply it
A Deny on s3:* with aws:SourceVpce also blocks the console, CI pipelines and even changes to the bucket policy itself from outside the endpoint. Scope the Deny to data actions, or add an exception for a break-glass role with aws:PrincipalArn, and test from both inside and outside the VPC.
In production
In production
Platform teams add S3 and DynamoDB gateway endpoints to every VPC from the account baseline, because they are free and remove a large share of NAT traffic immediately. Interface endpoints are a cost decision. With fifty VPCs, putting ten interface endpoints in every VPC across three AZs means 1,500 endpoint ENIs billed hourly, so larger organizations centralize them in a shared-services VPC and reach them through the Transit Gateway.
Centralization needs DNS work: private DNS on a shared endpoint only answers inside its own VPC, so teams turn it off, create Route 53 private hosted zones such as sqs.us-east-1.amazonaws.com pointing at the shared endpoint, and associate those zones with every spoke VPC. The trade-off is Transit Gateway data processing on that traffic, so very high-volume services often keep a local endpoint.
On the provider side, many vendors (monitoring, data warehouses, payment platforms) publish PrivateLink services so customers can reach them without public internet paths, and internal teams use the same model to expose a shared API to every business unit regardless of overlapping address space.
Common mistakes
Common mistakes
Mistake 1: an S3 endpoint policy that breaks hidden dependencies
Restricting the S3 gateway endpoint to your own buckets looks safe until package installs, container pulls or agents start failing. Amazon Linux package repositories, ECR image layers and some AWS agents fetch from AWS-owned S3 buckets through the same route. Allow the AWS-owned buckets you depend on explicitly, then test a deploy end to end.
Mistake 2: interface endpoint without working private DNS
If private DNS is off, or the VPC has DNS hostnames disabled, the SDK still resolves the public service address. In a subnet with NAT the traffic silently keeps flowing through NAT, so the bill does not drop; in an isolated subnet calls simply time out. Check with nslookup from an instance that the service name returns a private IP.
Mistake 3: a security group that blocks the endpoint
Interface endpoint ENIs have their own security group. If it does not allow TCP 443 from the client subnets (or from the spoke VPC ranges when centralized), connections hang. Gateway endpoints have no security group, which is why the same app may reach S3 but not SQS.
Best practices
Best practices
- Add S3 and DynamoDB gateway endpoints to every VPC as part of the baseline.
- Add interface endpoints where volume or isolation justifies the hourly cost; review NAT metrics to find candidates.
- Write endpoint policies that allow your organization's resources plus the AWS-owned buckets you rely on.
- Scope aws:SourceVpce Deny statements to data actions and keep a tested break-glass path.
💰 Cost & Cleanup
Gateway endpoints for S3 and DynamoDB are free. Each interface endpoint is billed per hour in every AZ where it has an ENI, plus per GB processed, so the two interface endpoints across two AZs in this lab bill four endpoint-hours every hour. An endpoint service has no charge of its own, but its NLB is billed hourly and by capacity used, and consumers pay for their interface endpoints. None of this is free tier; destroy the stack and delete endpoint services right after the lab, and check the PrivateLink pricing page for current rates.
Clean up when you are done
# CDK example: VPC, endpoints, bucket
cdk destroy PrivateAccessStack
# CLI endpoints and the endpoint service
aws ec2 delete-vpc-endpoints \
--vpc-endpoint-ids vpce-0a1b2c3d4e5f67890 vpce-0f1e2d3c4b5a69788
aws ec2 delete-vpc-endpoint-service-configurations --service-ids $SVC_IDMini challenge
Mini challenge: find VPCs paying NAT for S3
Write a boto3 audit script that lists every VPC in the Region and reports which ones are missing an S3 or DynamoDB gateway endpoint, so the platform team knows where free savings are waiting.
- Page through describe_vpcs so large accounts are covered
- Look only at Gateway endpoints for that VPC
- Print one line per VPC (Name tag if present) with OK or the missing services
Expected: For an account with a default VPC, an orders VPC with both endpoints and a reports VPC with only S3, the script prints: default-vpc MISSING dynamodb, s3 / orders OK / reports MISSING dynamodb.
Show hint
describe_vpc_endpoints accepts Filters for vpc-id and vpc-endpoint-type. Build the expected service names from ec2.meta.region_name and compare sets.
Show solution
import boto3
ec2 = boto3.client("ec2", region_name="us-east-1")
REGION = ec2.meta.region_name
WANTED = {f"com.amazonaws.{REGION}.s3", f"com.amazonaws.{REGION}.dynamodb"}
def vpc_name(vpc):
tags = {t["Key"]: t["Value"] for t in vpc.get("Tags", [])}
return tags.get("Name", "default-vpc" if vpc["IsDefault"] else vpc["VpcId"])
def gateway_services(vpc_id):
resp = ec2.describe_vpc_endpoints(
Filters=[
{"Name": "vpc-id", "Values": [vpc_id]},
{"Name": "vpc-endpoint-type", "Values": ["Gateway"]},
]
)
return {e["ServiceName"] for e in resp["VpcEndpoints"]}
vpcs = []
for page in ec2.get_paginator("describe_vpcs").paginate():
vpcs.extend(page["Vpcs"])
for vpc in sorted(vpcs, key=vpc_name):
have = gateway_services(vpc["VpcId"])
missing = sorted(svc.split(".")[-1] for svc in WANTED - have)
status = "OK" if not missing else "MISSING " + ", ".join(missing)
print(f"{vpc_name(vpc):<12} {status}")Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Gateway endpoints (S3, DynamoDB) are prefix-list routes: free, VPC-local, and worth adding everywhere.
- Interface endpoints are ENIs with private DNS: reachable from on-prem and other VPCs, billed per AZ-hour and per GB.
- Endpoint policies filter what can pass through an endpoint; aws:SourceVpce pins a resource to an endpoint.
- PrivateLink endpoint services publish an NLB-fronted service one-way, even across overlapping CIDRs.
AWS PrivateLink: VPC endpoints concepts — AWS Documentation
Gateway endpoints — AWS Documentation
AWS PrivateLink pricing — AWS Documentation