Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Graceful Degradation and Shutdown

Module 6 Lesson 6.f 50 min Difficulty 3/5

Prerequisites 6.a, 6.d

The idea in one minute#

Graceful degradation means doing less instead of nothing. When a dependency is down or the service is overloaded, it serves a reduced but useful response: the product page without recommendations, cached prices, search without personalisation, read-only mode. Users get most of the value; the service stays up. The degraded modes are designed, built and tested in advance — they are features.

Graceful shutdown means stopping without dropping requests. Every deploy, scale-down and node drain stops processes, many times a day. A process that dies mid-request turns routine operations into errors. The sequence is: stop receiving new work (fail readiness), wait for the load balancer to notice, finish in-flight work within a deadline, close connections, exit.

An analogy#

A restaurant whose dishwasher breaks switches to paper plates and a shorter menu instead of closing (degradation). At closing time it stops seating new guests, lets those already eating finish, then locks the doors — it does not switch off the lights on people mid-meal (shutdown).

A picture#

sequenceDiagram
  participant K as Kubernetes
  participant P as Pod (Go service)
  participant LB as Endpoints / LB
  K->>P: SIGTERM (pod is terminating)
  K->>LB: remove pod from endpoints (in parallel, takes a few seconds)
  P->>P: readiness → failing
  Note over P: keep serving for ~5–10 s<br/>(LB may still send requests)
  P->>P: http.Server.Shutdown(ctx): stop accepting,<br/>finish in-flight requests
  P->>P: flush logs, metrics, close DB pools
  P-->>K: exit 0 (before terminationGracePeriodSeconds)

How it really works#

Designing degraded modes#

For each dependency, decide what the service does without it:

DependencyDegraded behaviour
RecommendationsHide the section, or show static best-sellers
PersonalisationServe the generic page
Pricing serviceServe cached prices with a short TTL; block checkout if the cache is too old
Search ranking modelFall back to simple keyword ranking
Payment provider ARoute to provider B (with higher fees)
Primary databaseRead-only mode from a replica: browse works, orders queue or wait
Everything (overload)“Static mode”: a cached, pre-rendered version of the top pages from a CDN

Rules:

  • Decide per dependency, in advance, with product owners. “What should a user see when reviews are down?” is a product question.
  • Mark degraded responses (a response header, a metric degraded_responses_total{reason}) so you know how often it happens and SLIs can count it (a “quality” SLI, 2.a).
  • Test degraded modes regularly (Module 10). A fallback that has never run is a hypothesis; untested fallback code paths often fail exactly when needed.
  • Prefer static, simple fallbacks. A fallback that calls a second complex service is a new dependency, not a fallback.
  • Use kill switches: feature flags (8.c) that turn expensive features off instantly.

Stale-while-revalidate and caching for resilience#

A cache can hide a dependency’s outage if it is allowed to serve stale data when the dependency fails. HTTP has this built in: Cache-Control: max-age=60, stale-if-error=86400 lets a CDN serve a day-old copy if the origin errors. In code, keep the last good value and its age, serve it on error, and alert on its age.

Graceful shutdown in Kubernetes#

What happens when a pod is deleted:

  1. The pod is marked Terminating. In parallel: kubelet runs the preStop hook (if any) then sends SIGTERM; the endpoints controller removes the pod from Services. These happen at the same time, and load balancers and kube-proxy on every node take a few seconds to update.
  2. If the process exits immediately on SIGTERM, requests still being routed to it in those seconds fail. So the process should keep serving briefly (or use a preStop sleep).
  3. After terminationGracePeriodSeconds (default 30 s), kubelet sends SIGKILL.

Therefore:

  • On SIGTERM: mark not-ready, keep serving for a short delay (5–10 s), then call http.Server.Shutdown with a deadline shorter than the grace period.
  • Shutdown stops accepting connections, closes idle ones, and waits for active requests.
  • Long-lived connections (WebSockets, gRPC streams) need explicit draining: Shutdown does not wait for hijacked connections; tell clients to reconnect elsewhere (GOAWAY for HTTP/2 and gRPC — grpc.Server.GracefulStop).
  • Background workers: stop taking new jobs, finish or checkpoint the current one, and make jobs safe to retry elsewhere.
  • Set terminationGracePeriodSeconds longer than delay + the longest request.
YAML
spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: checkout
      readinessProbe:
        httpGet: { path: /readyz, port: 8080 }
        periodSeconds: 2
        failureThreshold: 1
      lifecycle:
        preStop:
          sleep: { seconds: 5 }   # native sleep action (Kubernetes 1.30+); or exec "sleep 5"

Startup matters too#

The mirror image: a new instance should report ready only when it can serve well — config loaded, connections established, caches warmed if needed — and the load balancer should give it traffic gradually (slow start; Envoy and most cloud load balancers support it). Otherwise every deploy creates a burst of slow requests.

A worked example#

A team sees a burst of 502s at every deploy — about 0.05% of the day’s requests, a fifth of the monthly error budget spent on routine deploys.

Investigation: on SIGTERM the Go service called os.Exit immediately; the load balancer kept sending requests to it for about 3 seconds; long checkout requests in flight were cut off.

Fix:

  1. Readiness endpoint returns 503 once shutdown starts.
  2. Wait 8 seconds (longer than the LB’s update time), still serving.
  3. server.Shutdown(ctx) with a 25-second timeout.
  4. terminationGracePeriodSeconds: 40.

Deploy-time errors dropped to zero, and deploys became boring — which is the goal.

Code#

A complete Go HTTP server with readiness, graceful shutdown on SIGTERM, and a degraded fallback for a flaky dependency. It serves HTTP, so gocheck -run skips it. Run it with go run server.go, call curl localhost:8080/product, then press Ctrl-C while a slow request is in flight and watch it finish.

Go
// server.go — readiness, graceful shutdown on SIGTERM, and a degraded fallback for a dependency.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"log"
	"math/rand"
	"net/http"
	"os"
	"os/signal"
	"sync"
	"sync/atomic"
	"syscall"
	"time"
)

var ready atomic.Bool
var degraded atomic.Int64

// recommendations is a flaky dependency; lastGood is the stale value we serve when it fails.
var (
	mu       sync.Mutex
	lastGood = []string{"best-seller-1", "best-seller-2"}
	lastAt   = time.Now()
)

func recommendations(ctx context.Context) ([]string, error) {
	select {
	case <-time.After(time.Duration(rand.Intn(300)) * time.Millisecond):
	case <-ctx.Done():
		return nil, ctx.Err()
	}
	if rand.Intn(3) == 0 {
		return nil, errors.New("recommendations: 503")
	}
	return []string{"item-42", "item-7", "item-99"}, nil
}

func product(w http.ResponseWriter, r *http.Request) {
	// The core of the page: always served.
	resp := map[string]any{"id": "sku-123", "name": "Walking boots", "price": "89.00"}

	// Soft dependency with a tight timeout and a stale fallback.
	ctx, cancel := context.WithTimeout(r.Context(), 150*time.Millisecond)
	defer cancel()
	recs, err := recommendations(ctx)
	mu.Lock()
	if err == nil {
		lastGood, lastAt = recs, time.Now()
	} else {
		recs = lastGood
		degraded.Add(1)
		w.Header().Set("X-Degraded", "recommendations")
		resp["recommendations_age_s"] = int(time.Since(lastAt).Seconds())
	}
	mu.Unlock()
	resp["recommendations"] = recs

	time.Sleep(2 * time.Second) // pretend the page is slow, so shutdown has in-flight work to wait for
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(resp)
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/product", product)
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) }) // liveness
	mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) {                           // readiness
		if !ready.Load() {
			http.Error(w, "shutting down", http.StatusServiceUnavailable)
			return
		}
		w.Write([]byte("ready"))
	})

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       60 * time.Second,
	}

	go func() {
		log.Println("listening on :8080")
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()
	ready.Store(true)

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, syscall.SIGTERM, os.Interrupt)
	<-stop

	log.Println("SIGTERM: failing readiness, still serving while the load balancer catches up")
	ready.Store(false)
	time.Sleep(5 * time.Second) // in Kubernetes: longer than endpoint propagation

	ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
	defer cancel()
	log.Println("shutting down: no new connections, waiting for in-flight requests")
	if err := srv.Shutdown(ctx); err != nil {
		log.Printf("forced shutdown: %v", err)
	}
	log.Printf("clean exit; %d degraded responses served", degraded.Load())
}

Remember this#

  • Degraded modes are features: designed per dependency with product owners, marked, measured, tested.
  • Prefer simple, static fallbacks and kill switches; serve stale data on error and alert on its age.
  • Graceful shutdown: fail readiness, keep serving for a few seconds, Shutdown with a deadline, drain streams and workers, exit before the grace period.
  • Readiness only when truly ready; slow-start new instances.

Try it#

  1. Run server.go. In another terminal: for i in 1 2 3 4 5; do curl -s -i localhost:8080/product | grep -i -E "x-degraded|recommendations"; done. How often is the response degraded?
  2. Start a request, then press Ctrl-C within a second. Does the request complete?
  3. Remove the 5-second sleep and deploy to a kind cluster behind a Service, under load from hey or k6. Count the errors during a rollout with and without it.

Check yourself#

  1. Why should degraded modes be decided with product owners?
  2. Why can a pod receive requests after it has been sent SIGTERM?
  3. What does http.Server.Shutdown do, and what does it not wait for?
  4. What is slow start, and which problem does it solve?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in