🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Container Orchestration: K8s, ECS, Service Discovery

Cloud ArchitectureContainer Orchestration⭐ Premium

Container Orchestration: K8s, ECS, Service Discovery

Difficulty: Senior Level | Companies: Google, Amazon, Microsoft, Netflix, Spotify

Interview Question

"Design a Kubernetes architecture for a microservices platform with 100+ services. How do you handle service discovery, load balancing, and auto-scaling?"

â„šī¸Key Concepts

This question tests your understanding of container orchestration, Kubernetes patterns, and production-grade deployment strategies.

Complete Kubernetes Architecture

Architecture Overview

KUBERNETES ARCHITECTURE

KUBERNETES ARCHITECT

┌───────────────────

┌─────────────┐ ┌──

API Server

Scheduler

Controller

(etcd)

Manager

└─────────────┘ └──

└───────────────────

┌───────────────────

┌─────────────────┐

Worker Node 1

Worker Node 2

┌─────────────┐

┌─────────────┐

Pod A

Pod C

┌────────┐

┌────────┐

Container

Container

└────────┘

└────────┘

└─────────────┘

└─────────────┘

┌─────────────┐

┌─────────────┐

Pod B

Pod D

┌────────┐

┌────────┐

Container

Container

└────────┘

└────────┘

└─────────────┘

└─────────────┘

└─────────────────┘

└───────────────────

┌───────────────────

Istio Linkerd Consul Connect

└───────────────────

Mathematical Foundation: Resource Planning

Pod Scheduling:

  • Total pods: P = 1000
  • Average pod CPU: C_pod = 0.5 cores
  • Average pod memory: M_pod = 512MB
  • Node CPU: C_node = 16 cores
  • Node memory: M_node = 32GB

Resource Utilization:

  • CPU utilization target: U_cpu = 70%
  • Memory utilization target: U_mem = 80%
  • Pods per node (CPU): P_cpu = (C_node × U_cpu) / C_pod = 22.4
  • Pods per node (Memory): P_mem = (M_node × U_mem) / M_pod = 51.2
  • Bottleneck: CPU-limited pods per node = 22

Cluster Size:

  • Nodes needed: N = P / P_cpu = 1000 / 22 ≈ 46 nodes
  • With 20% buffer: N_buffered = 46 × 1.2 = 55 nodes

Kubernetes Deployment

# Deployment with rolling update strategy
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
  namespace: production
  labels:
    app: order-service
    version: v1
spec:
  replicas: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
  selector:
    matchLabels:
      app: order-service
  template:
    metadata:
      labels:
        app: order-service
        version: v1
      annotations:
        prometheus.io/scrape: true
        prometheus.io/port: "9090"
    spec:
      serviceAccountName: order-service
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        fsGroup: 2000
      containers:
        - name: order-service
          image: order-service:latest
          ports:
            - containerPort: 8080
              name: http
            - containerPort: 9090
              name: metrics
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: DATABASE_URL
              valueFrom:
                secretKeyRef:
                  name: order-service-secrets
                  key: database-url
          resources:
            requests:
              cpu: "500m"
              memory: "512Mi"
            limits:
              cpu: "1000m"
              memory: "1Gi"
          livenessProbe:
            httpGet:
              path: /health/live
              port: 8080
            initialDelaySeconds: 30
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 3
          readinessProbe:
            httpGet:
              path: /health/ready
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 5
            timeoutSeconds: 3
            failureThreshold: 3
          startupProbe:
            httpGet:
              path: /health/startup
              port: 8080
            failureThreshold: 30
            periodSeconds: 10
          volumeMounts:
            - name: config
              mountPath: /etc/config
              readOnly: true
            - name: tmp
              mountPath: /tmp
      volumes:
        - name: config
          configMap:
            name: order-service-config
        - name: tmp
          emptyDir: {}
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: DoNotSchedule
          labelSelector:
            matchLabels:
              app: order-service
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchExpressions:
                    - key: app
                      operator: In
                      values:
                        - order-service
                topologyKey: kubernetes.io/hostname

Service Discovery

# Service for internal communication
apiVersion: v1
kind: Service
metadata:
  name: order-service
  namespace: production
  labels:
    app: order-service
spec:
  selector:
    app: order-service
  ports:
    - name: http
      port: 80
      targetPort: 8080
      protocol: TCP
    - name: metrics
      port: 9090
      targetPort: 9090
      protocol: TCP
  type: ClusterIP

---
# Headless service for StatefulSets
apiVersion: v1
kind: Service
metadata:
  name: order-service-headless
  namespace: production
spec:
  selector:
    app: order-service
  clusterIP: None
  ports:
    - name: http
      port: 80
      targetPort: 8080

---
# External service (ExternalName)
apiVersion: v1
kind: Service
metadata:
  name: external-payment-service
  namespace: production
spec:
  type: ExternalName
  externalName: payment.external.com

---
# Ingress for external access
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api-ingress
  namespace: production
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/rate-limit: "100"
    nginx.ingress.kubernetes.io/rate-limit-window: "1m"
spec:
  tls:
    - hosts:
        - api.example.com
      secretName: api-tls-secret
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /api/v1/orders
            pathType: Prefix
            backend:
              service:
                name: order-service
                port:
                  number: 80
          - path: /api/v1/users
            pathType: Prefix
            backend:
              service:
                name: user-service
                port:
                  number: 80
python
# Service discovery with DNS
import socket
from typing import List, Dict, Any
import dns.resolver
from dataclasses import dataclass

@dataclass
class ServiceEndpoint:
    host: str
    port: int
    weight: int = 1
    healthy: bool = True

class KubernetesServiceDiscovery:
    """Kubernetes service discovery using DNS"""

    def __init__(self, namespace: str = 'production'):
        self.namespace = namespace

    def get_service_endpoints(self, service_name: str) -> List[ServiceEndpoint]:
        """Get service endpoints from Kubernetes DNS"""
        endpoints = []

        # Kubernetes DNS format: service-name.namespace.svc.cluster.local
        dns_name = f"{service_name}.{self.namespace}.svc.cluster.local"

        try:
            # Resolve DNS
            answers = dns.resolver.resolve(dns_name, 'A')
            for rdata in answers:
                endpoints.append(ServiceEndpoint(
                    host=str(rdata),
                    port=80,  # Default port
                    healthy=True
                ))
        except Exception as e:
            print(f"Error resolving service {service_name}: {e}")

        return endpoints

    def get_headless_service_endpoints(self, service_name: str) -> List[ServiceEndpoint]:
        """Get endpoints for headless service (StatefulSet)"""
        endpoints = []

        # Headless service returns individual pod IPs
        dns_name = f"{service_name}.{self.namespace}.svc.cluster.local"

        try:
            answers = dns.resolver.resolve(dns_name, 'A')
            for i, rdata in enumerate(answers):
                endpoints.append(ServiceEndpoint(
                    host=str(rdata),
                    port=80,
                    weight=1,
                    healthy=True
                ))
        except Exception as e:
            print(f"Error resolving headless service {service_name}: {e}")

        return endpoints

class ServiceClient:
    """Client for calling Kubernetes services"""

    def __init__(self):
        self.discovery = KubernetesServiceDiscovery()

    def call_service(self, service_name: str, path: str, 
                    method: str = 'GET', data: Dict[str, Any] = None) -> Dict[str, Any]:
        """Call a Kubernetes service"""
        endpoints = self.discovery.get_service_endpoints(service_name)

        if not endpoints:
            raise Exception(f"No endpoints found for service {service_name}")

        # Simple load balancing - round robin
        endpoint = endpoints[0]

        # In production, use proper HTTP client with retries
        import requests
        url = f"http://{endpoint.host}:{endpoint.port}{path}"

        response = requests.request(
            method=method,
            url=url,
            json=data,
            timeout=30
        )

        return response.json()

Horizontal Pod Autoscaler

# HPA based on CPU and memory
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: order-service-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: order-service
  minReplicas: 5
  maxReplicas: 50
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 80
    - type: Pods
      pods:
        metric:
          name: requests_per_second
        target:
          type: AverageValue
          averageValue: "1000"
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 60
      policies:
        - type: Percent
          value: 100
          periodSeconds: 60
        - type: Pods
          value: 10
          periodSeconds: 60
      selectPolicy: Max
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - type: Percent
          value: 10
          periodSeconds: 60

---
# VPA for right-sizing
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: order-service-vpa
  namespace: production
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: order-service
  updatePolicy:
    updateMode: "Auto"
  resourcePolicy:
    containerPolicies:
      - containerName: order-service
        minAllowed:
          cpu: "100m"
          memory: "128Mi"
        maxAllowed:
          cpu: "2000m"
          memory: "4Gi"
        controlledResources: ["cpu", "memory"]
python
# Custom metrics for HPA
from prometheus_client import Counter, Histogram, Gauge
import time

# Custom metrics
request_counter = Counter(
    'http_requests_total',
    'Total HTTP requests',
    ['method', 'endpoint', 'status']
)

request_duration = Histogram(
    'http_request_duration_seconds',
    'HTTP request duration',
    ['method', 'endpoint'],
    buckets=[.005, .01, .025, .05, .1, .25, .5, 1.0, 2.5, 5.0, 10.0]
)

active_connections = Gauge(
    'active_connections',
    'Number of active connections',
    ['service']
)

class MetricsCollector:
    """Collect custom metrics for HPA"""

    def __init__(self):
        self.requests_per_second = 0
        self.last_calculation = time.time()

    def record_request(self, method: str, endpoint: str, status: int, duration: float):
        """Record request metrics"""
        request_counter.labels(method=method, endpoint=endpoint, status=status).inc()
        request_duration.labels(method=method, endpoint=endpoint).observe(duration)

    def get_requests_per_second(self) -> float:
        """Calculate requests per second"""
        now = time.time()
        elapsed = now - self.last_calculation

        if elapsed >= 1.0:
            # Calculate RPS
            total_requests = request_counter._value.get()
            self.requests_per_second = total_requests / elapsed
            self.last_calculation = now

        return self.requests_per_second

âš ī¸HPA Best Practices

Use custom metrics for scaling based on business metrics. Set appropriate stabilization windows to prevent flapping. Combine HPA with VPA for right-sizing.

Pod Disruption Budget

# Pod Disruption Budget
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: order-service-pdb
  namespace: production
spec:
  minAvailable: 80%
  selector:
    matchLabels:
      app: order-service

---
# PDB with max unavailable
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: order-service-pdb-max-unavailable
  namespace: production
spec:
  maxUnavailable: 2
  selector:
    matchLabels:
      app: order-service

Network Policies

# Network policy for service isolation
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: order-service-network-policy
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: order-service
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: api-gateway
        - podSelector:
            matchLabels:
              app: payment-service
      ports:
        - protocol: TCP
          port: 8080
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: order-database
      ports:
        - protocol: TCP
          port: 5432
    - to:
        - podSelector:
            matchLabels:
              app: redis-cache
      ports:
        - protocol: TCP
          port: 6379
    - to:
        - namespaceSelector: {}
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53

Resource Quotas

# Resource quota for namespace
apiVersion: v1
kind: ResourceQuota
metadata:
  name: production-quota
  namespace: production
spec:
  hard:
    requests.cpu: "100"
    requests.memory: "200Gi"
    limits.cpu: "200"
    limits.memory: "400Gi"
    pods: "500"
    services: "100"
    persistentvolumeclaims: "50"
    configmaps: "200"
    secrets: "200"

---
# Limit range for default values
apiVersion: v1
kind: LimitRange
metadata:
  name: production-limit-range
  namespace: production
spec:
  limits:
    - type: Container
      default:
        cpu: "500m"
        memory: "512Mi"
      defaultRequest:
        cpu: "100m"
        memory: "128Mi"
      max:
        cpu: "4"
        memory: "8Gi"
      min:
        cpu: "50m"
        memory: "64Mi"

✅Kubernetes Best Practices

Use resource quotas to prevent resource exhaustion. Implement network policies for security. Use PDBs for availability during disruptions.

Summary

ComponentPurposeConfiguration
DeploymentPod managementRolling updates, replicas
ServiceService discoveryClusterIP, NodePort, LoadBalancer
HPAAuto-scalingCPU, memory, custom metrics
NetworkPolicySecurityIngress/egress rules
PDBAvailabilityminAvailable/maxUnavailable
ResourceQuotaResource managementCPU, memory, object limits
🔒

Premium Content

Container Orchestration: K8s, ECS, Service Discovery

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-28

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement