SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Kubernetes Basics

A system that runs, scales, heals and updates your containers across many machines.

⏱ 16 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Kubernetes (often written K8s) is a system that runs your containers across many machines and keeps them healthy for you.

  • You do not say "start this container on that machine". You write down the desired state, for example "I want 3 copies of this app, version 1.2".
  • Kubernetes keeps comparing the actual state with the desired state, and fixes any difference. A crashed container is replaced. A dead machine's work moves to others.
  • It also handles rolling updates, scaling, service addresses and secrets. The price is a lot of new ideas to learn.

02Concept: What is it?

A single container is easy to run. Running hundreds of containers on dozens of machines is not. Something must decide which machine runs which container, restart the ones that crash, give them addresses, update them without downtime and add more when traffic grows. That job is called container orchestration, and Kubernetes is the most widely used orchestrator.

The big idea is the reconciliation loop. You send Kubernetes a description of what you want (a YAML file). A group of controllers then watch the cluster all the time. Each one asks: "does reality match what was asked for?" If not, it acts. Because this loop never stops, the cluster heals itself.

A cluster has a control plane and worker nodes
Control plane (the brain)
🚪API serverthe front door
🗃️etcdstores the state
📍Schedulerpicks a node
🔁Controllersfix differences
Worker nodes (the muscle)
🖥️Node 1kubelet + runtime
📦Pods
🖥️Node 2kubelet + runtime
📦Pods
You talk to the API server. The other parts do the work. Names are simplified.
🧠Declare, do not command
With Kubernetes you describe what you want, not the steps. "3 copies, please" is a promise the cluster keeps over and over, not a one-time order.

03Real-Life Example

🍵The Restaurant Manager
A restaurant owner tells the manager: "I always want 3 chefs on the line, wearing the new uniform." The owner does not say who to call or when. If a chef goes home sick, the manager calls a replacement. If the kitchen floods, the manager moves the cooks to the other kitchen. When the owner changes the uniform, the manager swaps the chefs one at a time, so the line is never empty. The owner only states the goal.
Restaurant
Kubernetes
The owner's instruction (3 chefs)
The desired state in a YAML file
The manager who keeps checking
A controller running the reconciliation loop
A chef
A pod (one running copy of your app)
A kitchen
A worker node (a machine)
Deciding which kitchen gets a new chef
The scheduler
Swapping uniforms one chef at a time
A rolling update
The sign: 'chef is ready to take orders'
A readiness probe
The loop that never stops
📝Desired3 pods, v1
→↓compare
👀Actual2 pods running
→↓differ?
🔧Actstart one more
→↓repeat

04Why Do We Need It?

🩹Self-healing
Crashed containers restart. Pods from a dead node are created again on another node.
📈Scaling
Change one number to run more copies, or let an autoscaler change it when load grows.
🔄Safe updates
Rolling updates replace pods a few at a time, and a bad release can be rolled back.
🏷️Stable addresses
Pods come and go, but a Service gives them one steady name and shares the traffic.
📐Efficient packing
The scheduler fits many apps onto the same machines, so you waste less hardware.
☁️Runs anywhere
The same YAML works on your laptop, in a data centre, or on a cloud provider.
You tell Kubernetes the goal once, and it keeps working to make the goal true.

05Where Do We Use It?

🧩Microservices
Dozens of small services, each with its own copies, updates and scaling. This is the classic fit.
☁️Managed clouds
Amazon EKS, Google GKE and Azure AKS run the control plane for you, so you manage only your apps.
🏢Company platforms
Many companies build an internal platform on Kubernetes, so teams can ship without managing servers.
🧠Batch and ML jobs
Jobs that run once or on a timetable, and training work that needs special machines.
🔁Build and test
CI systems start a fresh pod for each build, then throw it away.
🚫Not for everything
A small site with one or two servers rarely needs it. A simple host or a managed container service is easier.

06Types / Parts / How It Works

The objects you will meet

ObjectWhat it isWhy it exists
PodThe smallest unit. One or more containers that share a network address and storage.Pods are short-lived. Never rely on a single pod's IP address.
ReplicaSetKeeps a chosen number of identical pods running.Gives self-healing. You rarely create one by hand.
DeploymentManages ReplicaSets for you and does rolling updates and rollbacks.The normal way to run a stateless app.
ServiceA stable name and virtual IP that spreads traffic over the ready pods behind it.Pods change, so clients need one steady address.
IngressRules that route outside HTTP traffic (by host or path) to Services.One entry point for many apps.
ConfigMap and SecretSettings and sensitive values kept outside the image.One image can run in dev, test and production.
StatefulSet and volumesPods with a steady identity and storage that survives restarts.Databases and other apps that must remember data.
NamespaceA named group of objects inside a cluster.Separate teams or environments, with their own limits.

A short Deployment (illustrative)

deployment.yaml (illustrative, shortened)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-web
spec:
  replicas: 3                # desired number of pods
  selector:
    matchLabels: { app: shop-web }
  template:
    metadata:
      labels: { app: shop-web }
    spec:
      containers:
        - name: web
          image: example/shop-web:1.2
          resources:
            requests: { cpu: "250m", memory: "256Mi" }
            limits:   { memory: "512Mi" }
          readinessProbe:
            httpGet: { path: /ready, port: 8080 }

You apply it with a command such as kubectl apply -f deployment.yaml. Field names and defaults can change between versions, so check the current Kubernetes documentation before you copy it.

How a request reaches a pod
👤User
→↓
🚪Ingresshost and path rules
→↓
🏷️Servicesteady name
→↓
📦Pod Aready
📦Pod Bready
📦Pod Cnot ready
Gets traffic Skipped by the Service
Only pods that pass the readiness probe receive traffic from the Service.
VisualizerA tiny cluster: kill, scale and roll outClick a pod to kill it, fail a node, or change the desired count. Then press the controller step and watch the cluster move back to the desired state. Try a rollout of v2 with the bug switched on.
Worker nodes and their pods. Click a pod to kill it. Green = v1, purple = v2, dashed amber = starting (not ready).
Node 1
Node 2
Node 3
Desired
3
version v1
Running
3
pods that exist
Ready
3
get traffic from the Service
Versions
v1×3 v2×0
old and new
Desired state: 3 copies (pods) of version v1. Break something (click a pod to kill it, or fail a node), then press the controller step button and watch Kubernetes repair it.

A simplified model with no random numbers. Real Kubernetes also looks at CPU and memory requests when it places a pod, waits before it gives up on a node, and runs many controllers side by side. Here the controller does one thing per step, and a rolling update adds at most one extra pod at a time and never drops below the desired number of ready pods.

07How to Use It / Steps / Implementation

Using Kubernetes sensibly

  1. 1
    Start from a good container image
    Build a small image with one process. Kubernetes runs what the image contains. See Containers and Docker.
  2. 2
    Run it with a Deployment
    Set replicas to at least 2 for anything that matters, so one pod crash does not mean an outage.
  3. 3
    Add health probes
    A readiness probe says 'send me traffic now'. A liveness probe says 'I am stuck, restart me'. Without a readiness probe, users may reach a pod that is still starting.
  4. 4
    Set resource requests and limits
    A request tells the scheduler how much to reserve. A limit caps usage: too much CPU is throttled, too much memory gets the container killed.
  5. 5
    Expose it with a Service
    Use the Service name for calls between apps, and an Ingress for traffic from outside.
  6. 6
    Keep settings out of the image
    Use ConfigMaps for settings. Use a proper secret store for sensitive values.
  7. 7
    Autoscale and watch
    A Horizontal Pod Autoscaler adds or removes pods based on a metric such as CPU. Watch restarts, pending pods and readiness.
⚠️Secrets are not encrypted by default
A Kubernetes Secret is only base64 encoded by default, which is not encryption. Turn on encryption at rest for the cluster store, limit who can read Secrets, and consider an external secret manager.
💡Start with a managed cluster
Running the control plane yourself is hard work. A managed service (EKS, GKE or AKS) lets a small team use Kubernetes without becoming experts in its internals.

08Key Terms to Know

TermMeaning in easy words
ClusterA set of machines (nodes) managed together by Kubernetes
NodeOne worker machine that runs pods
PodThe smallest unit: one or more containers sharing a network address and storage
DeploymentAn object that keeps a number of pods running and handles rolling updates
ServiceA stable name and address that balances traffic over a set of pods
Desired stateWhat you asked for, written in a manifest
Reconciliation loopA controller repeatedly comparing actual state to desired state and fixing the difference
Readiness probeA check that decides whether a pod should receive traffic
Liveness probeA check that decides whether a pod is stuck and must be restarted
Resource request and limitThe amount reserved for scheduling, and the cap enforced while running
ManifestA YAML (or JSON) file that describes objects you want

09Pros, Cons and Trade-offs

✅ Pros
  • Self-healing and automatic restarts
  • Rolling updates and easy rollbacks
  • Scales out by changing one number
  • One standard way to run many kinds of apps
  • Runs on laptops, data centres and every major cloud
⚠️ Cons
  • Many concepts and a steep learning curve
  • Real operating cost: networking, upgrades and security
  • Easy to misconfigure (limits, probes, permissions)
  • Overkill for small systems
  • Stateful apps need extra care

Trade-offs

ChoiceWe gainWe lose
Kubernetes vs plain serversAutomation, healing, standard toolingSimplicity, and a team that must learn it
Managed vs self-run control planeLess work and fewer outages of the brainSome control, and a cloud bill
Many small pods vs few big podsSmoother scaling and failure impactMore overhead and more to manage
Tight CPU and memory limitsFair sharing and a safer clusterThrottling or killed containers if set too low
Autoscaling onPay for what you needSlow reaction to sudden spikes, and tuning work
Running databases in the clusterOne platform for everythingHarder storage, backups and failover

10Common Problems and Mistakes

Common mistakes

  1. No readiness probe. New pods get traffic before they are ready, and users see errors during every deploy.
  2. No resource requests or limits. One greedy pod starves its neighbours, or the scheduler packs too many pods onto one node.
  3. Only one replica. Any restart or node failure means downtime.
  4. Treating pods like pets. Pods are replaceable. Logging into one to fix it by hand is lost on the next restart.
  5. Storing data in a pod's own disk. It disappears when the pod is replaced. Use a volume or an external database.
  6. Using the "latest" image tag. You cannot tell what is running, and a rollback is unclear. Use fixed versions.
  7. Adopting it too early. A tiny app can spend more time on cluster care than on its own features.

Things to watch

🔁CrashLoopBackOff
A pod keeps crashing and restarting. Read its logs and the last exit reason.
⏳Pending pods
No node has enough room, or no node matches the rules. Check requests and capacity.
💥OOM kills
A container went over its memory limit and was killed. Raise the limit or fix the leak.
🧱Upgrades
The cluster itself must be upgraded now and then. Plan it, and test it first.

11Real-World Examples

☁️Managed services
EKS, GKE and AKS are the main managed offerings on the big clouds.
🏢Large companies
Many large companies run their services on Kubernetes or on platforms built on top of it.
🛠️Platform teams
A small team runs the cluster. Other teams deploy with a simple template.
🧪Local learning
Tools such as kind and minikube run a tiny cluster on a laptop for practice.
📦Package and deploy tools
Helm packages manifests, and GitOps tools such as Argo CD or Flux sync a cluster with a Git repository.
📊Observability
Metrics, logs and traces are usually added with tools like Prometheus and OpenTelemetry.
📝Note
Product names, versions and defaults change often. Check the current documentation before you rely on a detail from this page.
Mini case: one node dies
💥Node 2 diesits pods vanish
→↓noticed
🔁Controlleractual 2, desired 3
→↓schedule
📍Schedulerpicks node 1
→↓start
📦New podready, joins Service
Self-healing in four steps. No human is paged for the first reaction.

12Related Topics to Read Next

Containers and Docker→

Kubernetes runs containers, so you need to know how they are built.

Microservices→

The style of system that Kubernetes is most often used for.

Service Discovery→

A Kubernetes Service is a built-in form of it.

Health Checks→

Readiness and liveness probes are health checks.

Rolling Deployments→

A Deployment does a rolling update by default.

Secrets Management→

Kubernetes Secrets need extra protection.

Stateless vs Stateful→

Stateless apps are easy. Stateful apps need extra care.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a system that runs containers on many machines and keeps them healthy.
  • ✔Core idea: declare the desired state, and controllers reconcile reality to match.
  • ✔Objects: Pod, Deployment, Service, Ingress, ConfigMap, Secret, StatefulSet.
  • ✔Pods: short-lived. Never rely on one pod's IP or local disk.
  • ✔Probes: readiness (get traffic?) and liveness (restart me?).
  • ✔Resources: request = reserve, limit = cap (CPU throttled, memory killed).
  • ✔Careful: Secrets are base64, not encrypted, by default.
  • ✔One line: “Say what you want, and let the cluster keep it true.”
← Previous
Containers and Docker
Next →
Clean Architecture and Modular Monolith