
Find the IP pairs behind your cross-AZ data transfer bill (Part 1): Capture and enrich VPC Flow Logs
Build the capture and enrichment half of a cross-AZ cost pipeline with VPC Flow Logs, Amazon S3, AWS Lambda, Parameter Store and AWS Glue.
Running workloads across Availability Zones (AZs) improves resilience, but in most AWS Regions traffic between two AZs in one VPC costs $0.01/GB in each direction, or $0.02 per gigabyte exchanged. Chatty services, cross-AZ database reads and centralized NAT gateways can make that cost easy to miss.
Your bill shows regional data-transfer spend, but not which workloads caused it. VPC Flow Logs can. This series builds a serverless pipeline that estimates cross-AZ cost for each IP-address pair. Part 1 captures and enriches the logs, Part 2 analyses them with Athena, and Part 3 adds Quick Sight and production guidance.
You do most of the work in the AWS Management Console and paste in the scripts and SQL shown in full below.
What you'll learn
- Which VPC Flow Logs fields you need for AZ analysis, and why the default format isn't enough
- Why summing bytes over raw flow logs overstates traffic, and how to count each flow once
- How AWS Transit Gateway and NAT gateways change the cross-AZ picture
- How to build the capture and enrichment pipeline that Part 2 queries with Athena
One pricing rule to know first
Cross-AZ traffic inside a VPC, or over VPC peering, is charged at the regional data transfer rate : $0.01/GB out of one AZ plus $0.01/GB into the other. Traffic that crosses AZs through a Transit Gateway has no cross-AZ charge . Instead you pay Transit Gateway data processing , $0.02/GB in us-east-1, on every gigabyte sent into the Transit Gateway, whatever the AZs are.
The amount is similar, but the trigger differs. So "source AZ ≠ destination AZ" isn't enough to call something cross-AZ cost. You also need to know whether both ends are in the same VPC. The pipeline records the VPC of both ends and keeps the two cost types apart.
Architecture

- VPC Flow Logs write Parquet files to Amazon S3, with the fields the analysis needs.
- An AWS Lambda function builds a network map: every subnet's CIDR, AZ ID and VPC, plus which IPs are NAT gateways and Transit Gateway ENIs. It stores the map in AWS Systems Manager Parameter Store.
- An hourly AWS Glue job reads only new flow log files, sums bytes per hour, IP pair and observing ENI, and adds subnet, AZ ID, VPC and labels for both ends.
- An Amazon Athena view counts each flow once and classifies it. A query estimates the cost per IP pair (Part 2).
- An Amazon Quick Sight dashboard shows cost KPIs, an IP-to-IP heat map and a detail table (Part 3).
Why each flow is logged more than once
Each connection is logged by every elastic network interface (ENI) it crosses: client, server and, for inter-VPC traffic, both Transit Gateway attachment ENIs. Our 1 GiB Transit Gateway transfer appeared in four ENIs' logs. Two details rule out simply counting at the sender:
- Flow logs are best effort. An ENI can skip records (
log-status = SKIPDATA) or deliver files late. In our first test, the sender missed the 1 GiB transfer.
- Transit Gateway ENIs log their own address in
srcaddrordstaddr. The real endpoints are inpkt-srcaddr/pkt-dstaddr.
The Glue job rewrites Transit Gateway ENI addresses to the real endpoints and sums bytes per observing ENI. For each hour and IP pair, Athena takes the maximum across observers, counting the flow once even when one observer missed it.
Choose your path
| Lab | Your own VPCs |
|---|---|---|
Use when | You want to learn with predictable test traffic | You want results for real workloads |
Start at | Step 0 | Step 1, after reading the notes below |
Extra cost | ≈ $8/day for the lab network while it runs | Flow log delivery for your traffic volume |
Every step after Step 0 is the same for both paths. Where this post says VPC A and VPC B, use your own VPC IDs.
Notes for your own VPCs
- Estimate flow log cost first. S3 delivery incurs CloudWatch Logs delivery charges per GB (the "vended logs" rate), plus Parquet conversion. Start with one VPC for a day and check its volume before adding more.
- Existing flow logs can stay. A resource supports up to 250 flow log subscriptions ( limitations ). You can't change the fields of an existing flow log, so add a new one if yours lacks
pkt-srcaddr/pkt-dstaddr.
- Already have Parquet flow logs with the 9 required fields (Step 2)? Skip Step 2 and point the Glue job's
--flow_logs_pathat them.
- VPC peering instead of a Transit Gateway? Peering traffic is charged at the cross-AZ rate. Change one line in the Athena view (Part 2).
- Using a regional NAT gateway? This was tested with zonal NAT gateways. Regional NAT flow logs set
interface-idandsubnet-idto-and identify the gateway inresource-id. Add that field and use it as the observer wheninterface-idis-; otherwise records share one observer. The Lambda labels only zonalnat_gatewayENIs.
- Many subnets? Parameter Store values are limited to 8 KB, roughly 60 subnets plus labels. For more, store the map in S3 (see Part 3).
Required source: Summary tabs are explanations, not executable code. Open every nearby Complete templates or Complete code tab and copy the full block before following either Console or CLI.
Prerequisites
- An AWS account and Region (this post uses us-east-1) where you can create S3, Lambda, IAM, Glue and Athena resources.
- For the CLI alternatives: AWS CloudShell , or bash with AWS CLI v2 and
jq. Set these once:
export AWS_REGION=us-east-1export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)export BUCKET=cross-az-analytics-$ACCOUNT_ID-$AWS_REGIONAll required files appear in Parts 1 and 2. Save them under the names shown (
lambda/subnet_mapper.py , iam/*.json , sql/*.sql , cross-az-flowlogs-enrichment.py ). Part 3 will link to the companion repository.Step 0 (lab path only): Deploy the lab network
Use this step when you want a new, disposable environment with predictable traffic, preferably in a sandbox account or Region. If you are analysing your own VPCs, skip to Step 1.
The lab reuses the Networking Immersion Day Multiple VPCs template (download
multi-vpc-create-all-vpcs-and-tgw.yaml ) to create VPCs A–C, two-AZ subnets, AZ1 NAT gateways, a Transit Gateway and private AZ1 servers. The other templates add the Systems Manager instance profile and AZ2 clients in VPCs A and B. They create only the network and instances; Steps 1–2 create the log destination and flow-log subscriptions.Both template files are required for the lab.
Select the Complete templates tab to view and copy the full templates.
In CloudFormation → Create stack → With new resources → Upload a template file, deploy these templates in order, keeping the defaults:
-
pre-requisites.yaml(shown in this section) asNetworkingWorkshopPrerequisites. Check the IAM acknowledgement on the last page.
-
multi-vpc-create-all-vpcs-and-tgw.yamlasNetworkingWorkshopMultiVPCandTGW. SetParticipantIPAddressto your public IP with/32.
-
lab-demo-clients.yaml(shown in this section) asCrossAzDemoClients. In the drop-downs, select VPC A, VPC B and their Private Subnet AZ2 subnets.
The stacks take about 3, 4 and 2 minutes. If you set the lab up in a second Region of the same account, skip
pre-requisites.yaml : it creates a named IAM instance profile, which is account-wide and already exists.
Step 1: Create the S3 bucket
One bucket holds everything: raw flow logs under
flow-logs/ , enriched data under processed/ , and Athena results under athena-results/ . Flow logs record IP addresses per connection, so treat the bucket as you would any log data under your retention and access rules. Raw logs expire after 30 days with the rule below; the much smaller enriched data under processed/ is kept until you delete it. Add a third rule for that prefix if your retention policy requires one. The CloudFormation template in Part 3 also turns on versioning, server access logging and a TLS-only bucket policy; add them here too if your standards ask for them.- S3 → Create bucket. Name it
cross-az-analytics-<account-id>-<region>. Keep the defaults (Block all public access, SSE-S3) → Create bucket.
- Open the bucket → Management → Create lifecycle rule twice:
-
expire-raw-flow-logs: prefixflow-logs/, Expire current versions of objects after 30 days.
-
expire-query-results: prefixathena-results/, after 7 days.

Step 2: Turn on VPC Flow Logs with the fields you need
Step 0 created the network and test instances, and Step 1 created the S3 destination. Neither step enabled the flow logs used by this post. Here you create one flow-log subscription for VPC A and one for VPC B. The default format lacks
pkt-srcaddr / pkt-dstaddr , which the job needs for Transit Gateway traffic, so both subscriptions use a custom format.The Glue job requires these 9 fields:
Field | Why |
|---|---|
srcaddr , dstaddr | Source and destination IP |
pkt-srcaddr , pkt-dstaddr | Real endpoints when a Transit Gateway ENI logged the record |
interface-id | Which ENI observed the flow, used to count each flow once |
bytes , packets | Volume |
start | Puts each flow in the right hour and day |
log-status | Excludes NODATA and SKIPDATA records |
We tested these 9 fields end to end and obtained the same cost results. Fewer fields reduce the delivery bill. The walkthrough adds 14 troubleshooting fields, 23 total; they do not change the calculation.
The 14 troubleshooting fields are:
vpc-id , subnet-id , az-id , instance-id , flow-direction , traffic-path , srcport , dstport , protocol , action , version , account-id , region and end . They identify the observing ENI's location, application and path, and add multi-account context. With the 9 required fields, the walkthrough uses 23 of more than 50 available:${version} ${account-id} ${region} ${vpc-id} ${subnet-id} ${az-id} ${instance-id} ${interface-id}${srcaddr} ${dstaddr} ${srcport} ${dstport} ${pkt-srcaddr} ${pkt-dstaddr} ${protocol} ${packets}${bytes} ${start} ${end} ${action} ${log-status} ${flow-direction} ${traffic-path}- VPC → Your VPCs, select VPC A and VPC B, then Actions → Create flow log. One form creates a flow log for each selected VPC.
- Settings:
- Name:
cross-az-analytics; Filter: All; Maximum aggregation interval: 1 minute
- Destination: Send to an Amazon S3 bucket; S3 bucket ARN:
arn:aws:s3:::cross-az-analytics-<account-id>-<region>/flow-logs
- Log record format: Custom format. In Log format, select all 23 fields from the code block above. The Format preview shows the result. Field order doesn't matter for Parquet, because the job reads columns by name.
- Log file format: Parquet; Hive-compatible S3 prefix: Enable; Partition logs by time: Every 1 hour (60 minutes)
- Choose Create flow log. The console adds a bucket policy that lets the log delivery service write to the bucket, and each VPC's Flow logs tab lists
cross-az-analytics.


Step 3: Build the network map with Lambda
Flow logs tell you which ENI saw a flow, not which AZ the other end is in. This function reads your subnets and managed ENIs and writes a map to Parameter Store:
{ "subnets": { "10.1.3.0/24": { "subnet_id": "subnet-016c...", "subnet_name": "VPC B Private Subnet AZ2", "az_id": "use1-az2", "vpc_id": "vpc-0919..." }, "...": "..." }, "resources": { "10.1.0.229": "NAT gateway", "10.1.5.24": "Transit Gateway ENI", "...": "..." }, "transit_gateway_ips": [ "10.0.5.26", "10.1.5.24", "10.1.5.8", "10.0.5.10" ]}The map uses AZ IDs (
use1-az1 ), not AZ names ( us-east-1a ), because AZ names map to different physical AZs in different accounts.The function and IAM policy are required by both setup methods.
Select the Complete code tab to view and copy the full code and policy.
Run the function again whenever you add subnets, NAT gateways or Transit Gateway attachments, or add an Amazon EventBridge schedule that invokes it daily.
- Lambda → Event Functions → Create Event Function → Author from scratch. Name
cross-az-subnet-mapper, runtime Python 3.14 → Create Event Function. Dismiss the Getting started dialog if it appears.
- On the Code tab, replace the contents of
lambda_function.pywith the code shown in the Complete code tab above and choose Deploy. The DEPLOY panel changes from Undeployed to Current.
- Configuration → General configuration → Edit: set Timeout to 1 min → Save.
- Configuration → Environment variables → Edit → Add environment variable:
VPC_IDS= your VPC IDs separated by commas, for examplevpc-aaaa,vpc-bbbb→ Save.
- Configuration → Permissions: choose the role name. In IAM, Add permissions → Create inline policy → JSON, paste the policy shown in the Complete code tab above (replace
REGIONandACCOUNT_ID) → Next, name itcross-az-subnet-mapper→ Create policy.
- Back in Lambda, on the Test tab choose Test. Under Details, the response shows the subnets, labelled IPs and Transit Gateway IPs found: 12, 6 and 4 in the lab. The map itself is in Systems Manager → Parameter Store →
/cross-az/subnet-map.


Step 4: Create the Glue enrichment job
Glue script
The script,
cross-az-flowlogs-enrichment.py (shown in full below; the commented version is in Part 3's repository), does four things:- Reads only new flow log files. With job bookmarks enabled, Glue remembers which S3 objects it has processed.
- Replaces Transit Gateway ENI addresses with
pkt-srcaddr/pkt-dstaddr, so the flow is attributed to its real endpoints.
- Sums bytes per hour, source IP, destination IP and observing ENI, which shrinks the data a lot.
- Looks up subnet, AZ ID, VPC and label for both ends in the network map, appends Parquet partitioned by the day the traffic happened, and creates or updates the
flow_logs_enrichedtable.
Select the Complete code tab to view and copy the full script.
4a. IAM role and database
- IAM → Roles → Create role. Trusted entity AWS service → Glue → Next. Search for and select AWSGlueServiceRole → Next. Name the role
CrossAzGlueJobRole→ Create role. The managed policy covers Glue, CloudWatch Logs and theaws-glue-assets-*bucket where the console stores your script.
- Open the role → Add permissions → Create inline policy → JSON, paste the policy shown in this section (replace
BUCKET,REGION,ACCOUNT_ID) → Next, name itcross-az-glue-job→ Create policy. For this console path, the inline policy reads onlyflow-logs/; the managedAWSGlueServiceRolepolicy covers theaws-glue-assets-*bucket where the console stores the script.
- AWS Glue → Data Catalog → Databases → Add database:
cross_az_analytics→ Create database. The job creates its table on the first run.
{ "Version": "2012-10-17", "Statement": [ { "Sid": "ListBucket", "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::BUCKET", "Condition": { "StringLike": { "s3:prefix": ["flow-logs/*", "processed/*"] } } }, { "Sid": "ReadFlowLogs", "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::BUCKET/flow-logs/*" }, { "Sid": "WriteEnrichedData", "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], "Resource": "arn:aws:s3:::BUCKET/processed/*" }, { "Sid": "ReadNetworkMap", "Effect": "Allow", "Action": "ssm:GetParameter", "Resource": "arn:aws:ssm:REGION:ACCOUNT_ID:parameter/cross-az/subnet-map" } ]}4b. The job
- AWS Glue → ETL jobs → Script editor. Engine Spark, Start fresh → Create script. Replace the editor contents with the script shown in the Complete code tab.
- On the Job details tab, change these settings. Several console defaults differ from what this job needs:
Setting | Value | Console default |
|---|---|---|
Name | cross-az-flowlogs-enrichment | Untitled job |
IAM role | CrossAzGlueJobRole | — |
Glue version | Glue 5.0 (the version we tested) | Glue 6.0 |
Worker type, Requested number of workers | G 1X, 2 | G 1X, 10 |
Job bookmark | Enable | Disable |
Number of retries | 0 | 0 |
Job timeout (minutes) | 30 | 480 |
Advanced properties → Maximum concurrency | 1 | 1 |
- Under Advanced properties → Job parameters, choose Add new parameter five times:
Key | Value |
|---|---|
--flow_logs_path | s3://BUCKET/flow-logs/AWSLogs/ |
--output_path | s3://BUCKET/processed/flow_logs_enriched/ |
--database_name | cross_az_analytics |
--table_name | flow_logs_enriched |
--ssm_parameter_name | /cross-az/subnet-map |
- Choose Save. The console stores the script in
s3://aws-glue-assets-<account-id>-<region>/scripts/.
- On the Schedules tab, Create schedule: name
cross-az-flowlogs-hourly, Frequency Hourly, Minute of the hour 5 → Create schedule. That'scron(5 0/1 * * ? *), five minutes past every hour (UTC).


Next: Part 2
Continue with Part 2: Calculate cost with Amazon Athena . It generates the lab test traffic, runs the Glue job, and builds the Athena view and queries that count each flow once and estimate the cross-AZ cost per IP pair.
Resources
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article