Software Crafting

Slashing AWS Networking Costs: Replacing Expensive NAT Gateways with VPC Endpoints for Node.js Microservices

DDeepak RajputCloud and DevOps8 min read08 Apr 2026Updated 2026-11-07
Glass octagonal nodes with cyan and purple bases on a dark tiled floor, connected by bundles of glowing red lines

TL;DR: Reduce NAT Gateway data processing fees for your Node.js microservices by routing traffic to AWS services through VPC Endpoints. This guide shows how to use Amazon Athena on VPC Flow Logs to find what is crossing the NAT Gateway, deploy no-cost Gateway Endpoints for S3 and DynamoDB with Terraform, and use Interface Endpoints where the per-GB saving (roughly $0.045 down to $0.01 per GB at us-east-1 list prices) outweighs their hourly charge.

Key Takeaways

  • Query VPC Flow Logs using Amazon Athena to identify exactly which external IP addresses and AWS services are saturating your NAT Gateway data transfer.
  • Deploy Gateway Endpoints, which have no hourly or data processing charge, at the route table level to eliminate data processing fees for high-volume Amazon S3 and DynamoDB traffic.
  • Use the provided Terraform configuration to automate the provisioning and private route table association of your S3 Gateway Endpoints.
  • Keep Node.js S3 requests within the same AWS region; cross-region requests bypass Gateway Endpoints and will still incur NAT Gateway charges.
  • Provision Interface Endpoints for high-volume dependencies like ECR, CloudWatch Logs and SQS, where data processing drops from about $0.045/GB (₹3.8) to about $0.01/GB (₹0.85), and skip them for low-volume services where the hourly fee dominates.

You architect your infrastructure by the book: public subnets for Application Load Balancers, and private subnets for your Node.js microservices and PostgreSQL databases. By default, the instances in your private subnets lack public IP addresses. To allow them to communicate with the outside world, including AWS services like S3, DynamoDB, Secrets Manager, and CloudWatch-you provision a NAT Gateway.

Then, the end-of-month invoice arrives. A line item you did not plan for is suddenly large: NAT Gateway - Data Processed.

AWS charges about $0.045 (roughly ₹3.8) per GB for data processed through a NAT Gateway in regions such as US East, plus an hourly fee of a similar amount. Prices vary by region, so check the VPC pricing page for yours. If you have a high-throughput Node.js worker pulling 50TB of image assets from S3 monthly, or pushing gigabytes of verbose JSON logs to CloudWatch daily, the 50TB alone is about $2,250 (roughly ₹1.9 lakh) a month in NAT processing fees just to move data between your VPC and AWS services.

The fix is to send that traffic through VPC Endpoints (Gateway Endpoints, and Interface Endpoints powered by AWS PrivateLink) so it reaches AWS services without passing through the NAT Gateway.

Pinpointing NAT Gateway Bleed with VPC Flow Logs and Athena

Before changing infrastructure, you need evidence of which services are saturating your NAT Gateway. AWS Cost Explorer shows the aggregate bill, but it won't tell you what your Node.js apps are communicating with.

To trace the data, you must query your VPC Flow Logs. If you aren't already publishing flow logs to an S3 bucket, enable that first. Once the logs are in S3, create an Athena table for them (the VPC console's Athena integration can generate one) and query it. Athena column names match the flow log field names, such as srcaddr, dstaddr and bytes.

The following Athena SQL query aggregates outbound traffic from your private subnet CIDR blocks to external IP addresses, sorting by the highest data transfer volume.

SELECT
    dstaddr,
    SUM(bytes) / 1073741824.0 AS gigabytes_transferred,
    COUNT(*) AS flow_records
FROM vpc_flow_logs
WHERE
    srcaddr LIKE '10.0.%' -- Replace with your private subnet CIDR
    AND action = 'ACCEPT'
    AND dstaddr NOT LIKE '10.0.%' -- Exclude internal VPC traffic
GROUP BY dstaddr
ORDER BY gigabytes_transferred DESC
LIMIT 20;

When you run this, you will likely see high-volume traffic destined for AWS public IP ranges. You can cross-reference these IPs using the curl https://ip-ranges.amazonaws.com/ip-ranges.json dataset. If the top talkers are S3, DynamoDB, or ECR, endpoints are likely to pay off. This query only covers outbound bytes; responses (for example S3 downloads) are recorded with the AWS address as srcaddr, so run the mirror query on inbound traffic too.

Implementing Gateway Endpoints for High-Volume Data (S3 & DynamoDB)

AWS provides two types of VPC Endpoints. Gateway Endpoints are available only for Amazon S3 and DynamoDB, and AWS does not charge for them: there is no hourly charge and no data processing fee.

Instead of deploying elastic network interfaces (ENIs), Gateway Endpoints operate at the route table level. When you associate a Gateway Endpoint with your private subnet's route table, AWS injects a prefix list (e.g., pl-63a5400a) that intercepts traffic destined for S3 and routes it directly over the internal AWS network.

Here is a Terraform configuration to deploy an S3 Gateway Endpoint and attach it to your private route tables:

resource "aws_vpc_endpoint" "s3_gateway" {
  vpc_id            = aws_vpc.main.id
  service_name      = "com.amazonaws.${var.aws_region}.s3"
  vpc_endpoint_type = "Gateway"

  # This is the same as the default full-access policy.
  # Tighten it as shown in "Locking Down VPC Endpoint Policies" below.
  policy = jsonencode({
    Version = "2012-10-17",
    Statement = [
      {
        Action    = "*",
        Effect    = "Allow",
        Resource  = "*",
        Principal = "*"
      }
    ]
  })

  tags = {
    Name = "prod-s3-gateway-endpoint"
  }
}

resource "aws_vpc_endpoint_route_table_association" "private_s3" {
  count           = length(var.private_subnet_route_table_ids)
  route_table_id  = var.private_subnet_route_table_ids[count.index]
  vpc_endpoint_id = aws_vpc_endpoint.s3_gateway.id
}

Production Note: Gateway Endpoints are region-specific. If your VPC is in us-east-1, the S3 Gateway Endpoint will only intercept traffic destined for S3 buckets in us-east-1. If your Node.js application is fetching objects from an S3 bucket in eu-west-1, that traffic will bypass the Gateway Endpoint, fall back to the default route (0.0.0.0/0), and hit your NAT Gateway anyway.

Deploying Interface Endpoints for Backend Dependencies

For AWS services other than S3 and DynamoDB (such as Secrets Manager, SQS, SNS, KMS, and CloudWatch), you must use Interface Endpoints.

Unlike Gateway Endpoints, Interface Endpoints deploy actual ENIs into your subnets, consuming private IP addresses. In US East they cost about $0.01 (roughly ₹0.85) per GB processed plus about $0.01 per hour per AZ, around $7.30 (roughly ₹612) a month per AZ. That per-GB rate is about 78% lower than the NAT Gateway's $0.045/GB.

ECR (Elastic Container Registry) and CloudWatch Logs are common candidates. Fargate tasks pull images on every task start and push logs continuously, and in a VPC without a NAT Gateway, Fargate tasks need the ecr.api, ecr.dkr and logs interface endpoints plus the S3 gateway endpoint (ECR stores image layers in S3). If you want someone to audit and implement this for your account, our DevOps and cloud deployment services cover this kind of cost work.

Here is how you deploy an Interface Endpoint for CloudWatch Logs (logs) using Terraform. Notice the security group configuration: because this is an ENI residing in your subnet, you must explicitly allow inbound HTTPS traffic from your microservices.

resource "aws_security_group" "vpc_endpoint_sg" {
  name        = "vpc-endpoint-sg"
  description = "Allow TLS inbound for VPC Interface Endpoints"
  vpc_id      = aws_vpc.main.id

  ingress {
    description = "HTTPS from Private Subnets"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    # In production, restrict this to your specific private subnet CIDRs or workload Security Groups
    cidr_blocks = [aws_vpc.main.cidr_block]
  }
}

resource "aws_vpc_endpoint" "cloudwatch_logs" {
  vpc_id            = aws_vpc.main.id
  service_name      = "com.amazonaws.${var.aws_region}.logs"
  vpc_endpoint_type = "Interface"

  subnet_ids         = var.private_subnet_ids
  security_group_ids = [aws_security_group.vpc_endpoint_sg.id]

  # Makes the standard service hostname resolve to the endpoint's private IPs
  private_dns_enabled = true

  tags = {
    Name = "prod-cloudwatch-logs-endpoint"
  }
}

The private_dns_enabled = true flag matters. AWS associates a managed private hosted zone with your VPC that overrides the public DNS name for the service. When your Node.js app asks for logs.us-east-1.amazonaws.com, the Route 53 Resolver returns the private 10.0.x.x IPs of your Interface Endpoint, so the traffic stays inside the VPC with no code change. This requires enableDnsSupport and enableDnsHostnames on the VPC.

Configuring the Node.js AWS SDK v3 for Explicit Endpoint Routing

If you set private_dns_enabled = true on your Interface Endpoints and configure your route tables correctly for Gateway Endpoints, your Node.js code usually requires zero modifications. The AWS SDK natively uses the standard service hostnames, which are automatically intercepted by DNS or the route table.

However, in advanced multi-account architectures or shared VPC setups, you might not be able to enable Private DNS due to overlapping namespace conflicts. In these cases, you must explicitly tell the AWS SDK v3 to route requests to the VPC Endpoint's specific DNS name.

Connection reuse also matters for high-throughput clients. The SDK v3 NodeHttpHandler already creates an HTTPS agent with keepAlive: true and maxSockets: 50 by default. Pass your own agent only when you need different values, for example a larger pool for a worker that sends many concurrent SQS requests.

Here is an AWS SDK v3 configuration for an SQS client pointing to an explicit VPC Interface Endpoint with a custom connection pool:

import { SQSClient } from '@aws-sdk/client-sqs';
import { NodeHttpHandler } from '@smithy/node-http-handler';
import https from 'https';

// Reuse TLS connections to the VPC Endpoint. keepAlive and maxSockets: 50
// are already the SDK defaults; raise maxSockets only if you need more concurrency.
const customAgent = new https.Agent({
  keepAlive: true,
  maxSockets: 100,
  scheduling: 'lifo',
  timeout: 60000,
});

const sqsClient = new SQSClient({
  region: 'us-east-1',
  // Override the endpoint if private_dns_enabled is false
  endpoint: 'https://vpce-0123456789abcdef0-12345678.sqs.us-east-1.vpce.amazonaws.com',
  requestHandler: new NodeHttpHandler({
    httpsAgent: customAgent,
    connectionTimeout: 5000,
  }),
  maxAttempts: 3,
});

export const sendMessage = async (queueUrl: string, body: string) => {
  // Traffic goes to the VPC Endpoint ENI instead of through the NAT Gateway
  // ...
};

Tip: If you are hardcoding the endpoint like above, verify your security groups. If the Node.js process times out connecting to the VPC endpoint, it is usually a security group issue on the endpoint's ENI blocking inbound port 443 from the application's security group.

Locking Down VPC Endpoint Policies

When you bypass the public internet, you are implicitly relying on your VPC boundaries for security. But what happens if a compromised Node.js worker tries to exfiltrate data by writing it to an S3 bucket owned by an attacker's AWS account?

With the default full-access endpoint policy, the Gateway Endpoint carries requests to any S3 bucket in that region, so the worker can reach the attacker's bucket.

To prevent data exfiltration, you must attach a strict VPC Endpoint Policy. If you do not attach a policy, AWS attaches a default policy that allows full access. Replace it with a policy that restricts access to buckets in AWS accounts you own, plus any AWS-owned buckets your workloads depend on.

Here is a restricted JSON policy block for an S3 Gateway Endpoint. It allows requests through the endpoint only to S3 buckets owned by your AWS account, plus read access to the AWS-owned bucket that stores ECR image layers:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "RestrictToSpecificAccount",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceAccount": "111122223333"
        }
      }
    },
    {
      "Sid": "AllowEcrImageLayers",
      "Effect": "Allow",
      "Principal": "*",
      "Action": ["s3:GetObject"],
      "Resource": "arn:aws:s3:::prod-us-east-1-starport-layer-bucket/*"
    }
  ]
}

Notice the second block: AllowEcrImageLayers. ECR stores image layers in an AWS-owned bucket named prod-<region>-starport-layer-bucket, so without this statement your Fargate tasks and nodes can no longer pull images. Other AWS-owned buckets can be affected in the same way (for example, Amazon Linux package repositories), so test instance bootstrapping and image pulls after tightening the policy.

Architectural Trade-offs and the Break-Even Point

You shouldn't blindly provision an Interface Endpoint for every AWS service. Because each Interface Endpoint carries an hourly cost per AZ (about $7.30, roughly ₹612, a month in US East), provisioning 10 endpoints across 3 Availability Zones costs around $219 (roughly ₹18,000) a month before a single byte is transferred.

The Math (US East list prices, check your region):

  • NAT Gateway data processing: about $0.045 (₹3.8) / GB
  • Interface Endpoint data processing: about $0.01 (₹0.85) / GB
  • Delta: about $0.035 (₹2.98) / GB saved.

To justify the ~₹612/month hourly cost of a single Interface Endpoint in a single AZ, you need to push at least about 210 GB of data per month to that specific AWS service ( $7.30 / $0.035 = 208.6 ).

If your service pulls 10MB of Secrets Manager data a month, let it ride the NAT Gateway. If your service pulls 2TB of ECR images a month, provision the ECR Interface Endpoints (com.amazonaws.region.ecr.api and com.amazonaws.region.ecr.dkr). Gateway Endpoints (S3/DynamoDB) have no hourly or data processing charge, so they are worth adding to every VPC that talks to those services. Note that AWS warns existing S3 connections can be briefly interrupted when you add the S3 gateway endpoint, so do it in a maintenance window.

Sources

Available for Work

Need help building this in production?

SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.

Get a Free Consultation

Frequently Asked Questions

How can I find out which AWS services are driving up my NAT Gateway costs?

You can identify high-volume traffic sources by querying your VPC Flow Logs using Amazon Athena. By filtering outbound traffic from your private subnets and grouping by destination IP, you can cross-reference the top IP addresses with AWS public IP ranges to pinpoint the exact services causing the high costs.

What is the difference between Gateway Endpoints and Interface Endpoints in AWS?

Gateway Endpoints operate at the route table level, have no hourly or data processing charge, and are only available for Amazon S3 and DynamoDB. Interface Endpoints deploy Elastic Network Interfaces (ENIs) into your subnets for services like CloudWatch or Secrets Manager, charging an hourly rate per AZ and a reduced data processing fee of about $0.01 (₹0.85) per GB in US East.

Will an S3 Gateway Endpoint cover traffic to S3 buckets in other AWS regions?

No, Gateway Endpoints are region-specific. If your VPC is in us-east-1 but your Node.js application fetches objects from a bucket in eu-west-1, that cross-region traffic will bypass the Gateway Endpoint and still incur NAT Gateway data processing fees.

Are Interface Endpoints actually cheaper than using a NAT Gateway?

For high-volume traffic, yes. In US East, NAT Gateways charge about $0.045 (₹3.8) per GB processed and Interface Endpoints about $0.01 (₹0.85) per GB, roughly 78% less per GB. But each Interface Endpoint also has an hourly charge per AZ, so below roughly 200 GB a month per service and AZ the NAT Gateway can still be cheaper.

About the author

Deepak Rajput

Founder and CEO of SoftwareCrafting

Deepak Rajput is the Founder and CEO of SoftwareCrafting in Delhi and writes about web, mobile, backend, cloud, security, and engineering leadership.

Writes about Next.js, Node.js, React Native, PostgreSQL, AWS, Kubernetes.

View author profile

Last updated: 2026-11-07