Spanning Tree Protocol
STP is the protocol that keeps Ethernet networks alive by breaking loops in redundant topologies. From 802.1D's 50-second convergence to RSTP's sub-second failover — a deep dive into network resilience.
// CHAPTER 01
The Broadcast Storm That Killed the Network
Ethernet switches have a fundamental design rule: when a switch receives a frame destined for an unknown MAC address, it floods the frame out all ports except the incoming port. This is essential for network discovery. But in a topology with redundant links (loops), flooding creates an infinite storm.
Consider three switches: SW-A, SW-B, SW-C, each connected to each of the others, forming a triangle. A broadcast frame enters SW-A. SW-A floods it to SW-B and SW-C. SW-B floods it back to SW-A and to SW-C. SW-C floods it back to SW-A and SW-B. Each switch immediately floods again. The frame count doubles every microsecond. In milliseconds, all bandwidth is consumed. This is a broadcast storm.
The catastrophic consequence: switches also have limited memory for MAC address tables. As the storm generates billions of frames with randomized or duplicated source MAC addresses, the CAM table thrashes — constantly being overwritten. Legitimate MAC learning becomes impossible, further amplifying flooding.
Radia Perlman's Solution
In 1985, Radia Perlman (working at Digital Equipment Corporation) invented the Spanning Tree Algorithm. The insight: to eliminate loops in a graph, turn the graph into a tree — a loop-free topology. A tree can be constructed by identifying a root node and then finding the shortest path from every other node to the root, discarding all links that are not on any shortest path.
Perlman's algorithm works by having switches exchange special frames called BPDUs (Bridge Protocol Data Units) to collectively elect a root bridge and block the redundant links that would create loops. The result: a loop-free active topology overlaid on the redundant physical topology.
// CHAPTER 02
How STP Works: BPDUs, Root Election, and Port Roles
Step 1: Root Bridge Election
Every switch has a Bridge ID (BID) — a combination of a 2-byte priority (configurable, default 32768) and the switch's 6-byte MAC address. The switch with the lowest BID becomes the Root Bridge. Since priorities are configurable, network administrators can deterministically elect any switch as root by setting it to the lowest priority (e.g., 4096).
BPDUs are sent every 2 seconds (Hello interval). Each switch initially claims to be the Root, but will defer to a lower BID when it receives a superior BPDU. The election converges when all switches agree on the same Root Bridge.
# Cisco IOS — verify root bridge
show spanning-tree vlan 10
VLAN0010
Spanning tree enabled protocol rstp
Root ID Priority 4096
Address aabb.cc00.0101
This bridge is the root
Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec
Bridge ID Priority 4096 (priority 4096 sys-id-ext 10)
Address aabb.cc00.0101
Hello Time 2 sec Max Age 20 sec Forward Delay 15 sec
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- ----
Gi0/1 Desg FWD 4 128.1 P2p
Gi0/2 Desg FWD 4 128.2 P2pStep 2: Root Port Selection
On every non-root switch, each port is assigned a port cost based on link speed. The port that provides the lowest cumulative cost path to the Root Bridge is elected the Root Port. There is exactly one Root Port per non-root switch, and it is always in Forwarding state.
Standard STP port costs: 10 Mbps = 100, 100 Mbps = 19, 1 Gbps = 4, 10 Gbps = 2, 100 Gbps = 1. (These are the IEEE 802.1D-2004 short-mode values — long mode uses larger values for very high-speed links.)
Step 3: Designated Port Selection
For every LAN segment (link between two switches), one port is elected the Designated Port — the single port on that segment that will forward traffic toward the Root Bridge. The Root Bridge's ports are always Designated. For other segments, the switch with the lower path cost to the Root wins Designated status; tiebreaker is lower BID.
Step 4: Alternate and Backup Ports
Any port that is neither a Root Port nor a Designated Port becomes an Alternate Port (in RSTP) — it is blocked to prevent loops. In classic STP, this was called a "Non-Designated Port" and entered the Blocking state. The key insight: Alternate Ports are pre-calculated backup paths. In RSTP, when the Root Port fails, the Alternate Port can immediately transition to Root Port without waiting for timers to expire.
Interactive — STP Topology Viewer
Click a switch to inspect its port roles and states.
Topology: SW-A ↔ SW-B ↔ SW-C ↔ SW-A (triangle = physical loop)
STP blocks SW-C Gi0/2 (Alternate port) to break the loop. Active paths: SW-A→SW-B and SW-A→SW-C. SW-B→SW-C direct path is blocked.
// CHAPTER 03
STP Port States and Timers
Classic STP Port States (802.1D)
In original STP, ports transition through five states when coming online or recovering from a failure. This deliberate slow progression prevents transient loops during topology changes.
Blocking — the initial state. Port receives BPDUs but does not forward any frames (except BPDUs). Duration: Max Age (default 20 seconds) to decide if the port should be active.
Listening — the port is participating in STP and is listening to BPDUs to determine the active topology. No user data frames are forwarded. Duration: Forward Delay (default 15 seconds).
Learning — the port still doesn't forward user data, but it is learning MAC addresses from frames it sees. This pre-populates the CAM table before forwarding starts, preventing a brief flood when forwarding begins. Duration: Forward Delay (15 seconds).
Forwarding — the port is active and fully operational: forwarding frames, learning MAC addresses, and sending/receiving BPDUs.
Disabled — administratively shut down.
Total time from Blocking to Forwarding: Max Age (20s) + Listening (15s) + Learning (15s) = 50 seconds minimum. This is why classic STP convergence is so slow — every topology change means 50 seconds of network unavailability on affected ports.
The STP Timers
Hello Timer (2 seconds): how often the Root Bridge sends BPDUs. If a switch misses 10 consecutive BPDUs (10 × Hello = 20s = Max Age), it declares the Root path lost and re-initiates topology change.
Max Age (20 seconds): how long a switch stores a BPDU before discarding it. When a port misses BPDUs for Max Age duration, it assumes a topology change and begins transitioning.
Forward Delay (15 seconds): time spent in each of the Listening and Learning states.
// CHAPTER 04
Rapid STP (RSTP) — 802.1w
What Changed in RSTP
RSTP keeps the same fundamental algorithm — elect a Root Bridge, select Root Ports and Designated Ports, block alternate paths — but dramatically accelerates convergence with several key changes:
Reduced port states: RSTP collapses five states into three: Discarding (combines Blocking + Listening + Disabled), Learning, and Forwarding. This eliminates the Listening state entirely.
Proposal/Agreement mechanism: When a port wants to become Designated and forward, it sends a BPDU with the Proposal bit set. The downstream switch responds with an Agreement (if it agrees the upstream is the Designated port for the segment). Upon receiving Agreement, the port transitions to Forwarding immediately — no timers needed. This handshake replaces the 30-second wait in classic STP.
Topology Change Notification: In classic STP, Topology Change Notifications (TCN) are sent to the Root, which then floods a TC flag, causing all switches to shorten their MAC address table aging time to Forward Delay (15s) — causing unnecessary MAC flushes. In RSTP, each switch directly flushes its MAC table for ports that receive a TC-flagged BPDU and notifies its neighbors, converging faster without involving the Root.
Edge Ports (PortFast equivalent): RSTP designates ports connected to end devices as "edge ports" — they immediately transition to Forwarding without going through Discarding/Learning. This is functionally identical to Cisco's PortFast feature.
RSTP Port Roles
RSTP defines the same roles (Root, Designated, Alternate) plus one new role: Backup Port — a port that is a backup for a Designated Port on the same switch and same segment (requires a switch with two ports connected to the same hub/segment — rare in modern networks). Alternate and Backup ports are in the Discarding state.
Interactive — RSTP Convergence Simulator
Step through BPDU exchange, port role assignments, and a link failure recovery scenario.
Click "Next Step" to begin the simulation...
RSTP Link Types
RSTP uses link type to determine whether Proposal/Agreement can be used. Point-to-point links (full-duplex between two switches) support Proposal/Agreement and achieve rapid convergence. Shared links (half-duplex, connected to a hub with multiple switches) cannot use Proposal/Agreement — they fall back to classic STP timer-based convergence. In modern networks with only full-duplex switches, all links are point-to-point.
// CHAPTER 05
PVST+, RPVST+, and MSTP
Per-VLAN Spanning Tree (PVST+)
Standard 802.1D and 802.1w run a single spanning tree instance for the entire switched domain. This means all VLANs use the same active topology — the same links are blocked regardless of which VLAN is being considered. This wastes bandwidth on blocked links.
Cisco's proprietary PVST+ (Per-VLAN Spanning Tree Plus) runs a separate STP instance per VLAN. This enables load balancing: SW-A can be root for VLANs 10–20 (directing traffic through one path), while SW-B is root for VLANs 30–40 (directing traffic through another path). Both paths carry traffic simultaneously for different VLANs — doubling effective bandwidth utilization of redundant links.
Multiple Spanning Tree Protocol (MSTP)
PVST+ runs one STP instance per VLAN. With 200 VLANs, you run 200 independent STP processes, each exchanging BPDUs every 2 seconds. On a large campus with 500 switches and 200 VLANs, that's 500 × 200 = 100,000 BPDU packets every 2 seconds — significant CPU and bandwidth overhead.
IEEE 802.1s MSTP solves this by mapping multiple VLANs to a single MST Instance (MSTI). You might have MSTI 1 covering VLANs 10–50, MSTI 2 covering VLANs 51–100, and MSTI 0 (IST, Internal Spanning Tree) covering all remaining VLANs. You get load balancing with only a handful of STP instances regardless of VLAN count.
Interactive — STP Version Comparator
Click a protocol to compare features.
STP802.1D-199830–50 sNoPVST+Cisco (prop)30–50 sYesRSTP802.1w1–6 sNoRPVST+Cisco (prop)1–6 sYesMSTP802.1s1–6 sNo// CHAPTER 06
STP Optimizations: PortFast, BPDU Guard, Root Guard
PortFast
End-host ports (connecting to PCs, phones, printers) will never receive BPDUs — only switches and bridges generate them. Making these ports wait 30–50 seconds to transition to Forwarding is wasteful and causes problems (DHCP requests time out before the port comes up, causing boot failures on diskless workstations).
PortFast bypasses the Listening and Learning states, immediately transitioning to Forwarding when the link comes up. This should only be used on access ports connected to end hosts — if a switch is plugged into a PortFast port, loops can form before STP can react.
BPDU Guard
BPDU Guard is the enforcement mechanism for PortFast ports. If a BPDU is received on a PortFast port, it means something other than an end host is connected — likely a rogue switch. BPDU Guard immediately error-disables the port (shuts it down) and logs an alert. The port requires manual recovery (shutdown → no shutdown) or can be configured to auto-recover after a timeout.
! Apply PortFast and BPDU Guard to all access ports globally spanning-tree portfast default spanning-tree portfast bpduguard default ! Or per-interface interface GigabitEthernet0/1 spanning-tree portfast spanning-tree bpduguard enable ! Verify error-disabled ports show interfaces status err-disabled ! Auto-recovery after 300 seconds errdisable recovery cause bpduguard errdisable recovery interval 300
Root Guard
Root Guard protects against an unauthorized switch becoming the Root Bridge. When Root Guard is enabled on a port, if a superior BPDU is received (one that would cause a new Root election), the port is immediately placed in the root-inconsistent state (no traffic, no MAC learning) until the superior BPDUs stop. This prevents an attacker or misconfigured switch from hijacking the Root Bridge role.
Root Guard should be configured on all ports where you know the Root Bridge should never be located — typically all downlink ports from the distribution layer. The Root Bridge candidates should be the core/distribution switches, never access-layer switches or customer-connected ports.
BPDU Filter
BPDU Filter prevents BPDUs from being sent or processed on a port — essentially hiding the port from STP. This is appropriate for ports connecting to non-STP-capable devices. Use with extreme caution: if a loop is created on a BPDU-filtered port, STP cannot detect and block it, resulting in a broadcast storm.
Loop Guard
Loop Guard protects against a specific failure mode: a unidirectional link failure where a switch stops receiving BPDUs on a Blocking/Alternate port (because the upstream switch can't transmit) but the physical link remains up. Normally, the switch would "age out" the BPDU info and transition the blocked port to Forwarding — creating a loop. Loop Guard detects the absence of BPDUs on a port that should be receiving them and places the port in "loop-inconsistent" state instead of allowing it to transition forward.
// CHAPTER 07
STP and Network Design
Root Bridge Placement Strategy
The Root Bridge should be placed at the network's center of gravity — the switch that provides the shortest average path to all other switches. In a three-tier enterprise network (Access → Distribution → Core), the Root Bridge should be one of the Core switches, not a Distribution or Access switch.
Configure primary and secondary root bridges explicitly. The primary root uses priority 4096; the secondary uses 8192. This ensures deterministic election even after a switch replacement (a replacement switch with default priority 32768 will never outbid 4096).
! Set SW-CORE-01 as primary root for all VLANs spanning-tree vlan 1-4094 root primary ! sets priority to 24576 or lower ! Or manually spanning-tree vlan 10 priority 4096 ! Set SW-CORE-02 as secondary root spanning-tree vlan 10 priority 8192 ! Verify show spanning-tree vlan 10 detail
Diameter and Timer Considerations
The STP default timers assume a maximum network diameter of 7 hops (switches) between any two end points. For each additional hop beyond 7, the Max Age timer may need to be increased. If a BPDU travels 9 hops but Max Age is 20 seconds with 2-second hello intervals, a valid BPDU might expire before reaching the far end, triggering unnecessary topology changes.
With RSTP and MSTP, this is less critical — RSTP uses per-port BPDU aging rather than a global timer, and BPDUs are generated by every switch (not just the Root), so BPDUs never travel the full topology diameter.
// CHAPTER 08
STP Attacks and Security
Root Bridge Spoofing
An attacker connected to an access port can send crafted BPDUs claiming a very low priority (BID priority = 0, MAC = 00:00:00:00:00:01). If Root Guard is not configured, the switch will elect the attacker's device as the Root Bridge. The attacker becomes a chokepoint for traffic flows, enabling traffic interception, manipulation, and man-in-the-middle attacks.
Even without MITM intent, this disrupts the network: topology reconvergence causes 1–50 seconds of outage (depending on STP version), affects all VLANs (unless PVST+ is used), and may establish suboptimal traffic paths that permanently degrade performance.
Mitigation: spanning-tree portfast bpduguard enable on all access ports, spanning-tree guard root on all designated downlinks, and 802.1X authentication to prevent unauthorized devices from connecting.
TCN (Topology Change Notification) Flooding
In classic STP, when a topology change occurs, all switches reduce their MAC address aging time to Forward Delay (15 seconds) for the duration of the TC flag. An attacker can flood the network with continuous TC BPDUs, causing every switch to continuously flush its MAC table. This forces switches into hub-like behavior (flooding unknown MACs) and creates significant CPU and traffic overhead.
STP and VLAN Hopping
Some VLAN hopping attacks require an active trunk port. By injecting BPDUs that trigger topology changes, an attacker can try to manipulate which ports are Designated vs. Alternate — potentially causing a previously blocked trunk to become active, exposing VLANs. This is why BPDU Guard and proper port security must work together.
// CHAPTER 09
STP Monitoring and Troubleshooting
Key Diagnostic Commands
# Full STP topology for a VLAN show spanning-tree vlan 10 # See all port roles/states across all VLANs show spanning-tree summary # Detailed STP info including timers and BID show spanning-tree vlan 10 detail # Which ports are designated on this switch show spanning-tree vlan 10 | include Desg # Watch for topology changes in real time debug spanning-tree events # STP statistics — topology change count show spanning-tree vlan 10 | include topology # Port-level STP state show spanning-tree interface GigabitEthernet0/1 detail
The Five Most Common STP Issues
1. Unexpected Root Bridge. A new switch with default priority (32768) is added to the network but has a lower MAC than the current Root, winning the election. Symptom: topology changes across the network. Fix: explicitly configure priorities on core switches to prevent any access-layer switch from winning.
2. PortFast on trunk ports. A trunk port configured with PortFast immediately forwards frames before STP has determined the topology — creating a loop risk. Symptom: broadcast storms after configuration changes. Fix: PortFast should only be used on access ports. Use spanning-tree portfast trunk only when intentionally needed on trunk ports, and understand the risk.
3. Unidirectional link. A fiber link can transmit in one direction but not the other (TX works, RX fails). The switch on the dead-receive end stops getting BPDUs and transitions its Blocking port to Forwarding — creating a loop. Fix: enable Loop Guard and UDLD (Unidirectional Link Detection) on all inter-switch fiber links.
4. Native VLAN mismatch causing STP issues. STP BPDUs for the native VLAN are sent untagged. If native VLAN doesn't match between switches, STP BPDUs for VLAN 1 will be delivered to the wrong VLAN, causing STP to see phantom topology changes. Fix: ensure native VLAN is consistent across all trunk links.
5. Excessive topology changes. A flapping link (going up/down repeatedly) triggers a TC event every time, causing MAC table flushes and brief forwarding degradation. Identify the flapping port with show interfaces counters errors, then investigate the physical layer (cable, SFP, interface settings).
// CHAPTER 10
STP in Modern Data Centers
RSTP in Enterprise vs. Elimination in Data Centers
In enterprise campus networks, RSTP (typically RPVST+ for Cisco) remains standard. The hierarchical Access-Distribution-Core topology naturally limits the STP domain size. BPDU Guard and Root Guard protect the topology from misconfiguration. PortFast ensures end hosts connect instantly.
In modern data centers, the move to VXLAN-based leaf-spine fabric eliminates L2 loops at the physical layer. Each leaf-to-spine connection is a routed (L3) link. VMs communicate via VXLAN overlay, which encapsulates L2 frames in UDP/IP. The underlay is fully routed — STP is irrelevant at the physical layer. STP may still run within hypervisor virtual switches, but limited to the per-host vSwitch domain.
SPB (Shortest Path Bridging) — IEEE 802.1aq
Shortest Path Bridging uses IS-IS routing protocol to provide loop-free L2 topology without STP. Unlike STP which blocks redundant paths, SPB allows all paths to be active simultaneously, using MAC-in-MAC encapsulation to route frames via the shortest path. SPB provides better bandwidth utilization than STP while maintaining L2 semantics. It has seen adoption in carrier networks and some large enterprise deployments.
// CHAPTER 11
STP Configuration Reference
! === Cisco IOS — Production RSTP Configuration === ! Enable RSTP globally (default on newer IOS) spanning-tree mode rapid-pvst ! Set primary and secondary root bridges spanning-tree vlan 10,20 priority 4096 ! Primary root spanning-tree vlan 30,40 priority 8192 ! Secondary root ! PortFast + BPDU Guard on all access ports (global) spanning-tree portfast default spanning-tree portfast bpduguard default ! Root Guard on distribution downlinks interface range GigabitEthernet0/1-12 spanning-tree guard root ! Loop Guard on inter-switch links interface GigabitEthernet0/24 spanning-tree guard loop ! UDLD on fiber links udld enable aggressive ! Verify complete STP state show spanning-tree summary totals show spanning-tree inconsistentports
! === MSTP Configuration (scaling to many VLANs) === spanning-tree mode mst spanning-tree mst configuration name CAMPUS_MST revision 1 instance 1 vlan 10-50 ! Instance 1 covers VLANs 10-50 instance 2 vlan 51-100 ! Instance 2 covers VLANs 51-100 instance 3 vlan 101-200 ! Instance 3 covers VLANs 101-200 ! Set root per MSTI (load balance between core switches) spanning-tree mst 1 priority 4096 spanning-tree mst 2 priority 8192 spanning-tree mst 3 priority 4096
// CHAPTER 12
Real-World STP Incidents
The Facebook Outage Analogy
While Facebook's 2021 outage was BGP-related, the cascading failure pattern is analogous to STP storms. In STP: one misconfigured link causes a topology change → all switches flush MACs → all switches flood unknown frames → CPU spikes across all switches → switches can't process BPDUs → topology changes cascade → entire domain oscillates.
The defense is always defense-in-depth: Root Guard prevents unauthorized Root elections; BPDU Guard prevents rogue switches; Loop Guard prevents unidirectional link failures from creating loops; UDLD detects fiber failures before STP timer expiration. No single protection is sufficient.
The "Rogue Switch" Incident
A common real-world incident: an employee brings a home router/switch combination and plugs two of its ports into different wall jacks on the office network (perhaps trying to extend connectivity). The device creates a physical loop. If the office switch ports have PortFast but no BPDU Guard, and the home device sends BPDUs, STP must reconverge. If the home device doesn't send BPDUs (it's not STP-aware), a loop forms and a broadcast storm ensues. BPDU Guard would err-disable the ports immediately. Without it, the network operator scrambles to find which port is looped.
// CHAPTER 13
Common Misconceptions
// CHAPTER 14
Interview Questions
🎯 Key Takeaways
- ✓STP prevents broadcast storms in redundant Ethernet topologies by blocking ports that would create loops — creating a logical tree over a physical mesh.
- ✓Root Bridge election uses Bridge ID (priority + MAC); the lowest BID wins. Explicitly set priority on core switches to control which switch becomes Root.
- ✓Port roles: Root Port (best path to Root, one per non-root switch), Designated Port (best port per segment), Alternate (blocked backup path), Backup (blocked duplicate Designated).
- ✓Classic STP convergence is 30–50 seconds due to Listening + Learning timers. RSTP (802.1w) achieves 1–6 seconds using Proposal/Agreement handshake instead of timers.
- ✓PVST+ runs one STP instance per VLAN (enabling load balancing). MSTP maps multiple VLANs to MST instances, reducing BPDU overhead dramatically.
- ✓PortFast bypasses Listening/Learning for access ports — pair it always with BPDU Guard, which err-disables the port if a BPDU is received (indicating a rogue switch).
- ✓Root Guard prevents unauthorized switches from becoming Root Bridge. Loop Guard prevents unidirectional link failures from causing loops. Both are critical hardening measures.
- ✓Modern data center leaf-spine topologies are fully routed (L3), making STP irrelevant at the underlay. VXLAN provides L2 overlay semantics without requiring STP.
- ✓STP attacks include Root Bridge spoofing (injecting low-priority BPDUs) and TCN flooding (forcing continuous MAC table flushes). BPDU Guard and Root Guard mitigate both.
- ✓RSTP port states are Discarding, Learning, and Forwarding — simpler than classic STP's five states. Edge ports (PortFast) skip directly to Forwarding for end-host connections.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.