Thuta Learning
AWS Advanced
Advanced NetworkingDevOpsAdvanced

Transit Gateway: Hub-and-Spoke Routing and Segmentation

AWS AdvancedLesson 650 min

What you'll walk away with

  • Explain why full-mesh VPC peering stops scaling
  • Attach VPCs to a Transit Gateway and route traffic to it from VPC route tables
  • Use association and propagation to isolate prod and dev while sharing services
  • Share a Transit Gateway with AWS RAM and peer it across Regions
  • Estimate Transit Gateway cost and recognize when plain peering is still better

Explain it simply

Explain it simply

VPC peering is like building a private bridge between every pair of towns. With three towns you need three bridges, which is fine. With twenty towns you need 190 bridges, and a traveller still cannot cross two bridges in a row, because peering is non-transitive.

A Transit Gateway is a central bus station instead. Every town builds one road to the station, and the station's timetables, its route tables, decide which destinations each town is allowed to reach. Prod and dev can both reach the shared-services town without ever reaching each other.

You pay for the station by the hour for each connected road and by the gigabyte for what passes through it, so it is not free, but it is far simpler to run.

Problem → Why → Solution

The problem: the peering mesh

In AWS Fundamentals you peered two VPCs and added a route on each side. Now the organization has ten VPCs that all need to reach a shared-services VPC, an egress VPC and, in many cases, each other. A full mesh of n VPCs needs n(n-1)/2 peering connections: 45 for ten VPCs, plus at least 90 route entries, more if a VPC has several route tables.

Every new VPC means touching every other VPC's route tables, and because peering is non-transitive, you cannot simply peer everything to a central VPC and let it forward traffic. Ownership is also unclear: which team approves a peering request between two accounts it does not own?

mesh_math.py
def full_mesh(n):
    """Peering connections needed so every VPC reaches every other VPC."""
    return n * (n - 1) // 2


print(f"{'VPCs':>5} {'peerings':>9} {'routes':>7} {'TGW attachments':>16}")
for n in (3, 5, 10, 20, 50):
    links = full_mesh(n)
    # each peering needs a route on both sides (one route table per VPC)
    print(f"{n:>5} {links:>9} {2 * links:>7} {n:>16}")

Why it breaks down

Peering grows quadratically while a hub grows linearly: 50 VPCs need 1,225 peerings and 2,450 routes, but only 50 Transit Gateway attachments. Peering also has a per-VPC quota on active connections, and every change touches many accounts, so the mesh becomes a coordination problem long before it becomes a technical one.

Core concept: attachments, association, propagation

Transit Gateway (TGW)
A regional, highly available router that you attach networks to. It forwards traffic between attachments according to its own route tables, which are separate from VPC route tables.

An attachment is anything plugged into the hub: a VPC, a Site-to-Site VPN, a Direct Connect gateway, a Connect attachment for SD-WAN appliances, or a peering attachment to another Transit Gateway. A VPC attachment places an ENI in one subnet per AZ you choose, and resources can only use the TGW from AZs where that attachment has a subnet. That is why teams create small dedicated /28 attachment subnets in every AZ.

Traffic needs routes on both layers. The VPC route table must send the destination to the TGW (for example 10.0.0.0/8 to tgw-...), and the TGW route table must know which attachment owns the destination. Forgetting either side is the most common reason a new attachment does not work.

TermQuestion it answersRule
AssociationWhich TGW route table is used for traffic coming FROM this attachment?Exactly one table per attachment
PropagationWhich TGW route tables learn this attachment's routes automatically?Zero, one or many tables
Static routeWhere does a prefix go when nothing propagates it?Needed for peering attachments and default routes

Segmentation falls out of those two knobs. Give prod, dev and shared services their own route tables. Prod attachments associate with prod-rt, and prod-rt only receives propagations from prod and shared. Dev works the same way. The shared table receives propagations from everyone, so shared services can answer both. Prod and dev never see each other's routes, so their traffic is dropped at the hub even though both are plugged into it.

For segmentation to hold, turn off the TGW's default route table association and propagation when you create it. Otherwise every new attachment lands in one flat table that can reach everything.

text
SEGMENTED HUB-AND-SPOKE
-----------------------
      prod VPC            dev VPC            shared VPC
    10.16.0.0/19        10.20.0.0/19        10.24.0.0/19
         |                   |                   |
     [attach]            [attach]            [attach]
         |                   |                   |
  +------+-------------------+-------------------+------+
  |                  TRANSIT GATEWAY                    |
  |  prod-rt    assoc: prod     learns: prod, shared    |
  |  dev-rt     assoc: dev      learns: dev, shared     |
  |  shared-rt  assoc: shared   learns: prod, dev       |
  +-----------------------------------------------------+
   prod <-> shared: OK   dev <-> shared: OK   prod <-> dev: NO ROUTE
Mental model
  1. VPC route sends prefix to the TGW
  2. Association picks the TGW table
  3. Propagation fills the table
  4. No route in table = dropped

Read association as 'where do I look up routes when traffic arrives from this attachment' and propagation as 'who gets to know about this attachment'.

Working example: prod, dev and shared on one TGW

This script builds the segmented hub from the diagram using three existing VPCs, each with a /28 attachment subnet in two AZs. It disables the default tables, creates one route table per environment, wires associations and propagations, and finally adds the VPC-side routes. Run it from the network account that will own the TGW.

tgw-segmentation.sh
# 1. The hub: no default association/propagation, so nothing is flat
OPTS="AmazonSideAsn=64512,AutoAcceptSharedAttachments=enable"
OPTS="$OPTS,DefaultRouteTableAssociation=disable"
OPTS="$OPTS,DefaultRouteTablePropagation=disable,DnsSupport=enable"
TGW_ID=$(aws ec2 create-transit-gateway --description "core hub" \
  --options "$OPTS" --query 'TransitGateway.TransitGatewayId' --output text)
# ...wait until the TGW state is "available" (a few minutes)

# 2. One attachment per VPC, using the /28 attachment subnets in 2 AZs
attach() {
  aws ec2 create-transit-gateway-vpc-attachment \
    --transit-gateway-id $TGW_ID --vpc-id "$1" --subnet-ids "$2" "$3" \
    --query 'TransitGatewayVpcAttachment.TransitGatewayAttachmentId' \
    --output text
}
PROD_ATT=$(attach vpc-0a1b2c3d4e5f60001 subnet-0a1b2c3d4e5f6a001 subnet-0a1b2c3d4e5f6b001)
DEV_ATT=$(attach vpc-0a1b2c3d4e5f60002 subnet-0a1b2c3d4e5f6a002 subnet-0a1b2c3d4e5f6b002)
SHR_ATT=$(attach vpc-0a1b2c3d4e5f60003 subnet-0a1b2c3d4e5f6a003 subnet-0a1b2c3d4e5f6b003)

# 3. One TGW route table per environment
new_rt() {
  aws ec2 create-transit-gateway-route-table --transit-gateway-id $TGW_ID \
    --query 'TransitGatewayRouteTable.TransitGatewayRouteTableId' --output text
}
RT_PROD=$(new_rt); RT_DEV=$(new_rt); RT_SHR=$(new_rt)

# 4. Association: which table each attachment's traffic uses
associate() {
  aws ec2 associate-transit-gateway-route-table \
    --transit-gateway-route-table-id "$1" --transit-gateway-attachment-id "$2"
}
associate $RT_PROD $PROD_ATT
associate $RT_DEV $DEV_ATT
associate $RT_SHR $SHR_ATT

# 5. Propagation: who learns whose CIDR (prod and dev never learn each other)
propagate() {
  aws ec2 enable-transit-gateway-route-table-propagation \
    --transit-gateway-route-table-id "$1" --transit-gateway-attachment-id "$2"
}
propagate $RT_PROD $PROD_ATT; propagate $RT_PROD $SHR_ATT
propagate $RT_DEV $DEV_ATT;   propagate $RT_DEV $SHR_ATT
propagate $RT_SHR $PROD_ATT;  propagate $RT_SHR $DEV_ATT

# 6. VPC side: send the rest of 10.0.0.0/8 to the hub (one per route table)
aws ec2 create-route --route-table-id rtb-0a1b2c3d4e5f6c001 \
  --destination-cidr-block 10.0.0.0/8 --transit-gateway-id $TGW_ID

# 7. Check what dev can reach
aws ec2 search-transit-gateway-routes --transit-gateway-route-table-id $RT_DEV \
  --filters Name=state,Values=active \
  --query 'Routes[].[DestinationCidrBlock,Type,State]' --output table

Code breakdown

  1. Disable the defaultsOPTS="$OPTS,DefaultRouteTableAssociation=disable"

    With the defaults on, every attachment would associate with and propagate into one shared table, giving a flat network where prod can reach dev. Turning them off forces every attachment to be placed deliberately.

  2. Attachment subnets--subnet-ids "$2" "$3"

    One subnet per AZ. The TGW places an ENI in each, and only AZs listed here can send traffic through the hub, so include every AZ your workloads use.

  3. Associationassociate $RT_DEV $DEV_ATT

    Traffic arriving from the dev VPC is looked up in dev-rt. An attachment can be associated with only one route table at a time.

  4. Propagationpropagate $RT_DEV $SHR_ATT

    The shared VPC's CIDR is installed into dev-rt automatically. Because no line propagates PROD_ATT into RT_DEV, dev-rt has no route to prod and that traffic is dropped.

  5. VPC-side route--destination-cidr-block 10.0.0.0/8 --transit-gateway-id $TGW_ID

    Without this, instances never hand traffic to the TGW. Using the whole supernet keeps VPC route tables stable; the TGW route tables do the real filtering.

You should see
Sample output of the final command (dev-rt has dev and shared, no prod):
------------------------------------------
|       SearchTransitGatewayRoutes       |
+---------------+--------------+---------+
|  10.20.0.0/19 |  propagated  |  active |
|  10.24.0.0/19 |  propagated  |  active |
+---------------+--------------+---------+
Packet path: dev instance to shared and to prod
  1. Dev instance sends to 10.24.0.5
  2. VPC route 10.0.0.0/8 -> TGW
  3. TGW looks up dev-rt (association)
  4. Match 10.24.0.0/19 (propagated)?

Destination in shared VPC

Forwarded via shared attachment

Destination in prod VPC

No route in dev-rt: dropped

Sharing across accounts and peering across Regions

A TGW lives in one account and one Region. To let workload accounts attach their own VPCs, share it with AWS RAM, ideally to the whole organization. With AutoAcceptSharedAttachments enabled, attachments from member accounts become active without a manual accept, but they still have no association or propagation, so the network account keeps control of who can reach what.

To connect Regions, create a peering attachment between two TGWs. The traffic stays on the AWS backbone and is encrypted, but peering attachments do not propagate routes dynamically, so you add static routes for the remote Region's supernet on each side. This is another reason to give each Region one clean summary block.

share-and-peer.sh
# Share the TGW with every account in the organization
aws ram create-resource-share --name core-tgw \
  --resource-arns arn:aws:ec2:us-east-1:111122223333:transit-gateway/$TGW_ID \
  --principals arn:aws:organizations::111122223333:organization/o-a1b2c3d4e5 \
  --no-allow-external-principals

# Peer with the hub in eu-west-1 (same account here; can be cross-account)
PEER_ATT=$(aws ec2 create-transit-gateway-peering-attachment \
  --transit-gateway-id $TGW_ID \
  --peer-transit-gateway-id tgw-0f1e2d3c4b5a69788 \
  --peer-account-id 111122223333 --peer-region eu-west-1 \
  --query 'TransitGatewayPeeringAttachment.TransitGatewayAttachmentId' \
  --output text)

# The peer side accepts in its own Region
aws ec2 accept-transit-gateway-peering-attachment --region eu-west-1 \
  --transit-gateway-attachment-id $PEER_ATT

# Peering attachments need static routes: send Europe's /12 across
aws ec2 create-transit-gateway-route \
  --transit-gateway-route-table-id $RT_SHR \
  --destination-cidr-block 10.32.0.0/12 \
  --transit-gateway-attachment-id $PEER_ATT

The same hub as code

CDK has no high-level Transit Gateway construct, so production stacks use the L1 Cfn classes directly. The shape is identical to the CLI version: a TGW with defaults off, an attachment on the dedicated subnets, a route table with an association and a propagation, and VPC routes that depend on the attachment existing first.

tgw-hub.ts
import { App, Stack } from "aws-cdk-lib";
import * as ec2 from "aws-cdk-lib/aws-ec2";

const app = new App();
const stack = new Stack(app, "TgwHubStack");

const tgw = new ec2.CfnTransitGateway(stack, "Tgw", {
  description: "core hub",
  amazonSideAsn: 64512,
  autoAcceptSharedAttachments: "enable",
  defaultRouteTableAssociation: "disable",
  defaultRouteTablePropagation: "disable",
});

const vpc = new ec2.Vpc(stack, "ProdVpc", {
  ipAddresses: ec2.IpAddresses.cidr("10.16.0.0/19"),
  maxAzs: 2,
  natGateways: 0,
  subnetConfiguration: [
    { name: "app", subnetType: ec2.SubnetType.PRIVATE_ISOLATED, cidrMask: 22 },
    { name: "tgw", subnetType: ec2.SubnetType.PRIVATE_ISOLATED, cidrMask: 28 },
  ],
});

const attachment = new ec2.CfnTransitGatewayVpcAttachment(stack, "ProdAttach", {
  transitGatewayId: tgw.ref,
  vpcId: vpc.vpcId,
  subnetIds: vpc.selectSubnets({ subnetGroupName: "tgw" }).subnetIds,
});

const prodRt = new ec2.CfnTransitGatewayRouteTable(stack, "ProdRt", {
  transitGatewayId: tgw.ref,
});
new ec2.CfnTransitGatewayRouteTableAssociation(stack, "ProdAssoc", {
  transitGatewayAttachmentId: attachment.ref,
  transitGatewayRouteTableId: prodRt.ref,
});
new ec2.CfnTransitGatewayRouteTablePropagation(stack, "ProdProp", {
  transitGatewayAttachmentId: attachment.ref,
  transitGatewayRouteTableId: prodRt.ref,
});

// VPC side: app subnets send the rest of 10.0.0.0/8 to the hub
vpc.selectSubnets({ subnetGroupName: "app" }).subnets.forEach((subnet, i) => {
  const route = new ec2.CfnRoute(stack, "AppToTgw" + i, {
    routeTableId: subnet.routeTable.routeTableId,
    destinationCidrBlock: "10.0.0.0/8",
    transitGatewayId: tgw.ref,
  });
  route.addDependency(attachment); // the TGW must be attached first
});

app.synth();

In production

In production

Most organizations run one TGW per Region in a dedicated network account, shared through RAM. New accounts come out of account vending with a VPC already attached; an automation (often an EventBridge rule plus a Lambda function reading a tag such as env=prod) associates the attachment with the right route table and enables the right propagations. Humans rarely touch TGW route tables by hand.

Two patterns appear almost everywhere. Centralized egress puts NAT Gateways in one egress VPC, and spoke route tables get a static 0.0.0.0/0 route to that attachment, so you run a few NAT Gateways instead of dozens. Centralized inspection sends traffic through an inspection VPC running AWS Network Firewall; that attachment needs appliance mode enabled so both directions of a flow use the same AZ and the stateful firewall sees the whole conversation.

The cost model shapes these designs: you pay per attachment-hour and per GB sent into the TGW. Two VPCs that exchange tens of terabytes of replication traffic are often connected with a direct peering connection alongside the TGW, because peering has no hourly charge and no data processing fee. For many Regions and complex policies, teams evaluate AWS Cloud WAN, which builds on the same ideas with a global policy document.

Common mistakes

Common mistakes

Mistake 1: leaving the default route table on

The defaults associate and propagate every attachment into one table, so the moment a dev VPC attaches it can reach production databases. Teams discover this during an audit, not during setup. Create the TGW with both defaults disabled, or at least move every attachment out of the default table before it carries traffic.

Mistake 2: routing only one direction

A ping from dev to shared times out even though dev-rt has the shared route. The usual cause is the return path: shared-rt has no propagation from the dev attachment, or the shared VPC's route table has no route back to the TGW. Always check four places: both VPC route tables and both TGW route tables.

Mistake 3: attachment subnets missing an AZ

If the attachment only has subnets in two AZs, instances in the third AZ cannot use the hub at all, which looks like a random, partial outage. Add an attachment subnet in every AZ the VPC uses.

Best practices

Best practices

  • Own the TGW in a network account, share it with RAM, and automate association and propagation from tags.
  • Use dedicated /28 attachment subnets in every AZ, with their own route table.
  • Point VPC routes at the TGW using supernets and let TGW route tables do the filtering.
  • Add blackhole routes for ranges that must never be reachable, so a mistaken propagation cannot open them.

💰 Cost & Cleanup

A Transit Gateway is billed per attachment per hour (each VPC, VPN or peering attachment) plus per GB of data sent into it, so the three attachments in this lab cost money every hour they exist even with no traffic. RAM sharing itself is free. Inter-Region peering also adds inter-Region data transfer. There is no free tier for Transit Gateway, so delete attachments, route tables and the TGW right after the lab; check the Transit Gateway pricing page for current rates.

Clean up when you are done

bash
# VPC-side routes first, then attachments, route tables and the TGW
aws ec2 delete-route --route-table-id rtb-0a1b2c3d4e5f6c001 \
  --destination-cidr-block 10.0.0.0/8
for ATT in $PROD_ATT $DEV_ATT $SHR_ATT; do
  aws ec2 delete-transit-gateway-vpc-attachment \
    --transit-gateway-attachment-id $ATT
done
# ...wait until the attachments are "deleted", then:
for RT in $RT_PROD $RT_DEV $RT_SHR; do
  aws ec2 delete-transit-gateway-route-table \
    --transit-gateway-route-table-id $RT
done
aws ec2 delete-transit-gateway --transit-gateway-id $TGW_ID

Mini challenge

Mini challenge: centralized egress

Add an egress VPC (10.28.0.0/22, with NAT Gateways) to the hub so that prod and dev reach the internet through it, without letting prod and dev reach each other.

  • Attach the egress VPC and associate it with a new egress-rt
  • Add a static 0.0.0.0/0 route to the egress attachment in prod-rt and dev-rt
  • Propagate prod and dev into egress-rt so return traffic finds its way back

Expected: search-transit-gateway-routes on dev-rt shows 10.20.0.0/19 and 10.24.0.0/19 as propagated plus 0.0.0.0/0 as static, and still nothing for 10.16.0.0/19.

Show hint

Egress-rt learns prod and dev but prod-rt and dev-rt only get a default route to egress, not each other's CIDRs. Inside the egress VPC, the NAT subnets also need routes for 10.0.0.0/8 back to the TGW.

Show solution
bash
EGR_ATT=$(aws ec2 create-transit-gateway-vpc-attachment \
  --transit-gateway-id $TGW_ID --vpc-id vpc-0a1b2c3d4e5f60004 \
  --subnet-ids subnet-0a1b2c3d4e5f6a004 subnet-0a1b2c3d4e5f6b004 \
  --query 'TransitGatewayVpcAttachment.TransitGatewayAttachmentId' --output text)
RT_EGR=$(aws ec2 create-transit-gateway-route-table --transit-gateway-id $TGW_ID \
  --query 'TransitGatewayRouteTable.TransitGatewayRouteTableId' --output text)
aws ec2 associate-transit-gateway-route-table \
  --transit-gateway-route-table-id $RT_EGR --transit-gateway-attachment-id $EGR_ATT

# Spokes: default route to egress (static, because nothing propagates 0/0)
for RT in $RT_PROD $RT_DEV; do
  aws ec2 create-transit-gateway-route --transit-gateway-route-table-id $RT \
    --destination-cidr-block 0.0.0.0/0 --transit-gateway-attachment-id $EGR_ATT
done

# Return path: egress-rt learns prod and dev
for ATT in $PROD_ATT $DEV_ATT; do
  aws ec2 enable-transit-gateway-route-table-propagation \
    --transit-gateway-route-table-id $RT_EGR --transit-gateway-attachment-id $ATT
done

Quick quiz 1 / 3

VPC A peers with VPC B, and VPC B peers with VPC C. Can an instance in A reach C through B?

Quick quiz 2 / 3

The dev attachment is associated with dev-rt, and the prod attachment propagates only into prod-rt and shared-rt. The dev VPC route table sends 10.0.0.0/8 to the TGW. Can dev reach prod?

Quick quiz 3 / 3

Two VPCs in the same Region exchange about 50 TB per month of database replication and need no other connectivity. Which is usually the best fit?

What to remember

  • Full-mesh peering grows as n(n-1)/2 and is non-transitive; a Transit Gateway grows by one attachment per network.
  • Traffic needs a VPC route to the TGW and a TGW route to the destination attachment.
  • Association picks the table for incoming traffic; propagation decides who learns a network's routes.
  • Disable the default route table to keep prod, dev and shared segmented.
  • Share with RAM, peer Regions with static routes, and keep peering for simple high-volume pairs.

What is AWS Transit Gateway? — AWS Documentation

Transit gateway route tables — AWS Documentation

AWS Transit Gateway pricing — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Transit Gateway: Hub-and-Spoke Routing and Segmentation | Thuta Learning