BGP Fundamentals: Peering Sessions, Prefix Propagation, and Path Selection
Easy · Software Engineering Fundamentals · Software Engineer · Onsite
Prompt
Walk through how the Border Gateway Protocol (BGP) operates in modern IP networks. Explain the core routing challenge BGP is designed to solve, the lifecycle two BGP speakers follow to bring up a peering session and propagate route updates, the decision process a router uses when several candidate paths advertise the same prefix (such as 198.51.100.0/24), and how BGP differs architecturally from link-state interior protocols like OSPF.
Before diving deep, mention the scope choices worth clarifying with an interviewer—specifically whether to cover only inter-domain internet peering (eBGP) or also intra-domain backbone and leaf-spine data-center deployments (iBGP and private-ASN eBGP), and whether route selection should focus on the main policy attributes or trace the entire tie-breaking sequence.
Scope & Expectations
- Explain why independently administered networks require a policy-driven path-vector protocol rather than a single shared-metric shortest-path graph.
- Trace the BGP peering state machine over TCP and describe how incremental advertisements and withdrawals move through BGP routing tables.
- Detail the principal path attributes and ordered tie-breaking rules that select one winning route for an identical prefix.
- Contrast BGP with interior protocols like OSPF across administrative scope, topology visibility, transport mechanism, scale, and convergence speed.
Step-by-step walkthrough
Why BGP exists: routing between independent networks
The global internet is a patchwork of tens of thousands of Autonomous Systems (ASes) — independently operated networks (such as ISPs, cloud providers, universities, and large enterprises), each managed under its own routing policy and identified by a unique ASN (Autonomous System Number, originally 16-bit
0–65535and expanded to 32-bit in RFC 6793).Each AS owns one or more IP prefixes (contiguous blocks of IP addresses written in CIDR notation, such as
198.51.100.0/24) and needs to advertise how to reach them. Interior protocols like OSPF cannot run the whole internet for three reasons:- Business policy beats physical distance: no single cost metric exists across organizations. An ISP prefers sending traffic through a paying customer rather than a transit provider it pays, even if the customer path crosses more networks.
- Topology privacy: organizations will not broadcast their internal router-and-link diagrams to competitors.
- Scale and stability: the global IPv4 routing table holds roughly one million prefixes; flooding every link state across the planet would melt router CPUs whenever a link flapped.
BGP-4 (Border Gateway Protocol version 4, RFC 4271) solves this as a path-vector protocol — a routing protocol where each advertised prefix carries the ordered list of AS numbers (
AS_PATH) it has crossed so far, plus policy attributes. Loop prevention comes free fromAS_PATH: if a router sees its own ASN already inside an incoming route'sAS_PATH, it immediately drops that route.BGP peering lifecycle and finite state machine
Unlike OSPF, classic BGP routers do not auto-discover neighbors with broadcast hellos; an engineer explicitly configures each peer's IP address and expected ASN on both routers. Bringing up a session walks through a six-state finite state machine:
Idle ---> Connect ---> OpenSent ---> OpenConfirm ---> Established (routes flow!) | ^ v | (TCP connect failed; retry timer running) Active- TCP connection on port 179 (
Idle -> Connect / Active): BGP rides on TCP so packet ordering, fragmentation, and retransmissions are handled by the transport layer. If the TCP handshake fails, the session drops into Active (meaning it is actively retrying TCP, not that the session is healthy!). OPENexchange (OpenSent): once TCP connects, both peers send anOPENmessage containing BGP version (4), local ASN, 32-bit BGP router ID, proposed hold time (maximum seconds a peer waits without receiving any BGP message before declaring the session dead; negotiated to the smaller proposal, either0or>= 3 s, typically90 sor Cisco's180 sdefault), and optional capabilities (IPv6 multiprotocol, 4-byte ASNs, route refresh).KEEPALIVEconfirmation (OpenConfirm -> Established): if theOPENparameters match configuration, each router replies with a19-byteKEEPALIVEmessage (usually sent everyhold_time / 3seconds; operators often add BFD — Bidirectional Forwarding Detection — for sub-second link-failure detection). Receiving thatKEEPALIVEmoves the session to Established.
Sessions come in two flavors: eBGP (external BGP between two different ASes, sent with IP TTL
1by default over a direct link) and iBGP (internal BGP between routers inside the same AS, typically peered between stable loopback addresses).- TCP connection on port 179 (
How BGP exchanges routes and updates its tables
Once Established, peers exchange their current valid routes once and thereafter send only incremental
UPDATEmessages when routes appear, change attributes, or disappear—there is no periodic full-table refresh. EachUPDATEcarries withdrawn prefixes, path attributes, and NLRI (Network Layer Reachability Information — the list of prefixes sharing those attributes; IPv6 prefixes useMP_REACH_NLRIandMP_UNREACH_NLRIfrom RFC 4760).Inside one router, routes pass through three conceptual RIBs (Routing Information Bases — BGP's internal route tables):
Peer UPDATEs ---> [ Adj-RIB-In ] ---> (Import Policy: filter, set LOCAL_PREF) | v [ Loc-RIB ] <-- best path per prefix selected here | Peer UPDATEs <--- [ Adj-RIB-Out ] <-- (Export Policy: filter, prepend AS_PATH, set MED)Crossing an eBGP boundary modifies attributes differently from crossing an iBGP boundary:
Behavior on export AS_PATH NEXT_HOP LOCAL_PREF ---------------------- ------------------------ ------------------------------- --------------------- eBGP (to another AS) Prepend our own ASN Rewrite to our interface IP Stripped (never sent) iBGP (inside same AS) Left unchanged Left unchanged (unless Preserved across AS next-hop-self is configured)Because iBGP leaves
AS_PATHuntouched,AS_PATHcannot stop routing loops inside an AS. Instead, BGP enforces the iBGP split-horizon rule: a route learned from one iBGP peer is never re-advertised to another iBGP peer.Path attributes and the best-path selection order
Operators steer traffic by tuning path attributes on import and export:
LOCAL_PREF(well-known discretionary, local to your AS, default100, higher wins): controls outbound traffic from your entire AS. Setting customer routes to200, settlement-free peer routes to150, and paid transit routes to100enforces economic policy before hop count is ever checked.AS_PATH(well-known mandatory, global, shorter wins): lists traversed ASNs (65101 65200). Operators sometimes repeat their own ASN outbound (AS_PATH prepending) to make a backup link look longer to the rest of the internet.ORIGIN(well-known mandatory,IGP < EGP < INCOMPLETE): minor tie-breaker reflecting how the prefix originally entered BGP.MED(Multi-Exit Discriminator, optional non-transitive, lower wins): a hint sent to one directly connected neighbor AS suggesting which inter-AS link they should use to enter your network (compared by default only among routes arriving from that same neighbor AS).NEXT_HOP(well-known mandatory): IP address of the next router toward the prefix; if the local routing table cannot reachNEXT_HOP, BGP ignores the route completely.COMMUNITY(optional transitive): numeric tags (like65101:100) used to group routes so policies can match them cleanly.
When
Loc-RIBhas multiple valid routes for the exact same prefix (say198.51.100.0/24), BGP walks a strict waterfall of tie-breakers and stops at the first difference (shown in standard Cisco order):Step Rule Why it sits here ---- ------------------------------------------ ----------------------------------------------------- 0. Discard if NEXT_HOP is unreachable Cannot forward packets to an unknown next hop 1. Highest WEIGHT Vendor-local single-router override (never sent) 2. Highest LOCAL_PREF AS-wide business policy for outbound traffic 3. Locally originated route Prefer routes originated by this router itself 4. Shortest AS_PATH Fewer AS hops 5. Lowest ORIGIN code IGP < EGP < INCOMPLETE 6. Lowest MED (same neighbor AS only) Respect neighbor's preferred entry link 7. Prefer eBGP over iBGP Exit our AS directly rather than crossing internally 8. Lowest IGP metric to NEXT_HOP "Hot-potato routing": hand off at the closest border 9. (Optional multipath installation) Load-share if equal up to here and multipath enabled 10. Oldest eBGP route Avoid route-flap churn (RFC 5004) 11. Lowest advertising BGP Router ID Deterministic tie-breaker (or ORIGINATOR_ID) 12. Shortest CLUSTER_LIST length Fewer route-reflector hops 13. Lowest peer IP address Final deterministic tie-breakerTwo rules sit outside BGP's tie-breaker: 1. Longest prefix match always wins during packet forwarding: a route to
198.51.100.0/25beats198.51.100.0/24for destination198.51.100.10, regardless ofLOCAL_PREForAS_PATH. 2. Administrative distance arbitrates when two different routing protocols (say OSPF and BGP) both know the exact same prefix/24(Cisco defaults: eBGP20, OSPF110, iBGP200— lower wins).Worked numeric example and Python simulation
Suppose a border router in
AS 65000receives three candidate routes for198.51.100.0/24:Route Session & Peer AS_PATH LOCAL_PREF ORIGIN MED IGP cost to NEXT_HOP ----- --------------------- ------------------- ---------- ------ --- -------------------- R1 eBGP from 192.0.2.1 65101 65200 100 igp 0 0 R2 eBGP from 203.0.113.1 65102 65103 65200 100 igp 0 0 R3 iBGP from 10.10.0.4 65101 65200 100 igp 0 20- Baseline (
LOCAL_PREF = 100on all three): all tie on Step 2 (LOCAL_PREF = 100). At Step 4 (AS_PATHlength),R1(2) andR3(2) eliminateR2(3). Both tie onORIGIN(igp) andMED(0, both from neighbor65101). At Step 7 (eBGPoveriBGP),R1wins. - Policy override:
AS 65102is a lower-cost provider, so import policy setsLOCAL_PREF = 200onR2. NowR2wins immediately at Step 2, beating the shorterAS_PATHofR1andR3. - Neighbor
MEDhint: revertLOCAL_PREF = 100, and supposeAS 65101advertisesMED = 50onR1andMED = 0onR3. Because both enter from the same neighbor (65101), Step 6 compares theirMEDvalues andR3wins (0 < 50), steering traffic through internal border router10.10.0.4.
Here is the core decision waterfall in Python (using deterministic
MEDgrouping across routes sharing the same first AS):ORIGIN_RANK = {"igp": 0, "egp": 1, "incomplete": 2} def keep_lowest(routes, key_name): """Filter candidate routes down to those tied for the minimum value of key_name.""" best_val = min(route[key_name] for route in routes) return [route for route in routes if route[key_name] == best_val] def remove_worse_med(routes): """Deterministic MED: compare MED only among routes from the same neighboring AS.""" survivors = [] for route in routes: my_neighbor = route["as_path"][0] if route["as_path"] else None beaten = any( (other["as_path"][0] if other["as_path"] else None) == my_neighbor and other["med"] < route["med"] for other in routes ) if not beaten: survivors.append(route) return survivors def select_best_bgp_path(routes): """Return the winning route using core RFC 4271 tie-breakers.""" candidates = [] for route in routes: scored = dict(route) scored["neg_local_pref"] = -route["local_pref"] # Higher LOCAL_PREF wins scored["path_len"] = len(route["as_path"]) scored["origin_rank"] = ORIGIN_RANK[route["origin"]] scored["source_rank"] = 0 if route["ebgp"] else 1 # eBGP (0) beats iBGP (1) candidates.append(scored) for step_key in ["neg_local_pref", "path_len", "origin_rank"]: candidates = keep_lowest(candidates, step_key) candidates = remove_worse_med(candidates) for step_key in ["source_rank", "igp_cost", "router_id"]: candidates = keep_lowest(candidates, step_key) return candidates[0]- Baseline (
How BGP differs from OSPF (and how they work together)
OSPF (Open Shortest Path First) is a link-state IGP (Interior Gateway Protocol — a routing protocol used inside one organization where every router in an area floods its active links into a shared topology map and runs Dijkstra's shortest-path algorithm):
Dimension OSPF (Link-State IGP) BGP (Path-Vector EGP / iBGP) ------------------- ---------------------------------------- -------------------------------------------- Primary scope Inside a single AS (divided into areas) Between ASes (eBGP) & across backbones (iBGP) Optimization goal Lowest cumulative link cost (bandwidth) Policy & business rules first, path length 2nd Topology visibility Every router knows full area link graph Internal topology of other ASes stays hidden Core algorithm Dijkstra shortest-path-first (SPF) Per-prefix attribute tie-breaker waterfall Neighbor discovery Automatic multicast Hellos (224.0.0.5) Explicitly configured peer IPs and ASNs Transport Raw IP protocol 89 TCP port 179 Update style Flooded LSAs + periodic 30-min refresh Incremental UPDATEs only (no periodic dump) Typical scale Hundreds to a few thousand routers ~1,000,000 prefixes on global internet routers Convergence speed Sub-second to a few seconds Seconds to minutes (intentionally dampened)Inside a service provider or enterprise backbone, OSPF and BGP cooperate rather than compete: OSPF learns fast shortest paths between internal router loopbacks and border links, and BGP relies on OSPF both to verify that each external route's
NEXT_HOPis reachable (Step 0) and to measure internal distance to each exit router (Step 8).BGP inside one organization: backbones and data centers
Clarify whether the interviewer also wants internal and data-center BGP designs:
- iBGP across a backbone: redistributing one million internet prefixes into OSPF would overwhelm it, so edge routers keep external routes in iBGP. Because of iBGP split-horizon, a naive full mesh among
nrouters needsn * (n - 1) / 2TCP sessions: forn = 50routers,50 * 49 / 2 = 1,225sessions! Deploying2redundant route reflectors (RFC 4456 — special iBGP routers permitted to re-advertise routes among client peers while trackingORIGINATOR_IDandCLUSTER_LISTto stop loops) drops those50routers (48clients +2reflectors) to48 * 2 + 1 = 97sessions. - eBGP in modern leaf-spine data centers (RFC 7938): hyperscale data centers often skip OSPF entirely and assign a private ASN (
64512–65534or 4-byte4200000000–4294967294) to each rack switch or spine tier, using eBGP equal-cost multipath for predictable failure blast radius and rich policy filtering.
- iBGP across a backbone: redistributing one million internet prefixes into OSPF would overwhelm it, so edge routers keep external routes in iBGP. Because of iBGP split-horizon, a naive full mesh among
Intuition & how it works
Think of an interior protocol like OSPF as campus GPS inside one university: a single administration owns every walkway, every signpost shares a full map of the grounds, and everyone wants the fastest physical walk. BGP (Border Gateway Protocol) is more like international airline alliances between independent countries: airlines refuse to hand competitors their internal crew schedules, and "best" is governed by commercial treaties first—an airline would much rather route passengers onto a partner carrier that pays it than onto a rival carrier it has to pay, even if the partner route adds an extra stop!
Why would a naive shortest-path protocol fail across the global internet? First, the internet is run by tens of thousands of independent Autonomous Systems (ASes) (networks under separate ownership and policy, each identified by an AS number) with conflicting financial incentives: without policy controls, a small company connected to two giant ISPs could accidentally advertise one ISP's routes to the other and get crushed carrying free global transit traffic between them. Second, flooding a link-by-link graph of millions of routers and ~1,000,000 IP prefixes (contiguous blocks of IP addresses like 198.51.100.0/24) would saturate memory and CPU worldwide every time a single cable flapped. Instead, BGP works as a path-vector protocol (each route carries AS_PATH, the list of ASes traversed, preventing loops whenever a router sees its own ASN) over reliable TCP port 179 sessions—both eBGP (external BGP between different ASes) and iBGP (internal BGP within one AS)—evaluating local policy before path length.
Walk through 3 candidate routes to 198.51.100.0/24 arriving at a router in AS 65000:
R1via eBGP (AS_PATH: 65101 -> 65200,LOCAL_PREF: 100)R2via eBGP (AS_PATH: 65102 -> 65103 -> 65200,LOCAL_PREF: 100)R3via iBGP (AS_PATH: 65101 -> 65200,LOCAL_PREF: 100)
- Under equal
LOCAL_PREF = 100, BGP checksAS_PATHlength next:R2(3AS hops) loses toR1andR3(2AS hops), andR1beatsR3because externaleBGPexits are preferred over internaliBGPpaths. - Now suppose
AS 65102is a paying customer or cheaper link, soAS 65000setsLOCAL_PREF = 200onR2: becauseLOCAL_PREFis checked beforeAS_PATHlength,R2wins immediately despite crossing one extra AS!
Key points
- Inter-domain problem: BGP-4 (RFC 4271) exchanges prefix reachability between independent ASes without exposing internal link topologies or forcing a shared cost metric;
AS_PATHprovides built-in loop detection. - Session lifecycle: manually configured peers connect on TCP port 179, exchange
OPENmessages (version4, ASN, negotiated hold time = smaller proposal, router ID, capabilities), confirm withKEEPALIVEs, and reach Established (Idle -> Connect -> Active -> OpenSent -> OpenConfirm -> Established). - Incremental route updates: after one initial table exchange, peers send
UPDATEmessages (withdrawals + path attributes + prefixes) only when routes change—never on a periodic flood timer. - Policy-first best-path waterfall: ignore unreachable
NEXT_HOP-> highest localWEIGHT-> highestLOCAL_PREF(AS-wide outbound policy) -> locally originated -> shortestAS_PATH-> lowestORIGIN-> lowestMED(same neighbor AS) ->eBGPoveriBGP-> lowest IGP cost toNEXT_HOP-> oldesteBGProute / lowest router ID / peer IP. - Forwarding vs BGP selection: longest prefix match (
/25beats/24regardless of BGP attributes) and administrative distance (choosing between protocols for the exact same prefix: Cisco eBGP20, OSPF110, iBGP200) happen outside BGP's tie-breaker. - BGP vs OSPF: OSPF floods link states inside one AS over IP protocol
89and runs Dijkstra for fast sub-second shortest-path convergence; BGP hides topology, scales to ~1,000,000prefixes, enforces policy, and relies on OSPF (or IS-IS) to make internalNEXT_HOPaddresses reachable.
Common mistakes
- Describing BGP as "shortest-path routing":
AS_PATHlength is checked only afterLOCAL_PREF(and vendorWEIGHT), and even then it counts whole organizations traversed, not router hops, link bandwidth, or latency. - Assuming
Activestate means the session is working:Activemeans TCP port179connection attempts are failing and retrying; only Established exchanges routes. - Trying to steer inbound internet traffic with
LOCAL_PREF:LOCAL_PREFis stripped on eBGP export and stays strictly inside your own AS, so it only controls your outbound traffic. - Expecting
MEDto compare across two different ISPs: by default, routers compareMEDonly when two routes enter from the same neighboring AS, and neighbors never forwardMEDto downstream ASes. - Forgetting
NEXT_HOPreachability across iBGP: iBGP preserves the external eBGP peer's IP asNEXT_HOPby default; unlessnext-hop-selfis set at the border or the external subnet is advertised into OSPF, internal routers mark the BGP route inaccessible and refuse to use it. - Confusing longest-prefix routing with BGP tie-breaking: BGP best-path selection only compares multiple paths to the identical prefix (
/24vs/24); packet forwarding always picks/25over/24even if/24hasLOCAL_PREF = 500. - Running eBGP without prefix filters: omitting inbound/outbound prefix lists, max-prefix limits, and RPKI (Resource Public Key Infrastructure — cryptographic certificates proving which ASN is authorized to originate an IP prefix) risks accepting or leaking bogus global routes.
Follow-up questions
- When a BGP neighbor remains stuck in the Active state, how do you diagnose the root cause?
Activeindicates that the speaker is attempting TCP port179handshakes that fail beforeOPENmessages can be exchanged, so begin at Layers 3 and 4: confirm bidirectional IP routing from the exact configured source address (ping <peer> source <loopback>whenupdate-sourceis configured) and ensure no ACL or firewall drops TCP179in either direction. Next verify symmetric BGP transport configuration on both routers: the remote router'sneighborstatement must match your outgoing source IP, loopback-to-loopback eBGP requiresebgp-multihop(default eBGP IP TTL is1), and any TCP MD5 authentication secret must match byte-for-byte (a mismatched MD5 digest silently drops TCP segments inActive, whereas a mismatchedremote-ascompletes TCP, sendsOPEN, and tears down with aNOTIFICATION). Checkshow ip bgp neighbors, syslog errors, and atcpdumpcapture on TCP port179to see whetherSYNpackets go unanswered, receiveRST, or fail MD5 validation. - What protocol rule forces iBGP routers into either a full peering mesh or a route-reflector hierarchy? Because iBGP exports leave
AS_PATHunchanged,AS_PATHloop detection cannot catch routing loops inside an AS; BGP prevents intra-AS loops via the iBGP split-horizon rule, which forbids an iBGP router from re-advertising a route learned from one iBGP peer to any other iBGP peer. Without transitive internal forwarding, every internal router must peer directly with every other iBGP router—a full mesh ofn * (n - 1) / 2TCP sessions (1,225sessions across50routers). Route reflectors (RFC 4456) safely lift split-horizon on designated hub routers that reflect client routes while attachingORIGINATOR_IDandCLUSTER_LISTattributes to block loops, cutting50routers (48clients +2redundant reflectors) down to97sessions—at the cost of hiding non-best alternate paths unlessADD-PATH(RFC 7911) is enabled. - Suppose an enterprise multihomes to two transit ISPs. Which mechanisms steer egress traffic toward a primary ISP, and which levers nudge ingress traffic onto a preferred link? Egress traffic is directly governed inside your own AS: apply an import policy on the primary ISP session assigning a higher
LOCAL_PREF(say200vs default100on the secondary ISP), which propagates via iBGP so every internal router exits toward the primary ISP. Ingress traffic is selected by remote ASes across the internet, so you can only influence—not dictate—their choice: use AS_PATH prepending (repeating your ASN such as65000 65000 65000outbound toward the secondary ISP so the primary path has a shorterAS_PATH), attach provider-supported BGP communities instructing the secondary ISP to lower its internalLOCAL_PREFon your prefixes, or advertise more-specific sub-prefixes (e.g., two/24blocks) on the primary ISP while advertising the covering/23aggregate on both ISPs for automatic failover (remembering that IPv4 prefixes longer than/24or IPv6 prefixes longer than/48are filtered globally). Only longest-prefix match overrides a remote ISP's ownLOCAL_PREFpolicy. - How would you design an automated lab test suite to validate a router's BGP daemon? Pair the router under test in an isolated virtual or hardware lab topology against scriptable BGP speakers (such as ExaBGP, GoBGP, FRR, or BIRD) that inject deterministic packets and assert both internal RIB/FIB state and emitted
UPDATEmessages. Structure tests into four tiers: (1) FSM and negative protocol tests covering capability negotiation, hold-timer expiration, bad ASN/MD5 credentials, graceful restart, and malformedUPDATEfuzzing verifying RFC 7606 "treat-as-withdraw" handling without daemon crashes; (2) deterministic tie-breaker unit tests feeding route pairs that isolate each step of the best-path waterfall alongside import/export route-map filters; (3) scale and churn benchmarks injecting ~1,000,000prefixes and link flaps while tracking convergence time, CPU load, and memory growth; and (4) multi-vendor interoperability runs.
Follow-up questions
- When a BGP neighbor remains stuck in the Active state, how do you diagnose the root cause?
- What protocol rule forces iBGP routers into either a full peering mesh or a route-reflector hierarchy?
- Suppose an enterprise multihomes to two transit ISPs. Which mechanisms steer egress traffic toward a primary ISP, and which levers nudge ingress traffic onto a preferred link?
- How would you design an automated lab test suite to validate a router's BGP daemon?
Similar questions
- ICMP Ping Success vs. Port 443 Reachability
- In-Memory Task Tracker with CRUD Operations
- Core Mechanics of pytest Fixtures, Function Wrappers, and Lazy Generators
- Method Resolution Order in Python Multiple Inheritance
- Memory Layout and Arithmetic of C Pointer vs. Array Declarations
- Designing a Feature Test Strategy and Taming Intermittent CI Failures
More Cisco interview questions
- Leading a Testing and Release Process Upgrade Easy
- ICMP Ping Success vs. Port 443 Reachability Easy
- Modeling and Proving Optimality in a Horses-and-Ladders Crossing Puzzle Hard Pro
- In-Memory Task Tracker with CRUD Operations Easy Pro
- Leftmost Longest Repeat-Free Substring Easy Pro
- Method Resolution Order in Python Multiple Inheritance Easy Pro
- Core Mechanics of pytest Fixtures, Function Wrappers, and Lazy Generators Easy Pro
- Memory Layout and Arithmetic of C Pointer vs. Array Declarations Easy Pro
- Designing a Feature Test Strategy and Taming Intermittent CI Failures Easy Pro
- Constant-Time LFU Cache Hard Pro