Real-world troubleshooting: debug pod-to-external BGP flaps with Python automation on Kubernetes

Real-world troubleshooting: debug pod-to-external BGP flaps with python automation on Kubernetes

BGP “flaps” affecting pod-to-external traffic are rarely caused by a single component. They’re usually an interaction between Kubernetes dataplane behavior (kube-proxy iptables vs eBPF), node networking, and upstream routing policy (TOR/fabric/edge/ISP). This post walks through an advanced, practical troubleshooting workflow, and shows how to use python automation to correlate evidence across Kubernetes and BGP control plane logs—then drive safe, transient mitigations.

Problem framing: what “pod-to-external BGP flaps” often looks like

Symptoms typically show up as:

  • Short bursts of failed egress (timeouts) from pods to the internet or external services.
  • BGP sessions on nodes/route-reflectors bouncing, or steady sessions with route churn.
  • External monitoring seeing service IPs or node prefixes alternating paths.
  • “It only happens during node scaling / upgrades / CNI restarts / busy hours.”

A key insight: application failures are data-plane, while BGP churn is control-plane. You need to prove they correlate in time and scope before changing anything.


Reproduce and scope

1) Capture application traffic (prove impact and direction)

Start from the pod’s perspective:

  • Is DNS failing or TCP failing?
  • Is the failure SYNs not leaving, SYN/ACK not returning, or mid-flow resets?
  • Is it only certain destinations (one ISP/ASN), or all external?

Run a targeted capture on the node hosting the pod (more on choosing interfaces below):

bash
# Identify the node and pod IP
kubectl -n app get pod -o wide

# Quick connectivity test from the pod
kubectl -n app exec -it POD -- sh -c 'time nc -vz -w 2 1.1.1.1 443; echo $?'

# Capture only that pod IP and external target on the node (via ssh)
ssh NODE '
  sudo timeout 60 tcpdump -ni any -s0 -vv \
    "(host POD_IP) and (host 1.1.1.1) and (tcp port 443)" \
    -w /tmp/pod-egress.pcap
'

What to look for in the pcap:

  • Repeated SYN with no SYN/ACK: upstream return path issue, NAT state issue, or ACL/policy drop.
  • SYN leaves, SYN/ACK arrives but never reaches pod: node dataplane/conntrack/iptables/eBPF issue.
  • Midstream stalls: MTU/PMTUD blackhole, asymmetric routing, ECMP hashing changes.

2) kube-proxy iptables vs eBPF: choose the right lens

iptables kube-proxy (classic):
- Failure modes often involve conntrack table exhaustion, stale NAT entries, or rule churn during endpoint updates.
- Evidence: conntrack -S, iptables-save, kernel log drops.

eBPF dataplane (Cilium, Calico eBPF, etc.):
- Failure modes more often involve BPF program reloads, map pressure, CT map limits, or host-routing changes.
- Evidence: cilium monitor, bpftool map, agent logs, BPF CT drops.

Quick discriminators:

bash
# kube-proxy mode hints
kubectl -n kube-system get ds kube-proxy -o yaml | grep -iE 'mode|iptables|ipvs' -n

# Is iptables doing service DNAT?
ssh NODE 'sudo iptables -t nat -S | head'

# eBPF dataplane hints (example: Cilium)
kubectl -n kube-system get pods -l k8s-app=cilium

In practice, don’t assume: confirm which component is responsible for service translation (ClusterIP/NodePort) and which advertises routes externally (kube-router, Calico BGP, FRR, etc.).

3) Isolate where the problem lives: cluster vs fabric vs ISP handoff

Use a simple decision tree:

  • If BGP sessions are flapping between nodes and TORs/fabric:
  • suspect physical/link, MTU, interface errors, BFD, aggressive timers, control-plane CPU spikes.
  • If BGP sessions stay up but routes flap/withdraw rapidly:
  • suspect node agent restarts, CNI/BGP daemon restarts, policy changes, route-map issues, next-hop reachability.
  • If Kubernetes node events align with route churn:
  • suspect kubelet/CRIO/containerd pressure, CNI restarts, node reboots, kernel OOM, conntrack pressure.
  • If only certain external prefixes/destinations fail while BGP is stable:
  • suspect upstream ISP policy, blackholing, RPKI filtering, or asymmetric path changes.

Data collection recipes

The goal is to collect just enough data to correlate events across systems with consistent timestamps.

1) Targeted tcpdump on the right interfaces

On nodes, prefer capturing on:

  • The host uplink (e.g., eth0, ens192) to see packets leaving/returning.
  • The CNI host-side veth (if you can identify it) to prove delivery to pod.
  • any is convenient, but can hide offload behavior; use it for quick triage, then refine.

Examples:

bash
# Host uplink only, for return path verification
ssh NODE 'sudo timeout 60 tcpdump -ni eth0 -s0 -vv host 1.1.1.1 and tcp port 443'

# Capture BGP traffic (TCP/179) on TOR-facing interface
ssh NODE 'sudo timeout 60 tcpdump -ni eth0 -s0 -vv tcp port 179'

Tips:
- Ensure NTP is healthy on nodes and network devices.
- Always record the node name, pod IP, interface, and UTC time window.

2) BGP update logs (FRR / BIRD / GoBGP)

If you’re using FRR (common with Calico when configured, or standalone):

bash
# Inspect neighbor health
ssh NODE 'vtysh -c "show bgp summary"'

# Capture recent BGP events
ssh NODE 'sudo journalctl -u frr -S "2026-01-25 10:00:00" -U "2026-01-25 10:20:00" | tail -200'

# Enable transient debugging during a controlled window (use carefully)
ssh NODE 'vtysh -c "debug bgp neighbor-events" -c "debug bgp updates"'

If updates are too noisy, enable logging to a dedicated file for a brief window and disable afterwards.

On fabric/edge devices:
- Pull show bgp neighbors ... received-routes / advertised-routes samples (platform dependent).
- Capture syslog entries indicating neighbor resets, BFD down, or policy rejects.

3) SNMP/telemetry pulls: prove link/CPU/queue issues

Collect:
- Interface errors/discards (CRC, input errors, output drops).
- Device CPU (control-plane starvation can reset BGP).
- Queue depth / congestion indicators (especially if BGP is carried in-band with data).

Example SNMP snippets (replace OIDs/vendor specifics as appropriate):

bash
# Interface counters (generic IF-MIB examples)
snmpwalk -v2c -c COMMUNITY TOR1 IF-MIB::ifInErrors.1
snmpwalk -v2c -c COMMUNITY TOR1 IF-MIB::ifOutDiscards.1

4) Correlate timestamps across systems (the “single timeline” rule)

Create a timeline in UTC with:
- Kubernetes node/pod events
- BGP session state changes and route updates/withdrawals
- Interface error bursts / CPU spikes
- Packet-capture windows and app failure timestamps

Kubernetes event pulls:

bash
# Node lifecycle and readiness changes
kubectl get events --all-namespaces --field-selector involvedObject.kind=Node \
  --sort-by='.lastTimestamp' | tail -200

# Pod reschedules/restarts around the incident
kubectl -n app get events --sort-by='.lastTimestamp' | tail -200

# Node conditions and taints
kubectl describe node NODE | sed -n '/Conditions:/,/Addresses:/p'

Python tooling: correlate BGP updates with Kubernetes events

Manual correlation doesn’t scale when flaps are intermittent. The pattern that works well:

  1. Parse BGP daemon logs (or ExaBGP/GoBGP JSON streams) into structured events.
  2. Parse Kubernetes events for nodes/pods into structured events.
  3. Merge by timestamp, group by node, then generate hypotheses.

Data model: normalize everything to {ts, node, type, details}

Sources you can leverage:
- journalctl logs from FRR/BIRD
- kubectl get events -o json
- kubectl get nodes -o json for metadata (labels like rack/zone)
- Optional: interface counters snapshots from SNMP/telemetry (timestamped)

Example: python script to correlate FRR neighbor resets with NodeNotReady and pod reschedules

This example assumes:
- You collected frr.log lines (from journald export) per node.
- You collected k8s-events.json from kubectl get events -A -o json.

python
#!/usr/bin/env python3
import json
import re
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable, List, Optional, Dict, Tuple

TS_RE = re.compile(r"^(?P<ts>\w{3}\s+\d+\s+\d+:\d+:\d+)\s+(?P<host>\S+)\s+")
BGP_DOWN_RE = re.compile(r".*bgpd.*(?P<neighbor>\d+\.\d+\.\d+\.\d+).*(BGP Notification|Hold Timer expired|Connection reset).*", re.IGNORECASE)
BGP_UP_RE   = re.compile(r".*bgpd.*(?P<neighbor>\d+\.\d+\.\d+\.\d+).*(Established).*", re.IGNORECASE)

def parse_syslog_ts(line: str, year: int) -> Optional[datetime]:
    m = TS_RE.match(line)
    if not m:
        return None
    # Syslog often lacks year and timezone; assume UTC and provided year
    ts = datetime.strptime(f"{year} {m.group('ts')}", "%Y %b %d %H:%M:%S")
    return ts.replace(tzinfo=timezone.utc)

@dataclass
class Event:
    ts: datetime
    node: str
    etype: str
    details: str

def parse_frr_log(path: Path, year: int) -> List[Event]:
    out: List[Event] = []
    for line in path.read_text(errors="replace").splitlines():
        ts = parse_syslog_ts(line, year)
        if not ts:
            continue
        host_m = TS_RE.match(line)
        node = host_m.group("host") if host_m else "unknown"

        if (m := BGP_DOWN_RE.match(line)):
            out.append(Event(ts, node, "bgp_down", f"neighbor={m.group('neighbor')} line={line.strip()}"))
        elif (m := BGP_UP_RE.match(line)):
            out.append(Event(ts, node, "bgp_up", f"neighbor={m.group('neighbor')} line={line.strip()}"))
    return out

def parse_k8s_events(path: Path) -> List[Event]:
    data = json.loads(path.read_text())
    out: List[Event] = []
    for item in data.get("items", []):
        involved = item.get("involvedObject", {})
        kind = involved.get("kind", "")
        name = involved.get("name", "")
        ns = involved.get("namespace", "")
        reason = item.get("reason", "")
        msg = item.get("message", "")
        # Prefer eventTime/lastTimestamp/firstTimestamp
        ts_str = item.get("eventTime") or item.get("lastTimestamp") or item.get("firstTimestamp")
        if not ts_str:
            continue
        ts = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))

        if kind == "Node" and reason in ("NodeNotReady", "NodeReady", "Rebooted", "Starting"):
            out.append(Event(ts, name, f"k8s_{reason}", msg))
        elif kind == "Pod" and reason in ("Killing", "Started", "Created", "FailedScheduling"):
            # Node name is not always present on pod events; keep namespace/pod
            out.append(Event(ts, "unknown", f"pod_{reason}", f"{ns}/{name} {msg}"))
    return out

def correlate(events: List[Event], window_s: int = 120) -> List[Tuple[Event, List[Event]]]:
    events = sorted(events, key=lambda e: e.ts)
    correlated = []
    for i, e in enumerate(events):
        if e.etype != "bgp_down":
            continue
        neighbors = []
        start = e.ts.timestamp() - window_s
        end = e.ts.timestamp() + window_s
        for j in range(max(0, i - 200), min(len(events), i + 200)):
            e2 = events[j]
            if start <= e2.ts.timestamp() <= end and e2.node == e.node and e2.etype.startswith("k8s_"):
                neighbors.append(e2)
        correlated.append((e, neighbors))
    return correlated

def main():
    frr = parse_frr_log(Path("frr.log"), year=2026)
    k8s = parse_k8s_events(Path("k8s-events.json"))
    all_events = frr + k8s
    hits = correlate(all_events, window_s=180)

    # Simple hypothesis generation
    for bgp_evt, related in hits:
        print(f"\n[{bgp_evt.ts.isoformat()}] {bgp_evt.node} {bgp_evt.etype}: {bgp_evt.details}")
        if related:
            for r in related:
                print(f"  -> {r.ts.isoformat()} {r.etype}: {r.details}")
            print("  Hypothesis: node instability or kubelet/CNI disruption caused BGP session reset.")
        else:
            print("  No local k8s node readiness change observed near flap.")
            print("  Hypothesis: upstream fabric/edge issue, BFD/timers too aggressive, or control-plane CPU starvation.")

if __name__ == "__main__":
    main()

How to feed it data quickly:

bash
# On a node: export FRR logs for a time window into a file
ssh NODE 'sudo journalctl -u frr --since "2026-01-25 10:00:00" --until "2026-01-25 10:20:00" --no-pager' > frr.log

# From your workstation: export k8s events
kubectl get events -A -o json > k8s-events.json

python3 correlate.py

Extend the script for real environments:
- Parse show bgp neighbor ... json output if your stack supports it (structured > regex).
- Add node labels (rack/zone) to detect rack-local flaps (fabric issue).
- Merge telemetry (interface errors/CPU) to strengthen hypotheses.


Automated mitigation playbook (with validation loops)

Mitigation should be transient, scoped, and validated. The goal is to reduce impact while evidence is gathered and a permanent fix is prepared.

Safety rules before automating any routing change

  • Prefer changes that affect only the flapping node/prefix.
  • Use time-bound actions with automatic rollback.
  • Confirm intended blast radius: which prefixes, which neighbors, which VRFs.
  • Validate from both control-plane (BGP state, route visibility) and data-plane (synthetic probes).

1) Route dampening (use carefully)

Route dampening can reduce churn impact, but can also hide real failures and prolong recovery. Apply only when you understand your topology and timers.

  • Better: dampen at the edge/aggregation rather than inside the cluster.
  • Alternative: dampen specific prefix-families (service VIPs vs node podCIDRs).

Validation loop:
- Confirm flap frequency decreases.
- Ensure convergence time remains acceptable.

2) AS-path prepend for a subset of announcements

If one path is unstable (e.g., via a specific edge), prepend to bias traffic away temporarily.

Automation approach:
- Apply a route-map/policy update on the advertising speakers (or RR/edge).
- Validate best-path shift from multiple vantage points.

3) BGP next-hop rewrite (or policy-based next-hop)

When next-hop reachability is the real culprit (e.g., ephemeral node IP changes, ARP/ND instability, or asymmetric return), rewriting next-hop at an aggregation layer can stabilize.

Use cases:
- Nodes advertise service IPs but upstream can’t reliably reach node next-hops during churn.
- You want the fabric to forward to stable anycast gateways instead of transient node next-hops.

Example automation sketch: Ansible to apply a temporary prepend on FRR nodes

This shows the pattern (edit for your FRR config layout and policy names):

yaml
- name: Temporary mitigation - prepend on unstable nodes
  hosts: k8s_bgp_speakers
  become: true
  vars:
    prepend_as: "65001"
    route_map: "RM-TEMP-PREPEND"
  tasks:
    - name: Install route-map snippet (time-bound change)
      copy:
        dest: /etc/frr/frr.conf.d/temp-prepend.conf
        content: |
          route-map {{ route_map }} permit 10
            set as-path prepend {{ prepend_as }} {{ prepend_as }} {{ prepend_as }}
      notify: reload frr

    - name: Ensure route-map applied to neighbor (example)
      lineinfile:
        path: /etc/frr/frr.conf.d/bgpd.conf
        regexp: '^\s*neighbor 10\.0\.0\.1 route-map'
        line: ' neighbor 10.0.0.1 route-map {{ route_map }} out'
      notify: reload frr

  handlers:
    - name: reload frr
      shell: |
        vtysh -c "copy running-config startup-config"
        systemctl reload frr

Validation loop (control + data plane):

bash
# Control plane: session and advertised routes stable?
ssh NODE 'vtysh -c "show bgp summary"'
ssh EDGE 'show bgp ipv4 unicast neighbors X advertised-routes | match SERVICE_PREFIX'

# Data plane: synthetic egress probes from pods (repeat during window)
kubectl -n app exec -it POD -- sh -c 'for i in $(seq 1 20); do date -u +%T; nc -vz -w2 1.1.1.1 443; sleep 1; done'

Rollback:
- Remove the temporary include file / route-map binding.
- Reload FRR.
- Confirm routes return to normal preference and flaps are still understood.


Hardening and prevention

Once you’ve identified the likely culprit (or even if you only have a strong correlation), invest in changes that reduce sensitivity to transient events.

1) Service IP advertisement strategy (“service IPing”)

Common patterns and tradeoffs:

  • Advertise service VIPs from all nodes:
  • Pros: fast failover, simple.
  • Cons: churn during node events, large update volume, ECMP churn upstream.

  • Advertise from a subset (dedicated BGP speakers):

  • Pros: stable control-plane, less churn.
  • Cons: requires careful placement and capacity planning.

  • Aggregate prefixes (where possible):

  • Pros: fewer routes, less churn.
  • Cons: may reduce granularity for traffic steering; requires IP plan alignment.

Concrete actions:
- Use BGP speaker node selectors / affinity to pin advertisements to stable nodes.
- Avoid announcing per-pod routes externally unless you truly need it.
- Ensure external best-path doesn’t depend on frequently changing next-hops.

2) BGP timers, BFD, and keepalive realism

Aggressive timers can turn microbursts (CPU spikes, GC pauses, short packet loss) into session resets.

Checklist:
- Review keepalive/hold timers on both ends.
- If using BFD, confirm it’s provisioned on the actual forwarding path and not CPU-starved.
- Monitor control-plane CPU on TORs and nodes during flap windows.

3) Calico / kube-router / FRR configuration hardening

Examples of practical hardening moves:
- Ensure graceful restart (GR) settings match capabilities; misconfigured GR can prolong blackholes.
- Rate-limit or batch updates if supported, to reduce burstiness during endpoint churn.
- Ensure FRR/BIRD runs with sufficient CPU/memory priority on nodes (avoid eviction/oom).
- Pin BGP speaker pods (if containerized) with priorityClassName and resource requests/limits that reflect reality.

4) Monitoring and alerting to prevent recurrence

Alerts that actually help during flaps:

  • BGP neighbor state changes (rate-based, not just “down”).
  • Route churn rate (updates/withdraws per minute) per neighbor and per prefix-set.
  • Node readiness transitions and CNI daemon restarts.
  • Conntrack pressure (iptables mode), or BPF CT map pressure (eBPF mode).
  • Interface errors/discards and control-plane CPU spikes on TOR/edge.

Tie alerts together with a shared incident timestamp in UTC.

5) Postmortem checklist

Use this to convert findings into durable fixes:

  • What exact prefixes flapped (service VIPs, node podCIDRs, default route)?
  • Were BGP sessions down, or only routes changing?
  • Did the data-plane outage align with:
  • node NotReady
  • CNI restarts
  • BGP daemon restart/crash
  • interface error bursts
  • TOR/edge CPU spikes
  • Was return path consistent (asymmetry evidence in pcaps)?
  • Did any mitigation reduce symptoms? What was the blast radius?
  • What change will prevent recurrence (IP plan, speaker placement, timer tuning, capacity, hardware fix)?
  • What new alert would have detected this earlier?

Common pitfalls

  • Collecting too much tcpdump: large, noisy pcaps without tight filters are hard to analyze and hard to retain.
  • Not using a single time standard: mixing local timezones and clock-skewed devices makes correlation unreliable.
  • Assuming BGP “up” means traffic is fine: you can have stable sessions with broken next-hop reachability or blackholing.
  • Over-aggressive timers/BFD: flaps caused by micro-loss or control-plane starvation look like “random” Kubernetes issues.
  • Automating mitigations without guardrails: route-map mistakes and wide prefix matches can become bigger than the incident.
  • Ignoring dataplane mode: iptables conntrack issues and eBPF CT/map issues require different evidence and fixes.

Key takeaways

  • Troubleshoot BGP flaps by building a single, timestamped timeline across Kubernetes events, BGP control-plane logs, and dataplane captures.
  • Start with tight scope: one pod, one node, one neighbor, one prefix-set—then widen only when evidence demands it.
  • Use python to normalize and correlate events; it turns intermittent, multi-system failures into patterns you can act on.
  • Mitigate safely with time-bound, scoped routing changes and explicit validation loops (control-plane + data-plane).
  • Prevent recurrence by stabilizing advertisement strategy, tuning timers realistically, hardening CNI/BGP components, and alerting on churn—not just “down”.