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

  1. 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–65535 and 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:

    1. 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.
    2. Topology privacy: organizations will not broadcast their internal router-and-link diagrams to competitors.
    3. 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 from AS_PATH: if a router sees its own ASN already inside an incoming route's AS_PATH, it immediately drops that route.

  2. 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
    
    1. 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!).
    2. OPEN exchange (OpenSent): once TCP connects, both peers send an OPEN message 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, either 0 or >= 3 s, typically 90 s or Cisco's 180 s default), and optional capabilities (IPv6 multiprotocol, 4-byte ASNs, route refresh).
    3. KEEPALIVE confirmation (OpenConfirm -> Established): if the OPEN parameters match configuration, each router replies with a 19-byte KEEPALIVE message (usually sent every hold_time / 3 seconds; operators often add BFD — Bidirectional Forwarding Detection — for sub-second link-failure detection). Receiving that KEEPALIVE moves the session to Established.

    Sessions come in two flavors: eBGP (external BGP between two different ASes, sent with IP TTL 1 by default over a direct link) and iBGP (internal BGP between routers inside the same AS, typically peered between stable loopback addresses).

  3. How BGP exchanges routes and updates its tables

    Once Established, peers exchange their current valid routes once and thereafter send only incremental UPDATE messages when routes appear, change attributes, or disappear—there is no periodic full-table refresh. Each UPDATE carries withdrawn prefixes, path attributes, and NLRI (Network Layer Reachability Information — the list of prefixes sharing those attributes; IPv6 prefixes use MP_REACH_NLRI and MP_UNREACH_NLRI from 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_PATH untouched, AS_PATH cannot 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.

  4. 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, default 100, higher wins): controls outbound traffic from your entire AS. Setting customer routes to 200, settlement-free peer routes to 150, and paid transit routes to 100 enforces 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 reach NEXT_HOP, BGP ignores the route completely.
    • COMMUNITY (optional transitive): numeric tags (like 65101:100) used to group routes so policies can match them cleanly.

    When Loc-RIB has multiple valid routes for the exact same prefix (say 198.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-breaker
    

    Two rules sit outside BGP's tie-breaker: 1. Longest prefix match always wins during packet forwarding: a route to 198.51.100.0/25 beats 198.51.100.0/24 for destination 198.51.100.10, regardless of LOCAL_PREF or AS_PATH. 2. Administrative distance arbitrates when two different routing protocols (say OSPF and BGP) both know the exact same prefix /24 (Cisco defaults: eBGP 20, OSPF 110, iBGP 200 — lower wins).

  5. Worked numeric example and Python simulation

    Suppose a border router in AS 65000 receives three candidate routes for 198.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 = 100 on all three): all tie on Step 2 (LOCAL_PREF = 100). At Step 4 (AS_PATH length), R1 (2) and R3 (2) eliminate R2 (3). Both tie on ORIGIN (igp) and MED (0, both from neighbor 65101). At Step 7 (eBGP over iBGP), R1 wins.
    • Policy override: AS 65102 is a lower-cost provider, so import policy sets LOCAL_PREF = 200 on R2. Now R2 wins immediately at Step 2, beating the shorter AS_PATH of R1 and R3.
    • Neighbor MED hint: revert LOCAL_PREF = 100, and suppose AS 65101 advertises MED = 50 on R1 and MED = 0 on R3. Because both enter from the same neighbor (65101), Step 6 compares their MED values and R3 wins (0 < 50), steering traffic through internal border router 10.10.0.4.

    Here is the core decision waterfall in Python (using deterministic MED grouping 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]
    
  6. 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_HOP is reachable (Step 0) and to measure internal distance to each exit router (Step 8).

  7. 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 n routers needs n * (n - 1) / 2 TCP sessions: for n = 50 routers, 50 * 49 / 2 = 1,225 sessions! Deploying 2 redundant route reflectors (RFC 4456 — special iBGP routers permitted to re-advertise routes among client peers while tracking ORIGINATOR_ID and CLUSTER_LIST to stop loops) drops those 50 routers (48 clients + 2 reflectors) to 48 * 2 + 1 = 97 sessions.
    • eBGP in modern leaf-spine data centers (RFC 7938): hyperscale data centers often skip OSPF entirely and assign a private ASN (64512–65534 or 4-byte 4200000000–4294967294) to each rack switch or spine tier, using eBGP equal-cost multipath for predictable failure blast radius and rich policy filtering.

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:

  • R1 via eBGP (AS_PATH: 65101 -> 65200, LOCAL_PREF: 100)
  • R2 via eBGP (AS_PATH: 65102 -> 65103 -> 65200, LOCAL_PREF: 100)
  • R3 via iBGP (AS_PATH: 65101 -> 65200, LOCAL_PREF: 100)
  1. Under equal LOCAL_PREF = 100, BGP checks AS_PATH length next: R2 (3 AS hops) loses to R1 and R3 (2 AS hops), and R1 beats R3 because external eBGP exits are preferred over internal iBGP paths.
  2. Now suppose AS 65102 is a paying customer or cheaper link, so AS 65000 sets LOCAL_PREF = 200 on R2: because LOCAL_PREF is checked before AS_PATH length, R2 wins 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_PATH provides built-in loop detection.
  • Session lifecycle: manually configured peers connect on TCP port 179, exchange OPEN messages (version 4, ASN, negotiated hold time = smaller proposal, router ID, capabilities), confirm with KEEPALIVEs, and reach Established (Idle -> Connect -> Active -> OpenSent -> OpenConfirm -> Established).
  • Incremental route updates: after one initial table exchange, peers send UPDATE messages (withdrawals + path attributes + prefixes) only when routes change—never on a periodic flood timer.
  • Policy-first best-path waterfall: ignore unreachable NEXT_HOP -> highest local WEIGHT -> highest LOCAL_PREF (AS-wide outbound policy) -> locally originated -> shortest AS_PATH -> lowest ORIGIN -> lowest MED (same neighbor AS) -> eBGP over iBGP -> lowest IGP cost to NEXT_HOP -> oldest eBGP route / lowest router ID / peer IP.
  • Forwarding vs BGP selection: longest prefix match (/25 beats /24 regardless of BGP attributes) and administrative distance (choosing between protocols for the exact same prefix: Cisco eBGP 20, OSPF 110, iBGP 200) happen outside BGP's tie-breaker.
  • BGP vs OSPF: OSPF floods link states inside one AS over IP protocol 89 and runs Dijkstra for fast sub-second shortest-path convergence; BGP hides topology, scales to ~1,000,000 prefixes, enforces policy, and relies on OSPF (or IS-IS) to make internal NEXT_HOP addresses reachable.

Common mistakes

  • Describing BGP as "shortest-path routing": AS_PATH length is checked only after LOCAL_PREF (and vendor WEIGHT), and even then it counts whole organizations traversed, not router hops, link bandwidth, or latency.
  • Assuming Active state means the session is working: Active means TCP port 179 connection attempts are failing and retrying; only Established exchanges routes.
  • Trying to steer inbound internet traffic with LOCAL_PREF: LOCAL_PREF is stripped on eBGP export and stays strictly inside your own AS, so it only controls your outbound traffic.
  • Expecting MED to compare across two different ISPs: by default, routers compare MED only when two routes enter from the same neighboring AS, and neighbors never forward MED to downstream ASes.
  • Forgetting NEXT_HOP reachability across iBGP: iBGP preserves the external eBGP peer's IP as NEXT_HOP by default; unless next-hop-self is 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 (/24 vs /24); packet forwarding always picks /25 over /24 even if /24 has LOCAL_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? Active indicates that the speaker is attempting TCP port 179 handshakes that fail before OPEN messages can be exchanged, so begin at Layers 3 and 4: confirm bidirectional IP routing from the exact configured source address (ping <peer> source <loopback> when update-source is configured) and ensure no ACL or firewall drops TCP 179 in either direction. Next verify symmetric BGP transport configuration on both routers: the remote router's neighbor statement must match your outgoing source IP, loopback-to-loopback eBGP requires ebgp-multihop (default eBGP IP TTL is 1), and any TCP MD5 authentication secret must match byte-for-byte (a mismatched MD5 digest silently drops TCP segments in Active, whereas a mismatched remote-as completes TCP, sends OPEN, and tears down with a NOTIFICATION). Check show ip bgp neighbors, syslog errors, and a tcpdump capture on TCP port 179 to see whether SYN packets go unanswered, receive RST, 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_PATH unchanged, AS_PATH loop 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 of n * (n - 1) / 2 TCP sessions (1,225 sessions across 50 routers). Route reflectors (RFC 4456) safely lift split-horizon on designated hub routers that reflect client routes while attaching ORIGINATOR_ID and CLUSTER_LIST attributes to block loops, cutting 50 routers (48 clients + 2 redundant reflectors) down to 97 sessions—at the cost of hiding non-best alternate paths unless ADD-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 (say 200 vs default 100 on 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 as 65000 65000 65000 outbound toward the secondary ISP so the primary path has a shorter AS_PATH), attach provider-supported BGP communities instructing the secondary ISP to lower its internal LOCAL_PREF on your prefixes, or advertise more-specific sub-prefixes (e.g., two /24 blocks) on the primary ISP while advertising the covering /23 aggregate on both ISPs for automatic failover (remembering that IPv4 prefixes longer than /24 or IPv6 prefixes longer than /48 are filtered globally). Only longest-prefix match overrides a remote ISP's own LOCAL_PREF policy.
  • 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 UPDATE messages. Structure tests into four tiers: (1) FSM and negative protocol tests covering capability negotiation, hold-timer expiration, bad ASN/MD5 credentials, graceful restart, and malformed UPDATE fuzzing 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,000 prefixes and link flaps while tracking convergence time, CPU load, and memory growth; and (4) multi-vendor interoperability runs.

Follow-up questions

Similar questions

More Cisco interview questions

All 12 Cisco questions →