← Back to Blog

Kubernetes in Production: Lessons from the Trenches

kubernetesdevopscontainersproduction

Kubernetes in Production: Lessons from the Trenches

April 8, 2026
Paál Gyula
Paál Gyula
Founder & Lead Architect

Real-world Kubernetes deployment patterns, common pitfalls, and practical strategies for running production-grade clusters with confidence.

283 article views
4.8/5 (26 ratings)

🚀 Introduction

Getting a workload running on Kubernetes takes an afternoon. Keeping it running through node failures, rolling upgrades, noisy neighbours and a 3am traffic spike takes a different set of habits — and almost none of them are on by default.

This post is the list we wish someone had handed us before our first production cluster. It skips the "what is a Pod" material and goes straight to the settings and patterns that decide whether an incident is a non-event or an outage.

📋 Key Topics Covered

  • Cluster architecture and sizing
  • Resource management: requests, limits, and QoS
  • Probes and graceful shutdown — the source of most "random" 502s
  • Availability: PodDisruptionBudgets and topology spread
  • Networking: Services, Ingress, Gateway API, and NetworkPolicies
  • Storage: PersistentVolumes and StatefulSets
  • Security: RBAC, Pod Security, and Secrets
  • Observability and alerting
  • Backup, disaster recovery, and upgrades

🏗️ Cluster Architecture and Sizing

🎯 Managed Unless You Have a Reason

Running your own control plane means owning etcd backups, certificate rotation, and API server availability. Use a managed control plane (GKE, EKS, AKS) unless you have a concrete reason not to: data residency, on-prem hardware, or cost at a scale where an ops team is already paid for.

If you do self-host, run three control plane nodes with etcd on fast local SSDs. etcd is latency-sensitive: slow disks show up as API server timeouts long before anything looks "down".

⚖️ Node Sizing

Guidelines:

  1. Avoid tiny nodes. Every node pays a fixed tax for kubelet, container runtime, CNI and log agents. On a 2 vCPU node that tax can be 20–30% of capacity.
  2. Avoid giant nodes too. Losing one 64-core node evicts a large share of your workload at once and makes rescheduling slow.
  3. Separate pools by workload type. Stateless apps, stateful services, and batch jobs have different failure and scaling profiles. Use taints and node affinity to keep them apart.
  4. Leave headroom. Plan for N+1: the cluster must absorb the loss of its largest node without pods going Pending.

📦 Resource Management: Requests, Limits, and QoS

This is where most production clusters go wrong first. The scheduler places pods using requests; the kernel enforces limits. Get them wrong and you get either wasted capacity or OOM-killed pods during peak traffic.

🧮 QoS Classes

QoS classWhen it appliesEviction priority under pressure
GuaranteedEvery container has requests = limits for CPU and memoryEvicted last
BurstableAt least one request set, but not all equal to limitsEvicted in the middle
BestEffortNo requests or limits at allEvicted first

✅ A Sane Default

yaml
1resources:
2  requests:
3    cpu: 250m
4    memory: 512Mi
5  limits:
6    memory: 512Mi # memory limit = request: predictable, no surprise OOMs
7    # no CPU limit: avoids CFS throttling, CPU request still guarantees a share

Enforce it at the namespace level with a LimitRange (default requests for containers that forget) and a ResourceQuota (a ceiling per team), so one team's missing requests can't starve the cluster.

🩺 Probes and Graceful Shutdown

If your users see sporadic 502s during deployments, this section is why.

🔍 The Three Probes

  • startupProbe — "has the app finished booting?" Protects slow starters (JVMs, apps warming caches) from being killed by the liveness probe before they're ready.
  • readinessProbe — "should this pod receive traffic right now?" Failing removes the pod from Service endpoints, nothing else.
  • livenessProbe — "is this process wedged beyond recovery?" Failing restarts the container.

🛑 Graceful Shutdown

When a pod is deleted, two things happen in parallel: the kubelet sends SIGTERM, and the endpoint controller removes the pod from Services. Ingress controllers and kube-proxy take a few seconds to notice. If your app exits immediately on SIGTERM, requests still routed to it fail.

yaml
1spec:
2  terminationGracePeriodSeconds: 45
3  containers:
4    - name: api
5      lifecycle:
6        preStop:
7          sleep:
8            seconds: 10 # let endpoint removal propagate before SIGTERM

The native sleep action in preStop is available in recent Kubernetes versions; on older clusters use exec: { command: ["sleep", "10"] }. Then make sure your app actually handles SIGTERM by draining connections instead of dying instantly.

🛡️ Availability: Disruption Budgets and Spreading

Three replicas on one node is one replica. Two settings fix that:

yaml
1# Spread replicas across zones and nodes
2topologySpreadConstraints:
3  - maxSkew: 1
4    topologyKey: topology.kubernetes.io/zone
5    whenUnsatisfiable: ScheduleAnyway
6    labelSelector:
7      matchLabels: { app: api }
8---
9# Never let voluntary disruptions (drains, upgrades) take more than one at a time
10apiVersion: policy/v1
11kind: PodDisruptionBudget
12metadata:
13  name: api
14spec:
15  maxUnavailable: 1
16  selector:
17    matchLabels: { app: api }

🌐 Networking: Services, Ingress, and NetworkPolicies

🚪 Ingress and the Gateway API

For HTTP traffic, the Gateway API is the forward path: it separates infrastructure ownership (the Gateway, owned by the platform team) from routing (HTTPRoute, owned by app teams), and it supports traffic splitting and header matching without controller-specific annotations.

🔒 Default-Deny NetworkPolicies

By default every pod can talk to every other pod in the cluster. One compromised container can then reach your database directly. Start each namespace with a default-deny policy and open only what's needed:

yaml
1apiVersion: networking.k8s.io/v1
2kind: NetworkPolicy
3metadata:
4  name: default-deny
5spec:
6  podSelector: {}
7  policyTypes: [Ingress, Egress]
8---
9apiVersion: networking.k8s.io/v1
10kind: NetworkPolicy
11metadata:
12  name: api-to-postgres
13spec:
14  podSelector:
15    matchLabels: { app: postgres }
16  ingress:
17    - from:
18        - podSelector:
19            matchLabels: { app: api }
20      ports:
21        - port: 5432

Remember to allow egress to DNS (kube-dns on port 53) or everything breaks in confusing ways. And check that your CNI actually enforces NetworkPolicies — Calico and Cilium do; some basic CNIs silently ignore them.

💾 Storage: PersistentVolumes and StatefulSets

  • Use a StorageClass with volumeBindingMode: WaitForFirstConsumer. Otherwise a volume can be provisioned in a zone where the pod can't be scheduled.
  • Set reclaimPolicy: Retain for anything you can't recreate. The default Delete removes the disk when the PVC is deleted — including by an accidental kubectl delete namespace.
  • StatefulSets give stable identity, not high availability. Replication, failover, and backups are still the database's job. For Postgres, use an operator (CloudNativePG, Zalando) rather than a hand-rolled StatefulSet.
  • Ask honestly whether the database belongs in the cluster at all. A managed database is often cheaper than the engineering time to run one well on Kubernetes.

🔐 Security: RBAC, Pod Security, and Secrets

👤 RBAC

  1. No humans with cluster-admin by default. Grant it through a break-glass procedure that's logged.
  2. Bind roles to groups from your identity provider, not to individual users, so offboarding is one change.
  3. Give each workload its own ServiceAccount and set automountServiceAccountToken: false for pods that never call the Kubernetes API.

🧱 Pod Security Admission

PodSecurityPolicy is gone. Its replacement is built in: label each namespace with a Pod Security Standard level.

yaml
1apiVersion: v1
2kind: Namespace
3metadata:
4  name: payments
5  labels:
6    pod-security.kubernetes.io/enforce: restricted
7    pod-security.kubernetes.io/warn: restricted

restricted blocks privileged containers, host namespaces, running as root, and privilege escalation. Start application namespaces at restricted and make exceptions explicit.

🗝️ Secrets Are Not Encrypted by Default

A Kubernetes Secret is base64-encoded, which is encoding, not encryption. Turn on encryption at rest for etcd (managed clusters usually offer KMS integration), restrict get/list on Secrets in RBAC, and keep the source of truth outside the cluster — External Secrets Operator syncing from Vault or a cloud secret manager, or Sealed Secrets for GitOps repos.

📊 Observability and Alerting

Alerts worth waking up for:

  • Error rate and latency SLO burn for user-facing services
  • Pods in CrashLoopBackOff or stuck Pending for more than a few minutes
  • Nodes NotReady, or disk / memory pressure on nodes
  • PersistentVolumes above 85% full
  • Certificates expiring within 14 days
  • etcd leader changes and high fsync latency (self-hosted control planes)

Alerts that should be dashboards instead: CPU above 80%, a single pod restart, high memory on a pod that has a limit. Alert on symptoms users feel, not on every number that moves.

🔄 Backup, Disaster Recovery, and Upgrades

💽 Back Up Both Layers

  • Cluster state: etcd snapshots for self-hosted clusters, plus your manifests in Git (GitOps with Argo CD or Flux makes the Git repo the real backup).
  • Data: volume snapshots and application-level backups (pg_dump, WAL archiving). Velero handles both Kubernetes objects and volume snapshots.

⬆️ Upgrades

  1. Stay within the supported window. Kubernetes supports roughly the three most recent minor versions; falling behind turns a routine upgrade into a multi-step migration.
  2. Upgrade one minor version at a time, control plane first, then node pools.
  3. Check for removed APIs before upgrading. Tools like pluto or kubent scan your manifests and Helm releases for deprecated API versions.
  4. Rehearse on staging, with the same add-ons (CNI, ingress, operators) as production.
  5. Roll node pools by surging new nodes rather than draining in place, so capacity never drops.

🌍 Multi-Cluster: Not on Day One

Multiple clusters solve real problems — regional failover, blast-radius isolation, regulatory separation — but they multiply everything above. Get one cluster boring first. When you do go multi-cluster, keep clusters identical through GitOps rather than hand-maintaining each one.

✅ Production Readiness Checklist

AreaCheck
ResourcesEvery container has CPU/memory requests and a memory limit
ProbesReadiness on every service; liveness never checks dependencies
ShutdownpreStop delay + SIGTERM handling + adequate grace period
Availability≥2 replicas, topology spread, a drainable PDB
NetworkDefault-deny NetworkPolicy per namespace, DNS egress allowed
SecurityPod Security restricted, per-workload ServiceAccounts, no shared admin
SecretsEncryption at rest, external source of truth
ObservabilitySLO-based alerts, logs centralised, dashboards per service
RecoveryBackups of state and data, restore drill in the last quarter
UpgradesWithin the supported version window, deprecated APIs scanned

🏁 Conclusion

Kubernetes doesn't make applications reliable; it gives you the primitives to make them reliable. The defaults favour getting started, not staying up: no resource requests, no disruption budgets, open pod-to-pod networking, unencrypted Secrets, and apps that drop requests on every deploy.

None of the fixes are exotic. Requests and memory limits, honest probes, a preStop delay, a PDB, default-deny networking, restricted Pod Security, and a tested restore cover the vast majority of real incidents we've seen. Do those first, and most of your production surprises become the boring kind.

If you're weighing whether you need Kubernetes at all, read Why Cloud Run? — for many stateless services, a managed container platform removes this entire checklist.


❓ Frequently Asked Questions

Q: Should I set CPU limits on my containers?

A: Usually not. CPU limits cause CFS throttling, which shows up as latency spikes even on idle nodes. Set CPU requests so the scheduler reserves capacity and the container gets a guaranteed share, and skip CPU limits unless you need hard isolation (for example, untrusted multi-tenant workloads). Always set memory limits.

Q: How many replicas should a production service run?

A: At least two, spread across nodes (and zones, if your cluster spans them), with a PodDisruptionBudget allowing one to be unavailable. Three gives you headroom to lose a replica during a rolling update and still survive a node failure.

Q: Why do I get 502 errors during deployments?

A: Almost always because pods stop serving before load balancers stop sending them traffic. Add a preStop sleep of 5–15 seconds, handle SIGTERM by draining in-flight requests, and make sure readiness probes are configured so new pods only receive traffic when they're actually ready.

Q: Is it safe to run databases on Kubernetes?

A: It can be, with a mature operator (CloudNativePG for Postgres, for example), Retain reclaim policies, tested backups, and a team that understands both the database and Kubernetes storage. If you don't have that, a managed database service is usually the safer and cheaper choice.

Q: Are Kubernetes Secrets secure?

A: Not by default. They're base64-encoded in etcd, not encrypted. Enable encryption at rest (ideally with a KMS provider), restrict who can read Secrets via RBAC, and keep the source of truth in a dedicated secret manager synced in with External Secrets Operator.

Q: How often should we upgrade Kubernetes?

A: Plan for roughly two to three minor-version upgrades per year to stay inside the supported window. Upgrade one minor version at a time, scan for removed APIs first, and rehearse on a staging cluster with the same add-ons as production.

Q: Do we need a service mesh?

A: Not by default. A mesh adds mTLS between services, fine-grained traffic control, and uniform telemetry — at the cost of significant operational complexity. Start with NetworkPolicies and good application-level observability; adopt a mesh when you have a concrete requirement, such as mandatory mTLS or advanced traffic shifting, that you can't meet otherwise.

How did you find this article?

Leave your rating to help us improve our engineering content.

283 article views
4.8/5 (26 ratings)
Follow us
All Rights Reserved
© 2011-2026
Progressive Innovation
LAB