RecapsKayavak

Kayavak / Recaps / Infrastructure

Recaps · Volume 6

Infrastructure

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

79

Linux

Key ideas

  • Shape: kernel, init (systemd), userland; the filesystem hierarchy (/etc, /var, /usr, /proc, /sys, /run, /tmp).
  • Permissions: users, groups, mode bits, setuid/setgid/sticky, umask, ACLs, capabilities, root and sudo, SELinux/AppArmor.
  • Processes: fork/exec, PIDs and parents, states (R, S, D, Z, T), signals, exit codes (128 + signal), zombies and reaping, nice and priorities.
  • systemd: units, services (Type=, Restart=, User=, limits, sandboxing directives), timers, targets, journalctl.
  • Environment: variables, shells, PATH, config files and secrets handling.
  • Logs: journald, syslog, log rotation, structured logs to stdout for containers.
  • Networking: interfaces, routes, DNS (/etc/resolv.conf), ports and sockets, ss, ip, curl, dig, tcpdump, firewalls (nftables/iptables), TCP states.
  • Packages: apt/dnf, repositories, pinning, unattended upgrades.
  • Storage: block devices, partitions, filesystems (ext4, XFS), mounts and fstab, LVM, page cache, fsync, inodes.
  • Diagnostics: top, vmstat, iostat, mpstat, pidstat, PSI, strace, perf, eBPF tools (bcc, bpftrace), the USE method.

Numbers to remember

  • Exit 137 = SIGKILL (often OOM); 143 = SIGTERM.
  • TIME_WAIT lasts 60 s on Linux; default ephemeral range ~28k ports.
  • Lab: page cache made a 1 GB read 3.8× faster; O_DSYNC writes 45× slower than buffered; fd exhaustion at the soft limit; load 3.2 and rising with 4 busy loops on 2 CPUs.

Pitfalls

  • Services running as root.
  • Low nofile limits on busy servers.
  • Reading "free" memory instead of "available".
  • Assuming write() means durable.
  • Logs filling the disk without rotation.
  • Ignoring SIGTERM, so every restart drops requests.

Glossary

  • inode: a file's metadata record; directories map names to inodes.
  • Page cache: kernel RAM cache of file contents.
  • Load average: running + runnable (+ uninterruptible) tasks, averaged.
  • PSI: pressure stall information, time tasks wait for CPU, memory or I/O.
  • Capability: a slice of root's power (e.g. CAP_NET_BIND_SERVICE).
  • Unit: a systemd-managed object (service, timer, socket, mount…).

80

Containers

Key ideas

  • Container vs VM: shared kernel, process-level overhead, kernel-enforced isolation vs hypervisor isolation; sandboxed runtimes in between.
  • Namespaces: pid, net, mnt, uts, ipc, user, cgroup, time.
  • cgroups: v1 (controller hierarchies) vs v2 (unified, memory.max, cpu.max, PSI); memory (limit, OOM), CPU (shares/weight, quota/period), pids, io.
  • Confinement: capabilities, seccomp, AppArmor/SELinux, read-only root, no-new-privileges, rootless and user namespaces.
  • Images: layers, manifests, config, digests, multi-arch indexes; OCI image spec.
  • Registries: OCI distribution API, tags vs digests, mirrors and pull-through caches.
  • Runtime stack: CLI/kubelet → containerd/CRI-O → shim → runc/crun → kernel; CRI.
  • Storage: overlayfs copy-on-write, volumes, bind mounts, tmpfs.
  • Networking: veth pairs, bridges, NAT and port publishing, host and none modes, CNI.
  • Runtimes in containers: memory sizing (JVM, Node, Go, Python), CPU counts, PID 1 signal handling and zombie reaping (tini).

Numbers to remember

  • --cpus 0.5 = quota 50 ms per 100 ms period.
  • Lab: namespaces cost ~2 ms; docker run --rm ~330 ms; a 0.5-CPU busy loop was throttled in 111/112 periods; JVM default heap was 126 MB in a 256 MB cgroup (192 MB at MaxRAMPercentage=75).

Pitfalls

  • Treating containers as a security boundary for untrusted code.
  • Running as root inside without user namespaces.
  • CPU limits on latency-sensitive services without watching throttling.
  • Runtimes sized for the host, not the container.
  • Writing data into the container's writable layer.
  • A shell script as PID 1 that doesn't forward SIGTERM.

Glossary

  • Namespace: kernel-provided isolated view of a resource type.
  • cgroup: kernel resource accounting and limiting group.
  • CFS quota: CPU time allowed per period for a cgroup.
  • overlayfs: union filesystem merging read-only and writable layers.
  • OCI: Open Container Initiative standards.
  • Whiteout: marker hiding a lower-layer file deleted in an upper layer.

81

Docker

Key ideas

  • Dockerfile: FROM, WORKDIR, COPY/ADD, RUN, ENV, ARG, USER, EXPOSE, ENTRYPOINT/CMD (exec vs shell form), HEALTHCHECK, LABEL.
  • Layers and cache: content-addressed layers; a cache miss invalidates later steps; order by change frequency; cache mounts; remote cache export/import.
  • Multi-stage builds: build and runtime stages; scratch, distroless, slim and Wolfi bases; static vs dynamic binaries.
  • Tags and registries: tags are mutable, digests immutable; pin bases by digest; multi-arch indexes; private registries and mirrors.
  • Running: ports, volumes and bind mounts, environment, limits, restart policies, logging drivers, read-only rootfs, dropped capabilities, --init.
  • Compose: services, networks, volumes, health checks and depends_on conditions, profiles, overrides for dev.
  • Supply chain: SBOMs, vulnerability scanning, signing (cosign/Sigstore), provenance (SLSA), base image updates, secrets via BuildKit mounts.

Numbers to remember

  • Lab: multi-stage image 8.6 MB vs 527 MB naive; cache mounts cut a rebuild from 23.4 s to 1.6 s; a 300 MB context added 18 s; a shell PID 1 made docker stop take 10.2 s and exit 137.

Pitfalls

  • COPY . . before installing dependencies.
  • Secrets in COPY, ARG or ENV (they stay in layers and history).
  • Mutable latest tags in production.
  • Shell-form CMD or entrypoint scripts without exec.
  • Running as root; writable root filesystems.
  • Huge build contexts without .dockerignore.

Glossary

  • Layer: an immutable filesystem diff identified by its digest.
  • Digest: content hash (sha256:…) naming an exact image or layer.
  • BuildKit: Docker's build engine (parallel stages, cache and secret mounts).
  • Distroless: images with only the runtime and app.
  • SBOM: software bill of materials listing an image's components.
  • Multi-arch index: a manifest list pointing at per-platform images.

82

Reverse Proxies and Gateways

Key ideas

  • Roles: TLS termination, routing (host, path, header), load balancing, health checks, timeouts and limits, buffering, compression, caching, header management, auth offload, WAF.
  • NGINX: server/location matching, upstream, proxy_pass path rules, proxy_set_header, keepalive, buffering, limit_req, proxy_next_upstream.
  • HAProxy: frontends/backends, ACLs, balance algorithms, active/passive checks, stick tables, stats, runtime API.
  • Envoy: listeners, filter chains, clusters, xDS dynamic configuration, outlier detection, retries with budgets, observability; Istio, Envoy Gateway.
  • TLS: certificates and chains, SNI, TLS 1.3, ACME/Let's Encrypt automation, HSTS, mTLS to backends, OCSP stapling.
  • Load balancing: round-robin, weighted, least connections/requests, power of two choices, consistent hashing for affinity, L4 vs L7.
  • Timeouts and retries: connect/read/idle timeouts aligned across layers; retry only idempotent requests; retry budgets.
  • Gateways and meshes: API gateways (auth, quotas, transformation), Kubernetes Gateway API, service meshes (sidecars or ambient).

Numbers to remember

  • Lab: leastconn gave 8× round-robin's throughput with one 200 ms backend; health checks removed 40 errors and 40 timeouts when a backend died; upstream keep-alive doubled throughput and cut TIME_WAIT from 16,745 to 217; gzip cut a 20 KB JSON to 1.9 KB; a 1 s read timeout returned 504 in 1.0 s.

Pitfalls

  • No upstream keep-alive.
  • Trusting forwarded headers from the internet.
  • Retrying POSTs at the proxy.
  • Timeouts longer at the proxy than at the client.
  • Health checks that always return 200.
  • Forgetting WebSocket/streaming settings (upgrade headers, buffering, idle timeouts).

Glossary

  • Upstream / backend: servers the proxy forwards to.
  • SNI: TLS extension carrying the requested host name.
  • L4 / L7 balancing: by connection (TCP) vs by request (HTTP).
  • 502 / 504: bad gateway (backend error/refused) / gateway timeout.
  • Outlier detection: ejecting hosts with abnormal errors or latency.
  • xDS: Envoy's discovery APIs for dynamic configuration.

83

Kubernetes

Key ideas

  • Model: declarative objects stored in etcd via the API server; controllers reconcile; everything is a watch loop.
  • Architecture: API server, etcd, scheduler, controller manager, cloud controller; kubelet, container runtime (CRI), kube-proxy, CNI, CSI on nodes; CoreDNS.
  • Pods: one or more containers sharing network and volumes; init and sidecar containers; lifecycle and restart policy; probes (startup, readiness, liveness); graceful termination.
  • Workloads: Deployment/ReplicaSet, StatefulSet, DaemonSet, Job/CronJob.
  • Config: ConfigMaps, Secrets (base64, not encryption; use encryption at rest or external secret stores), environment vs mounted files.
  • Services and networking: ClusterIP, NodePort, LoadBalancer, headless; EndpointSlices; DNS; Ingress and Gateway API; NetworkPolicy.
  • Resources: requests vs limits, QoS classes, LimitRange, ResourceQuota, eviction.
  • Scaling: HPA (metrics-server, custom metrics, KEDA), VPA, Cluster Autoscaler/Karpenter.
  • Storage: PersistentVolumes and Claims, StorageClasses, CSI, access modes, StatefulSet volume templates.
  • Scheduling: node selectors, affinity/anti-affinity, taints and tolerations, topology spread, priority and preemption.
  • Security: RBAC, ServiceAccounts, Pod Security Standards, securityContext, admission (validating/mutating, Kyverno, Gatekeeper), image policy.
  • Extending: CRDs, operators, controllers with client-go/controller-runtime.

Numbers to remember

  • CrashLoopBackOff: 10 s doubling to a 5-minute cap.
  • Default termination grace period: 30 s.
  • Lab: restarts at 3 s, 18 s, 49 s; OOMKilled exit 137; Pending on "Insufficient cpu"; a not-ready pod left the Service in 1.6 s with no restart; 11 NAT rules for a 3-pod Service.

Pitfalls

  • No requests (scheduling blind) or memory limits far above requests (overcommit and evictions).
  • Liveness probes that check dependencies.
  • No readiness probe, so traffic reaches pods before they're ready.
  • Secrets treated as encrypted.
  • latest tags with IfNotPresent pull policy.
  • Long-lived connections and kube-proxy's per-connection balancing.

Glossary

  • Reconciliation: driving actual state towards desired state.
  • EndpointSlice: the list of pod addresses behind a Service.
  • QoS class: Guaranteed, Burstable or BestEffort, from requests and limits.
  • Taint / toleration: node repels pods unless they tolerate it.
  • CRD: custom resource definition extending the API.
  • Operator: a controller encoding operational knowledge for an application.

84

Kubernetes Deployment Strategy

Key ideas

  • What goes wrong: bad code, bad config, capacity drops, shutdown races, incompatible versions running together, irreversible state changes.
  • Recreate: simple, downtime, no mixing.
  • Rolling update: maxSurge, maxUnavailable, readiness gating, minReadySeconds, progressDeadlineSeconds, revision history.
  • Safe shutdown: readiness probe, preStop delay (endpoint propagation), SIGTERM draining, terminationGracePeriodSeconds.
  • Blue/green: two full environments, instant switch and rollback, double capacity, connection draining.
  • Canary: small traffic share, metrics comparison, weight- or header-based splitting via gateways/meshes; progressive delivery (Argo Rollouts, Flagger) with automated analysis; shadow traffic; A/B tests.
  • Feature flags: deploy ≠ release; kill switches, percentage rollouts, targeting; OpenFeature; flag hygiene.
  • Rollback: undo vs roll forward; why state (schemas, data formats, messages) blocks rollback; expand/contract migrations as separate steps.
  • Promotion: build once, immutable images by digest, promote through environments; Helm, Kustomize, GitOps (Argo CD, Flux).

Numbers to remember

  • Defaults: maxSurge 25%, maxUnavailable 25%, progressDeadlineSeconds 600, revisionHistoryLimit 10, grace period 30 s.
  • Lab: no preStop gave 6–13 errors per rollout, readiness + preStop 0; Recreate ~3 s outage; blue/green switch within a second; a 1-in-5 canary got 21% of traffic; a never-ready version stalled with 0 errors and ProgressDeadlineExceeded after 30 s.

Pitfalls

  • No preStop delay, so endpoint removal races SIGTERM.
  • Readiness probes that pass before the app is warm.
  • Grace periods shorter than drain time.
  • Schema changes that break the previous version.
  • Mixing kubectl rollout undo with GitOps (drift).
  • Canaries without metrics, or metrics too noisy to decide.

Glossary

  • ReplicaSet: keeps N identical pods; Deployments create one per template revision.
  • maxSurge / maxUnavailable: limits above and below desired replicas during a rollout.
  • preStop hook: action run before SIGTERM when a container is stopped.
  • Progressive delivery: automated, metric-gated gradual release.
  • Expand/contract: multi-step backward-compatible change.
  • GitOps: Git as the source of truth, reconciled into the cluster by an agent.