BGP Best Path Selection: The 13-Step Algorithm Explained - 夜莺博客

BGP Best Path Selection: The 13-Step Algorithm Explained

BGP routers commonly hear multiple paths to the same prefix, and the best path algorithm decides which one is installed in the routing table and advertised onward. The algorithm is a tiebreaker cascade: most paths never survive past the first few steps. Knowing which attribute decides in which scenario — and which knobs are local versus AS-wide — is the real skill. This guide walks the full Cisco 13-step order with a worked example of a dual-homed router.

The 13-Step Best Path Order

 0. Next hop must be reachable (drop unreachable paths)
 1. Weight           — highest wins (Cisco-proprietary, local to the router)
 2. Local preference — highest wins (advertised inside your AS)
 3. Locally originated (network/aggregate/redistribute) preferred
 4. AS_PATH          — shortest wins
 5. Origin           — IGP (i) > EGP (e) > incomplete (?)
 6. MED              — lowest wins, only if same neighbor AS
 7. eBGP over iBGP   — prefer external paths
 8. IGP metric to next hop — lowest wins
 9. maximum-paths: install multiple if equal here
10. Oldest eBGP path preferred
11. Lowest Router-ID
12. Lowest neighbor address

Worked Example: Three eBGP Paths

R1 hears 10.0.0.0/24 from three providers:

Path      Weight  LocalPref  AS-path    MED
ISP-A        0       200     65100 65200  100
ISP-B        0       200     65300        100
ISP-C      100       100     65400         50

Step 1 decides everything: ISP-C wins on weight (100 vs 0). Had weights been equal, local preference would have eliminated ISP-C (100 < 200), then AS-path length would pick ISP-B (one AS) over ISP-A (two).

Manipulating Selection

Weight forces one router to prefer an exit without affecting the rest of the AS — the classic remote-office-with-two-ISPs case. Set it inbound from a neighbor with a route-map:

route-map PREFER-ISP1 permit 10
 set weight 200
!
router bgp 65001
 neighbor 203.0.113.1 route-map PREFER-ISP1 in

Local preference is the AS-wide decision: set it at the eBGP edge and every iBGP router agrees on the exit. It is compared only among paths for the same prefix learned from the same... well, any neighbor — and it travels inside iBGP updates:

route-map SET-LP permit 10
 set local-preference 200
!
router bgp 65001
 neighbor 203.0.113.1 route-map SET-LP in

MED and Its Catch

MED (multi-exit discriminator) is a hint from the neighboring AS — lower is better, but it is only compared when the two paths come from the same neighbor AS. Otherwise the step is skipped. A common provider-side tuning technique is AS-path prepending: set as-path prepend 65001 65001 lengthens the path and makes a backup link less attractive.

Verification

show ip bgp
show ip bgp 10.0.0.0/24
show ip bgp neighbors 203.0.113.1 advertised-routes

show ip bgp <prefix> prints every path with weight, localpref and AS-path columns plus the > marker on the winner — read that output and you can always explain why a path won. Route dampening changes how flapping paths are treated (see BGP route dampening), and the same show commands apply on IOS XR BGP configurations.

原文链接:https://packetmentor.com/topics/bgp-path-selection

Why "Best" Is Only Locally Best

BGP is a path-vector protocol with no global view of the topology, so "best path" always means best path as seen by this router, right now, from the paths it happens to know. Two routers inside the same autonomous system can and frequently do install different next hops for the same prefix. That is not a bug — it is the direct consequence of a tiebreaker cascade that evaluates a long list of attributes in strict order and stops at the first difference. Knowing exactly where the cascade stops on each of your routers is the difference between predictable traffic flows and a support ticket that nobody can explain.

It also helps to sort the attributes into two families. Cisco's weight and local preference express local policy — "we want traffic to leave here". AS_PATH length, origin, MED and the surrounding AS relationships usually express learned topology — "this is what the network looks like from the outside". When you debug, ask which family the deciding attribute belongs to. That single question tells you whether the answer lives in your own configuration or somewhere upstream in somebody else's network.

Attribute-by-Attribute Detail

1. Next Hop Reachability — the Silent Killer

Before any attribute is compared, the next hop carried in the BGP path attribute must be resolvable in the IGP or by a static route, and it must not point at an interface that is down. A path with an unreachable next hop is simply not considered. On iBGP this is where the classic "next hop is carried unchanged across the AS" problem bites: the eBGP advertisement arrives with the external neighbour address, the receiving iBGP router cannot resolve it, and the prefix is dropped from the BGP table even though the session is up. The symptom is a route that appears on the edge router but nowhere else. Fix it with neighbor <ip> next-hop-self on the iBGP sessions, or by redistributing the external link into the IGP.

2. Weight — Highest Wins

Weight is a 16-bit value, local to one router, and never transmitted to any peer — not even to iBGP neighbours. That is what makes it the surgical tool it is: on a router with two uplinks you can force one exit without touching a single other device. Weights default to 0 for learned routes and 32768 for locally originated ones, so a network statement always beats a learned path for the same prefix unless you have explicitly weighted the learned path higher.

router bgp 65001
 address-family ipv4 unicast
  neighbor 203.0.113.1 route-map PREFER-ISP1 in
!
ip prefix-list DEEP-PREFIXES seq 10 permit 0.0.0.0/0 le 32
!
route-map PREFER-ISP1 permit 10
 match ip address prefix-list DEEP-PREFIXES
 set weight 200

The usual production pattern is weight only for a handful of specific prefixes ("send the voice subnet out of the primary ISP"), while the AS-wide preference is expressed with local preference.

3. Local Preference — Highest Wins

Local preference is the AS-wide decision. It is carried in iBGP updates, so setting it once at the eBGP edge makes every router inside the AS agree on the exit point. The default is 100. Because it beats every topology-derived attribute except weight, a careless set local-preference 200 on a backup link can black-hole traffic for prefixes the primary never learns — always pair local-preference changes with a prefix-list or an inbound AS-path filter so you know exactly which routes are affected.

route-map SET-LP-PRIMARY permit 10
 set local-preference 200
!
route-map SET-LP-BACKUP permit 10
 set local-preference 90

Note the second clause: a backup path gets a lower than default value rather than the primary being raised, which keeps the "default is neutral" convention intact and makes later troubleshooting much easier.

4. Locally Originated Routes

A route injected by network, aggregate-address or redistribute is preferred over an identical prefix learned from a peer. This is why an aggregate summary quietly overrides a more specific externally learned path for the same mask.

5. AS_PATH Length

Shortest wins, counting AS numbers as they appear. Two things trip people up here. First, AS_PATH length is compared before origin and MED, so no amount of MED tuning will rescue a path that is one AS hop longer. Second, the count is of AS numbers as written, not distinct autonomous systems — an AS that prepends its own number three times makes the path three hops longer by this metric. That is precisely why prepending works, and precisely why it is a blunt instrument: it lengthens the path for every prefix you prepend on, for every observer.

route-map PREPEND-BACKUP permit 10
 set as-path prepend 65001 65001 65001

On modern Cisco code you can also influence which path survives the AS_PATH comparison with bgp bestpath as-path multipath-relax, which relaxes the equal-length requirement for multipath, and bgp bestpath as-path ignore, which removes AS_PATH from the comparison entirely and hands the decision to origin and MED — a dangerous knob that exists for very specific transit-selection problems.

6. Origin Code

IGP (i, set by a network statement) beats EGP (e, effectively extinct) beats incomplete (?, set by redistribution). Because redistribution always produces ?, a prefix that you both originate with network and hear from a peer will resolve in your own favour — a useful safety property.

7. MED — Lowest Wins, With Conditions

MED is a hint from the neighbouring AS meaning "prefer this entry point". It is only compared between paths that came from the same neighbouring AS; otherwise the step is skipped and the cascade moves on. That single rule explains most "why is MED being ignored?" questions. Two Cisco commands change the behaviour:

router bgp 65001
 bgp always-compare-med
 bgp deterministic-med

always-compare-med allows comparison across different neighbour ASes — it must be configured identically on every router in the AS or you create persistent routing loops. deterministic-med sorts paths by neighbour AS before comparing, which removes a hidden dependency on the order in which updates arrived. The most common MED practice is a missing-MED policy: accept the peer's MED when present, and when it is absent treat it as a known worst case rather than as zero.

route-map MED-IN permit 10
 set metric 4294967295
!
route-map MED-IN permit 20
 match metric 0
 set metric 100

8. eBGP over iBGP

External paths win over internal ones when everything above is equal. This is why an edge router will prefer a directly attached customer over an iBGP-learned route from the other side of the AS — and why, on a route reflector topology, a second-best external path on a client is preferred over the best path reflected from a non-client unless you reach for bgp bestpath igp-metric ignore or a route-map that repaints local preference.

9. IGP Metric to the Next Hop

Lowest interior cost wins. This is the step that makes your IGP design matter to your egress selection. It is also the point at which multipath decisions are made: if paths are still equal here, maximum-paths installs them all and the traffic is load-shared by the forwarding hashing.

router bgp 65001
 address-family ipv4 unicast
  maximum-paths 4
  maximum-paths ibgp 2

10–12. The Tie-Breakers

If you get this far, the paths are truly identical in cost and policy. Cisco prefers, in order: the oldest external path (the "oldest path" rule, designed to reduce churn on flapping routes), then the lowest Router-ID, then the lowest neighbour address. The oldest-path rule has a side effect worth remembering: if a peer resets, its path is now newer and loses to a path of the same length that survived the reset — which can silently move traffic after any BGP session flap.

Multipath and Add-Path

Nothing in the cascade above forces a single winner. When several paths are equal through every step, maximum-paths installs them side by side and the router performs per-flow load sharing. Add-path and best-external take the idea further by advertising more than one path to a peer, which mostly matters for fast convergence and for BGP-based anycast designs — see BGP best external and add-path for the configuration details.

Common Mistakes and a Debugging Checklist

  • Reaching for prepending first. Prepending is the only tool that both lengthens the path for everyone and is compared at step 4 — before origin, MED and IGP metric. Local preference acts earlier and stays inside your AS.
  • Setting weight on the wrong router. Weight does not cross an iBGP session, so a weight applied on a core router has no effect on the edge router doing the selection.
  • Mixing always-compare-med with a non-uniform config. If one router has it and another does not, the two will disagree forever.
  • Assuming MED will be honoured. Peers are free to ignore it, and most will if the two paths arrive from different ASes.
  • Forgetting next-hop-self. The route exists on one router and nowhere else.

Run the three commands below on the router that is not choosing the path you expect, and read the winner marker:

show ip bgp 10.0.0.0/24
show ip bgp neighbors 203.0.113.1
show ip bgp summary

Read the columns left to right — status, weight, localpref, metric, AS-path — and stop at the first attribute where one line differs from the winner. That attribute is your answer. Related reading: BGP communities if you tag routes as they enter the AS, and route reflectors if your iBGP mesh is affecting which path the core sees.