Golang / GoLang System Architecture and Testing Interview Questions
How do you achieve zero-downtime deployments for a Go microservice in Kubernetes?
Zero-downtime deployment means in-flight requests complete before old pods terminate, and new pods are ready before traffic is routed to them. This requires coordination between the Go service and Kubernetes lifecycle hooks.
// Key components: // 1. Graceful shutdown in the Go service func main() { srv := &http.Server{Addr: ":8080", Handler: router} go func() { srv.ListenAndServe() }() quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGTERM) // k8s sends SIGTERM <-quit // Give in-flight requests time to complete ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) defer cancel() srv.Shutdown(ctx) // stop accepting; drain active connections db.Close() // close DB connections cleanly log.Println("shutdown complete") } // 2. Kubernetes deployment configuration // deployment.yaml (relevant sections): // spec.template.spec.containers: // lifecycle: // preStop: // exec: // command: ["sleep", "5"] // # SIGTERM is sent AFTER preStop // terminationGracePeriodSeconds: 30 # must be > service shutdown timeout // 3. Rolling update strategy // strategy: // type: RollingUpdate // rollingUpdate: // maxSurge: 1 # start 1 new pod before killing old // maxUnavailable: 0 # never kill old until new is Ready // 4. Readiness probe â k8s only sends traffic when this returns 200 // readinessProbe: // httpGet: // path: /readyz // port: 8080 // initialDelaySeconds: 5 # wait for startup // periodSeconds: 5 // failureThreshold: 3
preStop hook timing: when Kubernetes terminates a pod, it sends SIGTERM and simultaneously removes the pod from the Service endpoints. There is a propagation delay (~5s) before kube-proxy and ingress controllers stop routing. The preStop sleep 5 delays SIGTERM so the graceful shutdown starts after traffic has stopped arriving.
More Related questions...