Sub topic 15
Computing shortest paths with Dijkstra's algorithm
This chapter assumes you know the link-state flow from the previous chapters: routers exchange hellos, flood link-state advertisements (LSAs), and end up with an identical link-state database (LSDB). It also assumes you know basic graph terms and how a routing table is used. Here you will see how each router turns that shared database into forwarding decisions.
What the router computes
Every router in an area holds the same graph. Each router runs the shortest path first (SPF) computation on its own copy, with itself as the root. Dijkstra's algorithm produces a shortest-path tree. The tree gives two things for every destination:
- The total cost from the root to that destination.
- The first hop, which is the neighbor of the root that the path starts with.
Only the first hop goes into the forwarding table. A router does not need the rest of the path, because the next router on the path runs the same computation on the same database and picks the next hop itself. This works only if all routers agree on the graph. That is why LSDB synchronization matters so much.
The algorithm
Dijkstra's algorithm grows a set of "settled" nodes outward from the root:
- Set the root's distance to 0 and put it in a priority queue.
- Remove the queued node with the smallest tentative distance. Mark it settled. Its distance is now final.
- For each unsettled neighbor, compute
distance(node) + link cost. If this beats the neighbor's best known distance, record it and queue the neighbor. Carry along the first hop. If the node being expanded is the root, the first hop is the neighbor itself. Otherwise it is the first hop already stored for the node. - Repeat until the queue is empty.
Settling is correct because all costs are non-negative. Once the closest unsettled node is removed, no other path can reach it more cheaply, since any other path must pass through a node that is at least as far away.
Implementation
This function takes the LSDB as a dictionary and returns the distance and first hop for every reachable destination.
import heapq
def spf(graph, source):
"""graph: node -> {neighbor: cost}. Returns (distance, first_hop) per destination."""
dist = {source: 0}
first_hop = {}
done = set()
heap = [(0, source, None)]
while heap:
d, node, hop = heapq.heappop(heap)
if node in done:
continue
done.add(node)
if node != source:
first_hop[node] = hop
for nbr, cost in graph[node].items():
nd = d + cost
if nbr not in done and nd < dist.get(nbr, float("inf")):
dist[nbr] = nd
heapq.heappush(heap, (nd, nbr, nbr if node == source else hop))
return dist, first_hop
graph = {
"A": {"B": 1, "C": 2},
"B": {"A": 1, "C": 2, "D": 5},
"C": {"A": 2, "B": 2, "D": 1},
"D": {"B": 5, "C": 1, "E": 3},
"E": {"D": 3},
}
dist, first_hop = spf(graph, "A")
print(dist)
print(first_hop)The program prints:
{'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 6}
{'B': 'B', 'C': 'C', 'D': 'C', 'E': 'C'}The code uses a lazy-deletion heap. A node may be pushed more than once, and stale entries are skipped when they come off the heap because the node is already in done.
Worked trace
The example topology has five routers, and the costs label the links.
Run SPF from A:
| Step | Settled node | Distance | Action |
|---|---|---|---|
| 1 | A | 0 | Queue B at 1 (hop B) and C at 2 (hop C). |
| 2 | B | 1 | C via B costs 3, which is worse than 2. Queue D at 6 (hop B). |
| 3 | C | 2 | D via C costs 3, which beats 6. Queue D at 3 (hop C). |
| 4 | D | 3 | Queue E at 6 (hop C). |
| 5 | D at 6 | none | Stale heap entry, skipped. |
| 6 | E | 6 | Settled with first hop C. |
A's forwarding table therefore sends traffic for B to B, and traffic for C, D, and E to C. The path to D is A-C-D, not A-B-D, even though B is the closest neighbor. Distance to the neighbor does not decide the route. The total path cost does.
Cost and behavior in practice
With a binary heap, SPF runs in O((V + E) log V) time. Even a few thousand routers finish in milliseconds on modern hardware. The real cost is how often it runs. Every topology change triggers a new SPF, so a flapping link can keep the CPU busy. Implementations protect themselves with SPF throttling: a short initial delay to batch several LSAs, then exponentially increasing delays while changes continue. Many also run a partial calculation when only a stub network or an external route changes, because the tree itself is unaffected.
Several details separate a textbook SPF from a real one:
- Two-way check. A router only uses a link when both ends advertise it. Without this, a one-directional failure would produce a path that cannot carry return traffic.
- Equal-cost paths. The code above keeps the first path found at a given cost and ignores ties. Real implementations store every first hop whose cost ties and install them all, which gives equal-cost multipath (ECMP). OSPF installs up to a configurable number of such paths.
- Networks as nodes. On a broadcast segment, the designated router's network LSA represents the segment as a pseudonode. SPF treats it as a node, with cost 0 on the edge from the pseudonode to each attached router.
- Stub and external prefixes. Prefixes attach as leaves to the tree after the router-to-router tree is complete. Their cost is the cost to the advertising router plus the prefix's own metric.
Why consistent databases matter
Dijkstra is deterministic, so identical LSDBs produce consistent trees and loop-free forwarding. The weak point is the period when databases differ. If router X has processed a failure and router Y has not, X may send traffic to Y while Y sends it back. This forms a transient microloop that lasts until flooding and SPF finish on both routers. It is much shorter-lived than a count-to-infinity loop, but it is the main loop risk in link-state networks.
Exercise
In the example topology, the cost of the C-D link rises from 1 to 9 in both directions. Run SPF from A again. What are the distances to D and E, and what is the first hop for each?
Show answer
Through C, D would cost 2 + 9 = 11. Through B, D costs 1 + 5 = 6, so D is reached at cost 6 with first hop B. E is reached through D at cost 6 + 3 = 9, also with first hop B. A's forwarding table now sends D and E traffic to B. C stays at cost 2 with first hop C, because the direct A-C link still beats A-B-C at cost 3.