Bare-Metal IaC, Kubernetes Internals, Edge OTA, and IP Routing

Hard · System Design · Software Engineer · HR Screen

Prompt

You are interviewing for a platform and infrastructure engineering role spanning data-center hardware, container orchestration, remote edge fleets, and network operations. Walk through a cohesive declarative infrastructure architecture—grounded in your own hands-on Infrastructure-as-Code experience and any self-hosted lab environment you run—that unifies physical server lifecycle automation, Kubernetes cluster management, remote device updates, and IP network troubleshooting.

Scope & Expectations

  • Declarative bare-metal & cluster CI/CD: Share a concrete example from your IaC background, then design an automated pipeline to bootstrap and patch physical hosts and Kubernetes clusters—detailing zero-plaintext credential delivery, idempotent operations, and continuous configuration-drift detection.
  • Kubernetes control plane & capacity governance: Explain how Kubernetes controllers drive observed state toward desired state, and cover pod placement, resource requests vs. limits, namespace quotas, pod and cluster autoscaling (HPA, VPA, Cluster Autoscaler), and multi-tenant isolation.
  • Edge firmware delivery & fleet operations: Architect an over-the-air (OTA) update service for distributed field hardware with progressive rollout rings, unbrickable automatic fallback, and health telemetry gating.
  • IP forwarding & hands-on lab validation: Explain how routers select paths (longest-prefix matching and static vs. dynamic protocols), walk through diagnosing silent packet blackholes and asymmetric paths, and connect these concepts to what you practice in a personal homelab.

Step-by-step walkthrough

  1. Clarify scope, scale, and your IaC story

    This question spans five domains—Infrastructure as Code (IaC) for bare metal and Kubernetes, Kubernetes control-plane internals and scheduling, edge fleet Over-The-Air (OTA) firmware updates, IP routing and troubleshooting, and your homelab—all unified by one engineering principle: store declarative desired state in Git, and use idempotent reconciliation loops to drive real hardware toward it. In a 45-minute interview, budget ~12 minutes for bare-metal/cluster IaC, ~10 minutes for Kubernetes internals, ~10 minutes for edge OTA, ~8 minutes for routing, and ~5 minutes for your experience and homelab.

    Assumed production environment (state and confirm up front): - Bare metal: 3 data centers housing 4,000 servers (3,000 8-GPU servers + 1,000 CPU/storage hosts). Every server has a BMC (Baseboard Management Controller)—an independent microcontroller on the motherboard with its own network port on an isolated management network, allowing power control and OS installation even when the main OS is off or crashed. - Kubernetes: 30 clusters across staging and production; the largest runs 1,000 nodes and ~20,000 pods. - Edge fleet: 50,000 Linux devices at customer or field sites behind NAT firewalls on broadband or cellular links, occasionally offline for days.

    Core non-functional requirements: - Git as single source of truth: Every change flows through a pull request (CI plans -> human review -> CD applies in waves). Emergency manual actions require an audited break-glass role. - Turn-up & patching speed: Newly cabled racks go from power-on to in_service in < 4 hours with zero human commands; monthly fleet OS/firmware rollouts keep <= 5% of any cluster unavailable at once. - Security & drift: Zero plaintext secrets in Git; short-lived credentials everywhere; drift detected within 1 hour for security policies (24 hours for general config). - Unbrickable edge updates: Power loss or bad firmware during an OTA update must automatically revert to a working OS slot without a technician visit.

    How to open with your real IaC experience (~2 minutes): Share a real system you owned with concrete before/after metrics and one failure lesson (adapt to your own history; never invent experience). For example: "I migrated ~600 hand-installed bare-metal servers in two data centers to signed immutable OS images driven by an inventory API and split Terraform stacks. Our first scheduled drift scan flagged 14% of network rules as manually edited over prior years, so we spent three weeks importing or reverting them before enabling paging. Rack turn-up dropped from two days to under four hours, and after a resource rename accidentally recreated a load balancer for a 6-minute outage, we enforced moved blocks and a mandatory second approver whenever a saved plan destroys resources."

  2. Back-of-the-envelope numbers and canary math

    1. Bare-metal OS image distribution:
       Signed OS image size          = 4 GB
       500 nodes pulling from one 10 Gbps (1.25 GB/s) image server:
         500 x 4 GB / 1.25 GB/s      = 1,600 s (~27 minutes just waiting on network!)
       Fix: place local HTTP caches per rack row -> central store sends 4 GB once per row (~3.2 s).
    
    2. Monthly rolling reimage cadence:
       4,000 servers / 20 workdays   = 200 servers/day across all clusters.
       In the 1,000-node cluster, a 5% max-unavailable budget = 50 nodes per wave (~30 min/wave:
       drain, iPXE reimage, health check, uncordon) -> 20 waves (~10 hours total spread across the month).
    
    3. Why Terraform state MUST be split:
       20,000 resources in 1 state x 100 ms API refresh / default parallelism 10 = ~200 s per plan,
       plus one global state lock blocking every engineer!
       Splitting by (datacenter, layer) into ~300-resource stacks -> plans finish in < 10 s.
    
    4. Edge OTA bandwidth & telemetry volume (50,000 devices):
       Full rootfs image = 300 MB; binary delta from recent version = ~30 MB (10x smaller).
       Full fleet rollout = 50,000 x 30 MB = 1.5 TB (vs. 15 TB without deltas).
       25% rollout stage (12,500 devices) spread over a 2-hour jitter window (7,200 s):
         12,500 x 30 MB / 7,200 s    = ~52 MB/s (~0.42 Gbps) served easily by a CDN.
       Heartbeats (1 KB every 60 s)  = 50,000 / 60 = ~833 msg/s -> 72M msg/day (~72 GB/day raw).
    

    Statistical intuition for staged canary gates: Suppose healthy edge devices experience unexpected reboots at a 0.5% daily baseline rate: - In a 1% stage (500 devices), we expect 500 × 0.005 = 2.5 random failures. If a buggy firmware quadruples the crash rate to 2.0%, we expect 500 × 0.02 = 10 failures. Setting an automatic halt gate at >= 7 failures triggers a false alarm only ~1.4% of the time when healthy (Poisson tail of mean 2.5), while catching a 2.0% bug ~87% of the time! - However, a subtle regression from 0.5% to 0.7% averages 3.5 vs. 2.5 failures on 500 devices—statistically indistinguishable from noise. By the 25% stage (12,500 devices), 0.5% vs. 0.7% produces 62.5 vs. 87.5 expected failures, more than 3 standard deviations apart (sqrt(62.5) ≈ 7.9). Early small stages protect the fleet from catastrophic bugs; larger later stages with 24–48 hour bake windows catch subtle regressions.

  3. Interfaces, data model, and high-level architecture

    Notice how both bare-metal servers and intermittently offline edge devices use the exact same desired-vs-observed pull pattern: controllers record what version should run, and agents pull their target state whenever reachable.

    Git repositories (declarative source of truth)
      inventory/   Rack layouts, server serials, MACs, BMC IPs, switch ports, IPAM prefixes
      terraform/   Isolated stacks per (datacenter, layer): spine-leaf network, DNS, VIPs, IAM
      images/      Immutable Linux + GPU driver + kubelet OS builds, signed in CI
      clusters/    Cluster API manifests (control-plane versions, node pools, Etcd config)
      gitops/      Kubernetes platform add-ons & tenant namespaces synced per cluster
      firmware/    Signed edge OS images, binary deltas, staged rollout specs
    
    Core APIs
      Inventory    PUT  /v1/servers/{serial}        {desired_state, role, os_digest, fw_baseline}
      Provisioner  POST /v1/servers/{serial}/apply  {os_digest}   (idempotent per serial + digest)
      Edge Fleet   GET  /v1/devices/{id}/desired    -> {release, delta_url, full_url, sig, window}
                   POST /v1/devices/{id}/report     {running_ver, active_slot, boot_count, metrics}
                   POST /v1/rollouts/{id}/action    {action: "pause" | "resume" | "abort"}
    

    Data model:

    servers          serial PK, site, rack, bmc_ip, macs, role, desired_state, observed_state,
                     desired_os_digest, observed_os_digest, fw_baseline, last_heartbeat
    terraform_state  One encrypted, versioned remote state + lock per (datacenter, layer)
    devices          device_id PK, hw_rev, tpm_pubkey_fp, cohort_bucket (hash(device_id) % 10000),
                     desired_version, reported_version, active_slot ("A" | "B"), last_seen_at
    releases         version PK, hw_rev, full_sha256, delta_map, signature, min_security_ver
    rollouts         rollout_id PK, version, current_stage_pct, gate_status, state
    heartbeats       Time-series: (device_id, ts) -> version, slot, boot_reason, cpu_temp, rss, rssi
    

    Hashing device_id modulo 10,000 assigns every device a permanent cohort_bucket (0..9999), ensuring the "first 1%" (0..99) is a deterministic, reproducible canary group across releases.

      Engineers --PR--> [ Git ] --> [ CI: lint, OPA policy, terraform plan, build & sign images ]
                                                    |
                                      saved plan + 2nd approver for destroys
                                                    v
                               [ CD Orchestrator (wave-by-wave rollout) ]
             +-----------------------+------------------------+-----------------------+
             v                       v                        v                       v
      [ Terraform Stacks ]   [ Metal Provisioner ]    [ Cluster API ]        [ GitOps Sync ]
      BGP/VLANs, DNS, IPAM   Redfish -> BMC firmware  Upgrades 30 K8s        Syncs add-ons &
                             iPXE + row HTTP caches   control planes & pools apps per cluster
                                     |                        |                       |
                                     +----------> [ 4,000 Bare-Metal Servers -> 30 K8s Clusters ]
      [ Secret Manager (HA) ] <--- OIDC short-lived tokens (CI), KMS etcd encryption, TPM join
      [ Drift Detector ]      <--- Hourly read-only plans + GitOps diffs + host digest agents
    
      Edge OTA Pipeline:
      [ Release CI + HSM Signer ] -> [ CDN (30 MB deltas) ]    [ Rollout Controller & Gate Eval ]
                                            ^                                  |
      [ 50k Edge Devices (A/B slots) ] -----+-- mTLS HTTPS pull + MQTT notify -+-> [ Telemetry TSDB ]
    
  4. Bare-metal and cluster CI/CD: immutable images and wave rollouts

    Zero-touch bare-metal state machine: Each physical server progresses through deterministic states driven by the provisioner talking Redfish (a standard HTTPS/JSON management protocol exposed by BMCs) and iPXE (network firmware that boots an OS installer over HTTP):

    racked -> discovered -> fw_baselined -> burned_in -> os_imaged -> joined -> in_service
      BMC gets   Match serial  Redfish flashes  Memtest +   iPXE streams  TPM/token   Uncordoned
      DHCP IP    to inventory  BIOS/BMC/NIC/GPU NVLink/GPU  signed 4 GB   authenticates in K8s
                               to exact digest  stress test image via row & joins K8s  cluster
                                                            HTTP cache
    

    If burn-in or imaging fails (e.g., bad RAM DIMM or GPU PCIe link drop), the server transitions cleanly to maintenance and files a hardware RMA ticket—never entering a cluster half-configured.

    Immutable OS images over in-place mutation: Instead of running apt upgrade over years—which creates irreproducible "snowflake" servers—CI bakes the Linux kernel, NVIDIA drivers, containerd, and kubelet into a single immutable, signed image identified by SHA-256 digest. Monthly patching is a rolling reimage (cordon -> drain respecting PodDisruptionBudgets -> Redfish reboot to iPXE -> health check -> uncordon), capping unavailable nodes at 5% per cluster.

    CI/CD safety & Kubernetes upgrade order: 1. Plan-then-apply lockstep: On PR open, CI runs formatters, Open Policy Agent (OPA) rules (e.g., reject 0.0.0.0/0 SSH rules), and terraform plan -out=plan.bin. On merge, CD applies that exact saved plan.bin under a per-stack lock; if live state changed meanwhile, apply aborts safely and re-plans. Any plan containing resource deletions requires a second senior approver, and resource renames use declarative moved blocks. 2. Progressive promotion waves: Every infra, OS, or cluster change rolls out lab -> staging DC -> 1 canary rack / canary cluster -> production waves (5% -> 25% -> 100%), halting automatically if SLO error budgets or node readiness degrade. 3. Kubernetes version rules: Run 3 or 5 etcd quorum nodes (odd counts: 3 survives 1 failure, 5 survives 2). Upgrade one minor version at a time (1.30 -> 1.31): etcd and kube-apiserver first, then controller-manager/scheduler, then rolling node-pool reimages (Kubernetes' version-skew policy allows kubelet to be up to 3 minor versions older than kube-apiserver, never newer).

  5. Zero-plaintext credentials, idempotent execution, and drift control

    Secrets lifecycle without static keys: - Zero plaintext in Git: Git stores only secret path references (synced by the Kubernetes External Secrets Operator) or KMS-encrypted envelopes (SOPS) decryptable only by production CD identities. - OIDC federation in CI/CD: Instead of storing long-lived cloud or Vault tokens in CI variables, the CI runner presents a short-lived signed OIDC (OpenID Connect) JWT proving repo + protected_branch + job_environment to the secret manager in exchange for a 15-minute credential. - Solving "secret zero" on bare metal: A brand-new server has no credentials on disk. Best practice verifies the server's hardware TPM (Trusted Platform Module) endorsement key recorded at factory/intake; otherwise, the provisioner issues a single-use, 1-hour join token bound to (serial, MAC) delivered only over the isolated provisioning VLAN. Factory-default BMC passwords are rotated to unique per-server secrets during discovered. - At-rest & zero-downtime rotation: Kubernetes Secrets are encrypted at rest in etcd via a KMS plugin, Terraform state buckets enforce KMS encryption and strict IAM (because state files can hold generated credentials), and secret rotation uses a dual-credential overlap window (create Key B → deploy consumers reading Key B → verify zero Key A traffic → revoke Key A).

    Idempotency: An operation is idempotent if running it once or ten times yields the exact same system state without unintended side effects. - Declarative tools (Terraform, Kubernetes) are naturally idempotent; CI verifies this in the lab by running apply followed immediately by plan and asserting an empty diff. - Imperative hardware steps (BIOS flash, disk wipe) are wrapped in check-then-act guards keyed by (serial, target_digest): query BMC firmware version first and return success if already matching; refuse to wipe disks if the server's state is already in_service unless an explicit reimage ticket token matches. Avoid timestamps or random_id calls inside templates that create perpetual fake diffs.

    Automated drift detection: Drift occurs when live infrastructure diverges from Git (for instance, an engineer hot-fixes a switch ACL during an outage). Detect it across all three layers:

    import subprocess
    
    
    def check_terraform_drift(stack_dir: str) -> tuple[str, str]:
        """Run an hourly read-only Terraform plan using -detailed-exitcode.
    
        Exit codes: 0 = clean (zero diff), 1 = error, 2 = drift detected!
        """
        proc = subprocess.run(
            [
                "terraform",
                "plan",
                "-detailed-exitcode",
                "-input=false",
                "-lock=false",
                "-no-color",
            ],
            cwd=stack_dir,
            capture_output=True,
            text=True,
        )
        if proc.returncode == 0:
            return ("in_sync", "")
        if proc.returncode == 2:
            return ("drift_detected", proc.stdout)
        return ("plan_error", proc.stderr)
    

    Pair hourly Terraform drift scans with continuous GitOps cluster diffs and host telemetry agents reporting (os_digest, kernel_ver, bios_ver). Remediate by risk class: auto-revert stateless K8s app manifests, page and open a PR/ticket for stateful network/firewall changes (so an active break-glass mitigation isn't blindly reverted mid-incident), and cordon + reimage drifted hosts.

  6. Kubernetes internals: level-triggered reconciliation

    Kubernetes is not a traditional imperative orchestrator; it is a database (etcd fronted by kube-apiserver) watched by independent controllers, each running an infinite reconciliation loop that drives status (observed reality) toward spec (desired state).

    User / GitOps writes spec ---> [ kube-apiserver (etcd) ]
                                        |          ^
                       1. List + Watch  |          | 4. Create/Delete Pods & update status
                                        v          |    (with resourceVersion concurrency check)
                               [ Informer Local Cache ]
                                        |
                       2. Enqueue "ns/name" (deduplicated!)
                                        v
                           [ Rate-Limited Work Queue ] ---> 3. Worker runs reconcile("ns/name")
    

    Crucially, Kubernetes controllers are level-triggered, not edge-triggered: - An edge-triggered system reacts to an event payload ("pod-3 died → start 1 pod"); if the network drops that single event, capacity stays broken forever. - A level-triggered controller wakes up on any change (or periodic resync), reads the entire current state ("desired = 5, currently alive = 3 → create 2 pods"), and takes idempotent steps to close the gap.

    Key controller mechanics: - Shared Informers & Work Queues: Controllers never poll kube-apiserver in tight loops; an Informer runs one initial LIST followed by a streaming WATCH to maintain an in-memory cache. Watch callbacks push only the object key "namespace/name" into a deduplicating queue—if an object changes 10 times in 50 ms, the worker reconciles the latest cached state once. - Optimistic concurrency (resourceVersion): Every write includes the object's version stamp; if another actor modified the object concurrently, kube-apiserver rejects the write with 409 Conflict and the worker simply re-queues the key. - Garbage collection & expectations: Child pods carry ownerReferences pointing to their ReplicaSet so Kubernetes deletes children automatically, while finalizers block deletion until external resources (like cloud load balancers) are cleaned up. Real controllers also track in-flight expectations ("I just asked the API server to create 2 pods; wait until my Informer cache observes those 2 creations before reconciling again") so stale cache reads never double-create pods.

    def reconcile_replicaset(key: str, informer_cache, k8s_api) -> None:
        """Drive actual non-terminating pod count toward spec.replicas (level-triggered)."""
        rs = informer_cache.get_replicaset(key)
        if rs is None:
            # Object was deleted; Kubernetes garbage collector cleans up owned pods.
            return
    
        live_pods = [
            pod for pod in informer_cache.list_pods_owned_by(key)
            if pod.deletion_timestamp is None
        ]
        diff = rs.spec_replicas - len(live_pods)
    
        if diff > 0:
            for _ in range(diff):
                k8s_api.create_pod(template=rs.pod_template, owner_ref=key)
        elif diff < 0:
            # Scale down unscheduled/unready/newest pods first to minimize disruption.
            victims = sorted(live_pods, key=lambda p: (p.is_ready, p.created_at))[: -diff]
            for victim in victims:
                k8s_api.delete_pod(victim.name)
    
        # Record what we actually observed right now, plus which spec version we processed.
        k8s_api.update_status(
            key,
            ready_replicas=sum(1 for p in live_pods if p.is_ready),
            observed_generation=rs.metadata_generation,
        )
    
    
    def worker_loop(work_queue, informer_cache, k8s_api) -> None:
        while True:
            key = work_queue.get()  # Blocks; duplicate bursts collapse to one key
            try:
                reconcile_replicaset(key, informer_cache, k8s_api)
                work_queue.forget(key)  # Reset exponential backoff on clean run
            except Exception:
                work_queue.add_rate_limited(key)  # Re-queue with exponential backoff
            finally:
                work_queue.done(key)
    
  7. Kubernetes workload management, autoscaling, and multi-tenancy

    • Scheduling (kube-scheduler): Runs a two-phase pipeline for each unbound pod: Filter eliminates invalid nodes (insufficient unrequested CPU/RAM/GPU, mismatched nodeAffinity, untolerated node taints), and Score ranks surviving nodes (zone/rack topologySpreadConstraints, bin-packing vs. spreading, cached container images) before binding. Distributed multi-node GPU jobs require gang scheduling (via Kueue or Volcano) so 16 pods are placed all-or-nothing instead of deadlocking two half-filled 8-GPU jobs.
    • Requests, limits, and QoS classes: Requests reserve capacity in the scheduler; limits enforce kernel cgroup ceilings at runtime. Exceeding a CPU limit triggers CFS throttling (adding tail-latency spikes without killing the pod); exceeding a memory limit triggers an immediate kernel OOM-kill. Kubernetes derives three eviction Quality of Service (QoS) tiers: Guaranteed (requests == limits for all resources), Burstable, and BestEffort (evicted first under node memory pressure). Best practice for latency-critical services: set memory request == memory limit (prevents surprise evictions), set accurate CPU requests, and omit CPU limits (avoiding throttling spikes when spare cores exist). GPUs (nvidia.com/gpu) cannot be overcommitted (request == limit, whole integers).
    • Quotas & defaults: Enforce per-namespace ResourceQuota (capping aggregate CPU, RAM, GPUs, and object counts) paired with a LimitRange (injecting sane default requests/limits so pods without specs aren't rejected).
    • HPA, VPA, and Cluster Autoscaler:
      • HPA (Horizontal Pod Autoscaler): Scales replica count every 15 s via desired = ceil(current × current_metric / target_metric) with a 5-minute scale-down stabilization window; requires resource requests if scaling on % CPU, though custom queue-depth or RPS metrics react much faster.
      • VPA (Vertical Pod Autoscaler): Adjusts per-pod CPU/memory requests based on historical usage (recreating pods to resize). Never run HPA and VPA together on CPU/memory—they fight each other; use VPA in recommendation-only mode or pair VPA with custom-metric HPA.
      • Cluster Autoscaler: Provisions nodes when pods sit Pending (Unschedulable) and drains underutilized nodes (< 50% requested for 10 min) while honoring PodDisruptionBudgets. Because bare-metal PXE boot takes minutes, keep an overprovisioned "pause-pod" warm buffer.
    • Multi-tenancy: Soft multi-tenancy isolates trusted internal teams via namespaces, RBAC, ResourceQuota, default-deny NetworkPolicy, PodSecurity (restricted), and API Priority and Fairness (preventing one runaway client from starving kube-apiserver). Hard multi-tenancy for untrusted external code uses dedicated clusters per tenant (via Cluster API) or microVM sandboxes (Kata/gVisor) on tainted dedicated nodes.
  8. Edge fleet OTA updates: A/B slots, staged rollouts, and telemetry

    Field devices sit hours from technicians behind lossy cellular links, so an interrupted or buggy update must never brick a unit.

    Atomic A/B rootfs + hardware watchdog rollback:

    +--------------------+--------------------+----------------------+--------------------+
    | Bootloader + Env   | Root Slot A (ro)   | Root Slot B (ro)     | Persistent /data   |
    | active=A, tries=0  | v41 (known good)   | v42 (newly written)  | backward-compat DB |
    +--------------------+--------------------+----------------------+--------------------+
    Update flow:
      1. Agent on Slot A streams 30 MB delta (HTTP Range resumable), reconstructs v42 into Slot B,
         and verifies SHA-256 + offline-anchored cryptographic signature.
      2. Sets bootloader flags: try_slot=B, boot_tries_remaining=3 -> reboots.
      3. Hardware watchdog arms a 10-minute timer. Only after OS + network + app health pass
         does the agent mark Slot B "committed". Three failed boots auto-revert active=A!
    

    Crucial rule: /data schemas must remain backward-compatible across adjacent versions so Slot A can still read /data if Slot B crashes mid-run and rolls back.

    Cryptographic trust & anti-rollback tension: Updates follow TUF (The Update Framework) principles: an offline root key signs rotating release keys stored in a Hardware Security Module (HSM), and signed metadata includes an expiration timestamp so an attacker intercepting traffic cannot freeze a device on an old vulnerable version forever. Hardware anti-rollback counters (TPM / eFuses) block downgrading below a minimum security_version—because bumping that fuse permanently forbids rolling back to prior releases, increment security_version only for critical security patches after the new release has baked cleanly at 100%.

    Staged cohort rollout & control-group telemetry: - Devices connect via mutual TLS (keys inside hardware TPM), receive lightweight MQTT wake-up pokes, and pull artifacts from a CDN within site maintenance windows with random jitter and bandwidth caps. - Progress through lab (100, 4h) -> dogfood (500, 24h) -> 1% (500, 24h) -> 5% (2,500, 24h) -> 25% (12,500, 48h) -> 100%. - Control-group gating: Every gate compares updated cohort devices against un-updated control devices in the exact same time window and region. If a regional cellular carrier suffers an outage, heartbeats drop equally in both cohorts, preventing false firmware rollbacks; if watchdog rollbacks or crash rates spike only in the updated cohort, the controller pauses automatically.

  9. IP routing tables, blackholes, and asymmetric routing

    How a router picks a path (strict priority order): 1. Longest-Prefix Match (LPM) ALWAYS wins first: Among every route whose CIDR subnet contains the destination IP, the router selects the most specific prefix (largest /N mask), regardless of which protocol learned it. A static or OSPF /24 always beats a BGP /16, which beats /8, which beats 0.0.0.0/0. 2. Administrative Distance (AD): Only when multiple sources advertise the exact same /N prefix (e.g., both static and BGP offer 10.20.30.0/24), the router picks the most trusted source (connected 0 < static 1 < eBGP 20 < OSPF 110 < iBGP 200). 3. Protocol Metric & ECMP: Within the same protocol and prefix, lowest cost/AS-path wins; exact ties share traffic via ECMP (Equal-Cost Multi-Path), hashing each packet's 5-tuple (src_ip, dst_ip, proto, src_port, dst_port) so packets of a single TCP stream stay ordered on one link.

    import ipaddress
    
    SampleRoutes = [
        ("0.0.0.0/0", "203.0.113.1"),      # Default route (/0)
        ("10.0.0.0/8", "192.168.1.1"),     # Corporate summary (/8)
        ("10.20.0.0/16", "192.168.1.2"),   # Site prefix (/16)
        ("10.20.30.0/24", "192.168.1.3"),  # Rack VLAN (/24)
    ]
    
    
    def longest_prefix_lookup(dest_ip: str, routes: list[tuple[str, str]]) -> str | None:
        """Select the next hop whose matching CIDR network has the largest prefix length."""
        target = ipaddress.ip_address(dest_ip)
        best_prefix_len = -1
        chosen_next_hop = None
    
        for cidr, next_hop in routes:
            net = ipaddress.ip_network(cidr)
            if target in net and net.prefixlen > best_prefix_len:
                best_prefix_len = net.prefixlen
                chosen_next_hop = next_hop
        return chosen_next_hop
    

    In this table, 10.20.30.7 matches all four prefixes and picks /24 (192.168.1.3); 8.8.8.8 matches only /0 (203.0.113.1). Software routers use compressed radix tries (Linux ip route get <ip>) and hardware switches use parallel TCAM memory for single-cycle lookups.

    Static vs. dynamic routing: Static routes are simple and deterministic for stub edges, but blind to upstream failures beyond the immediate link unless paired with BFD (Bidirectional Forwarding Detection) probes. Inside our data centers, a leaf-spine fabric runs eBGP with ECMP and BFD (Kubernetes nodes advertise pod/service VIPs to top-of-rack switches via Calico/MetalLB BGP), protected by strict prefix filters and max-prefix caps to block route leaks.

    Troubleshooting blackholes (silent packet drops): 1. Isolate the pattern: Do all packets fail (missing/null route), ~1/N of TCP flows fail (one degraded link inside an N-way ECMP group—vary --sport in mtr -T -P 443 to hit each link), or do small packets succeed (ssh login banner) while large transfers hang (scp, TLS certificates)? 2. RIB vs. FIB & Null0: On the last responding hop, run ip route get / show ip route (Control-Plane RIB) AND check hardware forwarding entries (FIB) plus neighbor ARP tables and summary Null0 discard routes. 3. MTU blackhole: Overlay tunnels like VXLAN add 50 bytes of headers, shrinking inner MTU from 1500 to 1450. If a firewall blocks ICMP Type 3 Code 4 (Fragmentation Needed), Path MTU Discovery silently stalls. Prove it with ping -M do -s 1472 <dst> (1472 + 20 IP + 8 ICMP = 1500 bytes) vs -s 1400; fix by permitting ICMP packet-too-big, aligning MTUs, and clamping TCP MSS.

    Troubleshooting asymmetric routing:

      Client ---> [ Router 1 ] ---> [ Stateful Firewall A (records TCP SYN) ] ---> Server (eth0)
      Client <--- [ Router 2 ] <--- [ Stateful Firewall B (NO session! DROPS SYN-ACK) ] <--- Server (eth1 default gw)
    

    Asymmetry is harmless on stateless core routers, but breaks stateful firewalls/NATs (Firewall B never saw the outbound SYN and drops the returning SYN-ACK) and hosts with strict reverse-path filtering (rp_filter=1) (Linux drops packets arriving on eth0 if its routing table says replies to that source leave via eth1). Diagnose with bidirectional mtr plus tcpdump -ni any on the server (watching packets enter eth0 and exit eth1) and nstat (IPReversePathFilter counter). Fix with source-based policy routing (ip rule add from <eth0_ip> table 100 so replies exit the interface they entered), active/active state-synced firewall pairs, symmetric BGP LOCAL_PREF/MED policy, or loose mode rp_filter=2 on intentionally multi-path interfaces.

  10. Homelab blueprint, failure matrix, and key trade-offs

    A strong homelab proves you have built, broken, and debugged these exact mechanisms end to end (while candidly noting production differences like offline HSMs, multi-engineer PR gates, and redundant utility feeds):

    Hardware     3 mini x86 servers + 2 Raspberry Pis + VLAN-capable switch + Linux FRR BGP router
    Bare metal   iPXE + unattended Git repo rebuilds the entire lab from bare disks in < 45 minutes
    Kubernetes   3-node HA control plane + etcd, Flux/Argo GitOps, KMS-encrypted secrets, MetalLB
                 peering eBGP with FRR so `show ip bgp` displays live cluster LoadBalancer /32s
    Networking   Isolated Mgmt / Cluster / Edge VLANs, WireGuard VPN, policy-routing rule on dual-NIC host
    Edge OTA     Pis running A/B root slots + hardware watchdog; inject a deliberately broken daemon
                 to verify 3-boot automatic fallback and Prometheus alert firing
    

    Fleet failure summary & key trade-offs: - Bad IaC / OS rollout: Halts at canary rack/cluster wave; git revert re-runs the idempotent pipeline. - Etcd quorum loss or Secret Manager outage: Restore etcd from tested hourly object-store snapshots (5-node HA tolerates 2 losses); workloads run on cached secrets whose lease TTL exceeds recovery time. - Key trade-offs: Immutable reimaging vs. live patching trades spare 5% surge capacity for zero configuration drift; split Terraform states vs. monostate trades cross-stack output wiring for < 10 s plans and isolated blast radius; omitting CPU limits vs. setting limits trades strict noisy-neighbor caps for predictable p99 latency; and multi-day staged edge rollouts + cautious anti-rollback fuses trade deployment velocity for never bricking 50,000 remote devices.

Intuition & how it works

Think of operating 4,000 bare-metal servers, 30 Kubernetes clusters, and 50,000 remote edge devices like replacing thousands of manual wall switches with smart thermostats, paired with a postal zip-code sorter for the network. If you manage rooms by sending one-off commands ("turn heater on for 10 minutes"), a single dropped network packet or reboot leaves a machine stuck in the wrong state forever. A thermostat instead runs a level-triggered reconciliation loop: Git stores the desired temperature (70°F), and each local controller continuously compares desired state against observed reality, nudging hardware toward the target until the difference is zero. Meanwhile, IP routers forward packets like postal sorters that always obey the longest-prefix match—a rule for a specific street block (10.20.30.0/24) always overrides a rule for the whole city (10.20.0.0/16) or country (0.0.0.0/0), no matter who wrote the rule.

A naive script-driven approach collapses quickly at fleet scale. Running SSH upgrade scripts in place turns servers into unique "snowflakes" with drifted kernels, wipes live disks if a failed job retries without an idempotency guard, locks all engineers behind one 20,000-resource Terraform state file, and bricks remote cellular edge devices the first time power drops mid-download. On the network side, checking traceroute from only one end misses asymmetric routing—where requests go out through Firewall A and replies return through Firewall B, which has no record of the connection and silently drops every reply.

Trace four concrete events across this architecture to see how every piece reinforces the others: 1. Bare-metal wave rollout: An engineer merges a pull request bumping the signed OS image digest. CI saves an exact plan.bin, and CD drains 5% (50 nodes) of a cluster, instructs each server's BMC (Baseboard Management Controller, an independent management chip on the motherboard) via Redfish to network-boot the 4 GB image from a local rack-row HTTP cache, verifies GPU health, and uncordons the nodes before touching the next wave. 2. Kubernetes level-triggered self-healing: While 2 nodes reimage, a ReplicaSet controller wakes up from its local Informer cache, compares spec.replicas = 20 against 18 observed live pods, and asks kube-apiserver to create 2 replacement pods—even if individual pod-delete events were delayed or coalesced in its deduplicating work queue. 3. Unbrickable edge A/B fallback: A cellular edge device pulls a 30 MB binary delta into inactive Slot B and reboots with a 3-try boot counter and a 10-minute hardware watchdog timer. When a bug crashes the daemon on all 3 tries, the bootloader automatically falls back to untouched Slot A, reports the rollback event, and trips the >= 7 failure gate on the 500-device (1%) canary cohort before 99% of the fleet ever downloads the bad build. 4. Routing lookup & symmetry: A server at 10.20.30.7 receives a client packet via /24 longest-prefix match on eth0; a Linux source-based policy rule (ip rule) ensures the reply exits eth0 back through the same stateful firewall rather than drifting out eth1's management default gateway.

Key trade-offs

  • Immutable OS reimaging vs. in-place package updates. Baking the kernel, GPU drivers, and kubelet into a single signed image and rolling-reimaging nodes requires ~5% spare cluster surge capacity and ~30 minutes per wave, but guarantees every server matches a single cryptographic digest and makes rollback trivial. In-place configuration management applies tiny tweaks faster but accumulates hidden state drift over years.
  • Split Terraform states vs. a single monolithic state. Partitioning Terraform by (datacenter, layer) into small ~300-resource stacks keeps terraform plan under 10 seconds and confines lock contention and mistakes to one subsystem, at the cost of managing explicit cross-stack outputs and multi-stage pipelines.
  • Declarative self-healing vs. alert-only drift detection. Having GitOps automatically overwrite manual cluster edits eliminates configuration drift within minutes, whereas critical firewall or routing layers use alert-only drift mode so an operator's emergency break-glass mitigation is not blindly undone mid-incident before being codified in a pull request.
  • Secret manager at runtime vs. KMS-encrypted files in Git. A central secret manager issuing short-lived dynamic credentials via OIDC (OpenID Connect identity tokens) minimizes leak blast radius and enables instant revocation, but introduces a high-availability runtime dependency; KMS-encrypted Git files have zero runtime dependencies for bootstrap config but require commits to rotate. Combining KMS-encrypted bootstrap config with a runtime secret manager captures the best of both.
  • Kubernetes CPU limits vs. unthrottled CPU requests. Enforcing hard CPU limits prevents noisy neighbors from using idle cores, but triggers kernel CFS throttling pauses that inflate p99 tail latency even on half-idle hosts; latency-critical services set accurate CPU requests without CPU limits while always enforcing memory request == memory limit (Guaranteed-style memory safety).
  • Edge rollout velocity vs. statistical detection & rollback safety. A 6-stage rollout with 24–48 hour bakes takes ~1 week per firmware release, because a 500-device (1%) canary can statistically catch a jump from 0.5% to 2.0% crashes (~87% power) while catching a subtle 0.5% → 0.7% bug requires 12,500 (25%) devices. Similarly, delaying hardware anti-rollback fuse bumps until a security patch is proven at 100% preserves operational rollback during rollout.
  • Static vs. dynamic routing. Static routes add zero control-plane complexity at network edges but blackhole traffic if an upstream path fails beyond the immediate next hop; eBGP dynamic routing with BFD (Bidirectional Forwarding Detection sub-second keepalives) fails over automatically across leaf-spine paths, requiring strict prefix filters so a misconfiguration does not propagate fleet-wide.

Common mistakes

  • Applying a fresh terraform apply on merge instead of the reviewed plan.bin artifact, allowing unreviewed concurrent changes or surprise resource deletions to slip into production.
  • Storing long-lived cloud or BMC credentials in CI variables or plaintext Git, or forgetting that Terraform state files themselves can contain cleartext secrets if unencrypted and broadly readable.
  • Writing imperative provisioning scripts (disk wipes, BIOS flashes) without check-then-act idempotency guards, causing a retried job to wipe an already-joined production node.
  • Describing Kubernetes controllers as event-driven ("reacting to each event") rather than level-triggered, and overlooking Informer cache lag (where creating pods without tracking in-flight expectations causes duplicate pod creation on back-to-back reconciles).
  • Enabling HPA and VPA simultaneously on CPU or memory, causing the two autoscalers to thrash against each other, or configuring percentage-based HPA on pods that declare no resource requests.
  • Shipping single-partition in-place edge updates or bumping anti-rollback fuses on every release, either of which turns a bad release or mid-write power outage into thousands of physically bricked field units.
  • Evaluating OTA canary failure rates against last week's historical average instead of a live un-updated control cohort in the same time window, causing regional ISP outages to look like bad firmware (or masking real bugs during quiet traffic hours).
  • Thinking administrative distance overrides longest-prefix match (a dynamic BGP /24 always beats a static /16), blocking all ICMP packets (which breaks Path MTU Discovery across 1450-byte VXLAN tunnels and causes silent hangs on large TLS/SCP packets), or running traceroute from only one side when diagnosing asymmetric stateful-firewall drops.

Follow-up questions

  • How would you roll out a minor Kubernetes version upgrade across all 30 clusters without tenant downtime? First run automated static checks (such as pluto/kubent and API server audit-log scans) against every GitOps repo and live cluster to replace deprecated API versions before upgrading. Upgrade one minor version at a time (1.30 → 1.31), starting with a dev cluster, then a staging canary cluster, and finally production clusters in waves (never two clusters backing the same multi-cluster service simultaneously): take an etcd snapshot first, upgrade etcd and kube-apiserver, upgrade core add-ons (CNI, CoreDNS, CSI), and roll worker pools via surge bare-metal reimaging while honoring PodDisruptionBudgets. Bake the canary cluster for 48–72 hours watching API error rates, scheduling latency, and tenant SLOs before proceeding.
  • A bare-metal GPU host alternates between Ready and NotReady every few minutes—how do you isolate the root cause? Start with kubectl describe node and API events to see whether kubelet actively reports MemoryPressure/DiskPressure/PIDPressure or whether NodeStatusUnknown appears because heartbeats timed out. SSH or connect via BMC serial-over-LAN to inspect journalctl -u kubelet -u containerd and dmesg -T for kernel OOM-kills, hung NVMe I/O, clock skew (NTP/Chrony), or GPU/PCIe bus lockups, and check whether unthrottled pods starved kubelet of CPU (solved via systemReserved / kubeReserved cgroups). If the host itself is healthy during flaps, correlate flap timestamps with top-of-rack switch port counters and ECMP paths to kube-apiserver—one lossy link in an ECMP group will intermittently drop kubelet lease renewals; once confirmed hardware-related, cordon, drain, and transition the server to maintenance in the inventory.
  • What is your incident response plan if the edge OTA firmware signing key is compromised? Immediately halt active rollouts and use the offline root key (kept air-gapped outside the CI/HSM network) to publish new signed root/targets metadata revoking the compromised signing key and rotating trust to a fresh HSM key, then re-sign known-good releases. Note that incrementing the hardware anti-rollback version alone does not stop an attacker who possesses a valid signing key, because the attacker could sign malicious firmware with a higher version number—revoking the signing key via the offline root key is what blocks unauthorized images. Finally, query fleet telemetry for any device reporting an observed_digest or boot measurement not matching your official release ledger, quarantine its mTLS client certificate at the gateway, and dispatch physical re-flashing for any unit whose runtime agent can no longer be trusted.

Follow-up questions

Similar questions

More Lambda interview questions

All 2 Lambda questions →