Chapters

How routing works (in depth)

Chapter 5 stopped at "the gateway passes it on". This chapter follows one packet from the Kadé office to kade-api through every router on the way, and shows each decision and every field that changes.

Layers, routing and transport · chapter 12 of 34 · 12 min read

What routing is

Routing is moving a packet across several networks toward its destination. No single router knows the whole path. Each one makes one decision: given this destination IP, what is the best next hop? Then it forgets about the packet.

The path we follow

The front desk PC in the Kadé office loads an order from kade-api. The office uses an ISP called LankaNet (made up for this course). LankaNet connects straight to Google in Singapore, and also buys general internet access from a transit provider, a bigger network that carries traffic to everywhere else.

Kadé officeLankaNet (ISP) · AS 64500Google · AS 15169Front desk PC172.16.1.10gw 172.16.1.1R1 · officeeth1 172.16.1.1eth0 198.51.100.20does NATR2 · ISP edgege0 198.51.100.1ge1 10.200.0.1R3 · ISP borderge0 10.200.0.2ge1 192.0.2.1ge2 192.0.2.5R4 · Google edge192.0.2.2Singaporekade-api34.87.120.15(10.10.1.10)172.16.1.0/24198.51.100.0/2410.200.0.0/30192.0.2.0/30Google's networkTransit provider192.0.2.6 · link 192.0.2.4/30

Each link between two routers is its own tiny network (a /30 has room for exactly 2 devices). Router interfaces are named like ge0, ge1 (gigabit Ethernet). Addresses are documentation or private ranges; the AS numbers are explained in section 10.

Wide by design - scroll it sideways.

The routing table

Every router keeps a routing table: a list of destination networks mapped to a next hop and an outgoing interface. You met small ones in chapters 5 and 6. Here is R1's:

DestinationNext hopInterfaceSource of the route
172.16.1.0/24directeth1connected (eth1 is on this network)
172.16.2.0/24directeth2connected
198.51.100.0/24directeth0connected
0.0.0.0/0198.51.100.1eth0static (typed in by whoever set up the router)
  • Destination: a network in CIDR form (chapter 3).
  • Next hop: the IP of the next router, or "direct" when the destination is on a network this router is connected to.
  • Interface: which port to send it out of.

For every packet, the router: (1) reads the destination IP, (2) finds every row it matches, (3) picks the most specific one (section 7), (4) runs ARP for the next hop (or for the target itself if "direct"), (5) builds a new frame and sends it out that interface.

Hop by hop

Step through the trip. At each stop you see that router's table (the row it chose is marked), its decision, and the packet as it leaves:

1 · Front desk PC · looks up 34.87.120.15

DestinationNext hopIfaceNote
172.16.1.0/24directen0connected
0.0.0.0/0172.16.1.1en0default gateway ← chosen

34.87.120.15 is not in 172.16.1.0/24. Only the default route matches, so send to 172.16.1.1. ARP gives R1 eth1's MAC.

frame · source MAC
3c:7c:3f:10:22:01 (PC)
frame · destination MAC
e4:8d:8c:00:01:01 (R1 eth1)
IP · source (with port)
172.16.1.10:52814
IP · destination (with port)
34.87.120.15:443
IP · TTL
64

What changes, and what does not

#FieldPC → R1R1 → R2R2 → R3R3 → R4R4 → kade-api
1Destination IP34.87.120.15samesamesame10.10.1.10 GCP's 1:1 NAT
2Source IP172.16.1.10198.51.100.20 R1's NATsamesamesame
3TTL6463626160
4IP header checksum-recalculatedrecalculatedrecalculatedrecalculated
5MAC addressesPC → R1R1 → R2R2 → R3R3 → R4R4 side → kade-api
6TCP ports, HTTP data52814 → 44340001 → 443 R1's NATsamesamesame
Bold = changed at that hop. Every router lowers the TTL, and since TTL is part of the IP header, the header checksum must be recalculated at every hop too. Inside Google's network there are more routers; the table skips them.

TTL: the loop safety valve

Routers make mistakes. Say LankaNet mistypes a route: R2 sends 203.0.113.99 to R3, and R3 sends it back to R2. Without a limit, a packet for that address would bounce forever, and millions of them would fill the links.

SenderTTL starts at 64R2"203.0.113.99 → R3"R3"203.0.113.99 → R2"TTL 63, 61, 59 …TTL 62, 60, 58 …at TTL 0:packet dropped,ICMP "Time Exceeded"sent to the sender

Wide by design - scroll it sideways.

So the IP header carries a TTL (Time To Live), a number that each router lowers by one. At 0 the router drops the packet and tells the sender with an ICMP message. Common starting values: 64 (Linux, macOS), 128 (Windows), 255 (many routers). Chapter 13 turns this safety valve into a tool: traceroute.

Longest prefix match

A destination can match several rows. R3, LankaNet's border router, has these routes (among others):

DestinationNext hopInterfaceLearned from
0.0.0.0/0192.0.2.6ge2transit provider: "send me anything"
34.0.0.0/8192.0.2.6ge2transit provider: "I can reach 34.x"
34.87.0.0/16192.0.2.2ge1Google directly: "34.87.x is mine"

34.87.120.15 matches all three. The router always picks the most specific match: the one with the longest prefix, meaning the most network bits that agree. Bit by bit:

destination
34.87.120.15
34.87.120.15
0.0.0.0/0match · /0
34.0.0.0/8match · /8
34.87.0.0/16match · /16 · wins
198.51.100.0/24no match (bit 1 differs)

Only the first /N bits of each route are compared (the rest are shown as dots). Green = same as the destination, highlighted = different. /0 compares nothing, so it always matches. Among the matches, the one comparing the most bits wins.

The /16 wins, so the packet goes straight to Google over the direct link, not the long way through the transit provider. This is good for LankaNet too: direct links with Google are usually cheaper and faster than paid transit.

Try other destinations against R3's full table:

R3’s tableNext hopIfaceNote
10.200.0.0/30directge0connected
198.51.100.0/2410.200.0.1ge0OSPF: customers behind R2
192.0.2.0/30directge1connected: link to Google
192.0.2.4/30directge2connected: link to transit
34.87.0.0/16192.0.2.2ge1BGP from Google ← chosen
34.0.0.0/8192.0.2.6ge2BGP from transit · matches
0.0.0.0/0192.0.2.6ge2BGP from transit · matches

34.87.120.15 → 34.87.0.0/16 (BGP from Google) → next hop 192.0.2.2 out ge1

When two routes have the same length

Longest prefix match comes first. Only if two matching routes have the same prefix length does the router need a tie-breaker:

1 · Trust in the sourceRoutes learned in different ways get a trust score (Cisco calls it administrative distance; lower wins). Typical values: connected 0, static 1, BGP from another network 20, OSPF 110, RIP 120.
2 · MetricAmong routes from the same protocol, the one with the lower cost wins (fewer hops for RIP, faster links for OSPF).
3 · Still equal: ECMPEqual-Cost Multi-Path: the router uses all of them and spreads traffic. It keeps each connection on one path, so packets are not reordered.
GCP uses a simpler version: each VPC route has a priority number, and among routes of the same length the lowest number wins. Equal priorities are spread with ECMP.

The default route

What if nothing matches? Routers use a default route, 0.0.0.0/0: "when in doubt, send it here". It matches every address with 0 bits, so it always loses to anything more specific. It is the last resort, not the first choice.

Front desk PC0.0.0.0/0 → 172.16.1.1 its default gateway (chapter 5)
R1 office0.0.0.0/0 → 198.51.100.1 LankaNet
R2 ISP edge0.0.0.0/0 → 10.200.0.2 R3, deeper in LankaNet
R3 ISP border0.0.0.0/0 → 192.0.2.6 the transit provider
Big backbone routersno default at all they know a route to every network: the "default-free zone"

Static and dynamic routing

Routing tables are filled in two ways:

Static routes

Typed in by hand. Simple and predictable. Fine for small setups like R1's one default route.

Problem: if a link fails, nothing updates itself.

Dynamic routes

Routers tell each other which networks they can reach, using a routing protocol, and update their tables when links fail or return.

#ProtocolUsedHow it choosesIn our path
1RIPSmall, older networksFewest hops (max 15)Not used
2OSPFInside one organisationEvery router learns the full map of links and computes the fastest pathR2 and R3 inside LankaNet
3BGPBetween organisations: the whole internetPolicies and paths between networks, not just speedR3 with Google and the transit provider

The internet is a network of networks. Each organisation that runs its own routing is an autonomous system (AS) with a number: Google is AS 15169. BGP is how they tell each other "these address ranges are reachable through me":

Kadé officeno AS · static defaultLankaNet · AS 64500owns 198.51.100.0/24Google · AS 15169owns 34.87.0.0/16Transit · AS 64510reaches everywhere"34.87.0.0/16 via me""0.0.0.0/0 and 34.0.0.0/8 via me""198.51.100.0/24 via me"

Green: announcements that build R3's table from section 7. Amber: LankaNet's own announcement, which is how Google knows where to send kade-api's replies to 198.51.100.20. Traffic flows the opposite way to announcements. AS 64500 and 64510 are numbers reserved for examples.

Wide by design - scroll it sideways.

Routing in GCP

A VPC has a routing table too, managed by GCP. For kade-vpc today, plus the office VPN that is coming later:

#DestinationNext hopTypePriority
110.10.1.0/24the VPC networksubnet route (automatic)-
210.10.2.0/24the VPC networksubnet route (automatic)-
30.0.0.0/0default-internet-gatewaystatic (created with the VPC)1000
4172.16.0.0/16 laterVPN tunnel to the officedynamic: learned by Cloud Router over BGPset by BGP
Same rules as everywhere else: longest prefix first, then lowest priority number. Cloud Router is GCP's BGP speaker: it learns the office's 172.16.0.0/16 over the VPN and tells the office about 10.10.0.0/16. The same Cloud Router hosts Cloud NAT (chapter 10).

Other routing ideas you will hear

Asymmetric routingThe reply may take a different path from the request. Each router decides on its own, and kade-api's reply is routed by Google's and LankaNet's tables, not by the original path. Keep this in mind when reading traceroute (chapter 13).
Route summarizationAnnouncing one bigger range instead of many small ones. The office could announce 172.16.0.0/16 instead of 172.16.1.0/24 and 172.16.2.0/24. Smaller tables, fewer updates.
Blackhole (null) routeA route whose next hop is "drop it". Used to throw away attack traffic, or to stop a summary route from looping.
Routing table vs forwarding tableProtocols build the routing table (all known routes). The router copies only the winners into a fast forwarding table used for each packet.

The full IPv4 header

This chapter used many IP header fields one at a time: TTL, protocol, the checksum. Here is the whole header, laid out like UDP's (chapter 15) and TCP's (chapter 18). It is 20 bytes without options, which is what almost every packet uses:

bit →08162431bytes 0-3Ver4IHL4DSCP6ECN2Total length16bytes 4-7Identification16Flags3Fragment offset13bytes 8-11TTL8Protocol8Header checksum16bytes 12-15Source address32 bitsbytes 16-19Destination address32 bits20-59Options (rare)0 to 40 bytesthenData: a TCP segment, UDP datagram or ICMP message

Five rows = 20 bytes, like TCP’s fixed part. Everything a router needs is here; the data behind it is someone else’s business (chapter 11).

And the real bytes: the IP header around the SYN from chapter 18, as it leaves the laptop toward kade-api:

000045ver + IHL00DSCP/ECN00length3c3cID1a40flags/offset0040TTL06protocola2checksum7cc0sourcea80117
001622destination57780f

Byte 0 = 45: version 4 in the top half, IHL 5 in the bottom half. Bytes 6-7 = 40 00: the DF bit is on, offset 0. The checksum a2 7c was computed for real; re-adding all ten 16-bit words gives 0xFFFF.

#FieldSizeIn this packetJob, and where you met it
1Version4 bits4IPv4. (IPv6 packets start with 6.)
2IHL (header length)4 bits5 → 5 × 4 = 20 bytesWhere the header ends, like TCP's data offset
3DSCP6 bits0Priority class. Networks can use it to put voice calls ahead of backups (QoS).
4ECN2 bits0Congestion marks (chapter 20). 0 = not ECN-capable.
5Total length16 bits00 3c = 60Header + everything inside: 20 IP + 40 TCP
6Identification16 bits3c 1aMatches fragments of one packet (chapter 18)
7Flags3 bits010 = DFDF and MF (chapter 18). TCP always sets DF.
8Fragment offset13 bits0Where a fragment's data starts, in 8-byte units
9TTL8 bits40 = 64Lowered at every router (section 6)
10Protocol8 bits06 = TCPWhat is inside: 1 ICMP, 6 TCP, 17 UDP (chapter 13)
11Header checksum16 bitsa2 7cCovers the IP header only. After R1 lowers TTL to 63 and NATs the source, it becomes 3a f4.
12Source address32 bitsc0 a8 01 17192.168.1.23 (chapter 2)
13Destination address32 bits22 57 78 0f34.87.120.15, the only field routers look up
14Options0-40 bytesnoneRarely used; many routers treat packets with options as suspicious

Where latency comes from

Three words get mixed up all the time:

WordMeaningHome → kade-api
LatencyHow long one piece of data takes to get there. Usually quoted as round-trip time (RTT).41 ms RTT
BandwidthThe most a link can carry per second. A property of the link.100 Mbit/s (your plan)
ThroughputWhat you actually get per second, after windows, loss and sharing (chapters 19-20).anything up to 100 Mbit/s
A faster plan raises bandwidth. It does not lower latency to Singapore at all.

Every packet's delay is the sum of four parts, at every hop:

#DelayCaused bySize on our pathCan you reduce it?
1PropagationDistance. Light in fibre covers about 200 km per millisecond.~35 ms of the 41 (Colombo ⇄ Singapore)Only by moving closer: a nearer region, a CDN, anycast (section 15)
2TransmissionPushing the bits onto the link: packet size ÷ link speed1,500 bytes at 100 Mbit/s = 0.12 msFaster links; matters on slow links
3QueuingWaiting behind other packets in router queues0 to hundreds of ms (bufferbloat, chapter 20)Better queues, less congestion
4ProcessingRouters reading headers; the server doing its workmicroseconds per router; kade-api's own time on topFaster code (for the server part)

the 41 ms ping from home to kade-api, roughly split

propagation · ~35 msqueue ~3proc
Most of the delay is simply distance. The last sliver is transmission across all the hops. An HTTP request adds kade-api's own processing time on top of this.

Try the physics yourself:

One-way, light in fibre
3300 ÷ 200 km/ms = 16.5 ms
Best possible RTT
33.0 ms before any queues or processing
Transmission of one packet
1,500 × 8 bits ÷ 100 Mbit/s = 0.12 ms per link

Cable routes are longer than straight lines: Colombo to Singapore is about 2,700 km direct but more by cable, which fits the ~35 ms part of the 41 ms ping.

Anycast: one IP, many places

Normally one IP address belongs to one machine in one place: unicast. With anycast, the same address range is announced over BGP (section 10) from many locations at once. Every router simply follows its best route, so each user reaches the nearest location without knowing others exist.

#KindOne sender reachesExample
1Unicastone specific hostkade-api today at 34.87.120.15
2Broadcastevery host on the local networkARP requests, DHCP Discover
3Multicastevery host that joined a groupLive video inside a company network
4Anycastthe nearest of many hosts sharing one IP1.1.1.1, 8.8.8.8, Cloudflare, Google's global load balancers
Shopper in Colombo→ 34.120.7.9Shopper in London→ 34.120.7.9 (same IP)Google edgenear Colombo · announces itGoogle edgeLondon · announces it tooshort hopshort hopGoogle's private backbonekade-apiSingapore

Later in the course, api.kade.lk moves to a GCP global external load balancer, which gets one anycast IP (34.120.7.9 here is an example). TCP and TLS then end at the nearest Google edge, so the handshakes (chapter 16) happen over a short distance, and the long part of the trip runs over Google's own network.

Wide by design - scroll it sideways.

  • Failover for free: if one location stops announcing the route, BGP sends users to the next-nearest one.
  • Spreads attacks: a DDoS aimed at one IP lands on many locations at once.
  • Works for TCP because internet routes rarely change in the middle of a connection. It was first used for DNS (short UDP exchanges), and still is.

Summary

#IdeaIn one lineNew terms
1RoutingOne decision per router: best next hop for this destination IProuting, next hop
3TableDestination (CIDR) → next hop + interfaceconnected, static route
5ChangesIP stays (except NAT); MAC, TTL, checksum change every hop
6TTLLowered by 1 per router; at 0 dropped + ICMP messageTTL, routing loop
7Longest prefixMost specific match winslongest prefix match
8TiesTrust (admin distance), then metric, then ECMPadministrative distance, metric, ECMP
9Default0.0.0.0/0, the last resortdefault-free zone
10Filling tablesStatic by hand; dynamic via RIP, OSPF, BGPOSPF, BGP, AS, transit, peering
11GCPSubnet, static and dynamic routes; priority; Cloud Router for BGPCloud Router
13IPv4 header20 bytes: version, length, ID/flags/offset, TTL, protocol, checksum, addressesIHL, DSCP
14LatencyPropagation + transmission + queuing + processing; distance dominateslatency, bandwidth, throughput
15AnycastOne IP announced from many places; BGP picks the nearestunicast, anycast

Try it yourself

Your routing table

  • What to look for: Connected route for your LAN, and the default route.
  • Runs on: Linux · macOS: netstat -rn -f inet · Windows: route print -4
  • From section: 3. The routing table
ip route

Which row wins for one destination

  • What to look for: The chosen next hop and interface.
  • Runs on: Linux · macOS: route -n get 34.87.120.15
  • From section: 7. Longest prefix match
ip route get 34.87.120.15

The reply's TTL

ping -c 1 1.1.1.1

Who announces an IP range

whois -h whois.radb.net 8.8.8.8

A VPC's routes

  • What to look for: Destination range, next hop, priority.
  • From section: 11. Routing in GCP
gcloud compute routes list --filter="network:kade-vpc"

One packet's IP header decoded

  • What to look for: tos 0x0, ttl 64, id …, flags [DF], proto TCP (6), length …
  • From section: 13. The full IPv4 header
sudo tcpdump -n -v -c 1 -i en0 tcp

Anycast in action

  • Steps: traceroute 1.1.1.1, and ask a friend abroad to run it too
  • What to look for: Same destination, different last hops and much shorter RTTs than the distance to any one "home" of 1.1.1.1.
  • From section: 15. Anycast: one IP, many places
traceroute 1.1.1.1

Routes a Cloud Router learned over BGP

  • What to look for: The bestRoutes list, once the VPN exists.
  • From section: 11. Routing in GCP
gcloud compute routers get-status ROUTER --region=REGION

Spotted a mistake, or something unclear? Suggest an edit on GitHub