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.

Fault Injection in Go

Module 10 Lesson 10.b 50 min Difficulty 3/5

Prerequisites 10.a, 6.c

The idea in one minute#

Infrastructure chaos tools inject faults from outside the process. You can also build fault injection into your code: a wrapper around each dependency client that can add latency, return errors or hang, switched on by configuration, a flag or a request header. Then you can test resilience in unit tests, in CI, in staging and — carefully — for a sliver of production traffic, at the exact layer where your timeouts, retries, breakers and fallbacks live.

Combine it with an experiment runner that measures the steady state before, during and after the fault, and aborts automatically if the SLI drops below a threshold.

An analogy#

A flight simulator with an instructor’s console: the instructor can fail an engine, ice the wings, or kill the radio at the press of a button, and stop it at any moment. The pilot trains the real reactions, without a real aeroplane at risk.

A picture#

flowchart LR
  H[":go: <b>Handler</b>"] --> FI["<b>Fault injector</b><br/><small>latency · error · hang<br/>rate, scope, kill switch</small>"]
  FI --> C[":go: <b>Dependency client</b><br/><small>timeout, retry, breaker, fallback</small>"]
  C --> D[":i-server: Dependency"]
  CFG[":i-wrench: Config / flag / header<br/><small>x-fault: pricing=latency:400ms</small>"] -.-> FI
  RUN[":i-flask-conical: <b>Experiment runner</b><br/><small>baseline → inject → recover<br/>abort on SLI</small>"] -.-> CFG
  class H,C compute
  class FI warn
  class D io
  class CFG neutral
  class RUN queue

How it really works#

Where to inject#

Inject at the boundary of each dependency — the client interface — so the code above it sees exactly what it would see in a real failure: a slow response, an error value, a context deadline. In Go, define the dependency as an interface and wrap it:

Go
type Pricing interface {
	Price(ctx context.Context, sku string) (float64, error)
}

type faulty struct {
	next Pricing
	cfg  *FaultConfig // latency, error rate, hang; read atomically
}

func (f faulty) Price(ctx context.Context, sku string) (float64, error) {
	if err := f.cfg.inject(ctx); err != nil {
		return 0, err
	}
	return f.next.Price(ctx, sku)
}

For HTTP clients, the same idea fits an http.RoundTripper; for servers, an HTTP middleware; for gRPC, interceptors.

Kinds of fault#

FaultImplementationTests
LatencySleep (respecting ctx.Done()) before callingTimeouts, deadline propagation
ErrorReturn a typed error (e.g. 503-equivalent) without callingRetries, breakers, fallbacks
HangBlock until the context is cancelledTimeouts — the most commonly missing one
PartialReturn truncated or malformed dataValidation, parsing robustness
Slow dripReturn data slowly (for streams)Read timeouts, buffer handling

Controls you must have#

  • Rate: a percentage of calls (deterministic per request ID for reproducibility).
  • Scope: only for requests marked as test traffic (a header such as x-fault, accepted only from authenticated internal callers), or only in staging.
  • Kill switch: a flag that disables all injection instantly; default off.
  • Expiry: every enabled fault has an end time, so a forgotten experiment does not run for weeks.
  • Visibility: a metric faults_injected_total{dependency,kind} and a log line per injected fault, so nobody debugs a fault you caused.

Testing resilience in CI#

The same wrapper makes resilience unit-testable: inject “pricing hangs” and assert the handler returns a fallback within 200 ms. These tests catch the regression where someone removes a timeout — long before production does.

A worked example#

A product handler calls pricing (hard dependency, timeout 150 ms, falls back to a cached price) and reviews (soft, timeout 100 ms, omitted on failure). The experiment:

PhaseFaultExpected
Baseline (60 requests)Nonesuccess ≥ 99.9%, p99 a few ms
Inject (120 requests)Reviews: 100% errors; pricing: +400 ms on 30%success ≥ 99.9% (degraded allowed); p99 < 200 ms
Recover (60 requests)NoneBack to baseline
Abort ifsuccess < 99% (after at least 20 requests)Stop injecting immediately

The program runs exactly this experiment in simulated time, twice: once with the fallbacks in place, and once with the pricing fallback “accidentally removed”, to show the abort condition stopping the experiment.

Code#

Go
// faults.go — a fault-injecting dependency wrapper and an experiment runner with abort conditions.
package main

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"sort"
	"sync/atomic"
	"time"
)

var errInjected = errors.New("injected fault: 503")

type Fault struct {
	ErrorRate   float64
	LatencyRate float64
	Latency     time.Duration
	enabled     atomic.Bool // the kill switch
}

// inject applies the configured fault. It respects the caller's context, as a real slow call would.
func (f *Fault) inject(ctx context.Context, r *rand.Rand) error {
	if !f.enabled.Load() {
		return nil
	}
	if r.Float64() < f.ErrorRate {
		return errInjected
	}
	if r.Float64() < f.LatencyRate {
		select {
		case <-time.After(f.Latency):
		case <-ctx.Done():
			return ctx.Err()
		}
	}
	return nil
}

type service struct {
	r                       *rand.Rand
	pricingFault, revsFault *Fault
	pricingFallback         bool
	degraded                atomic.Int64
}

// handle simulates one product-page request; it returns latency and whether the user got a page.
func (s *service) handle() (time.Duration, bool) {
	start := time.Now()
	ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
	err := s.pricingFault.inject(ctx, s.r)
	cancel()
	if err != nil {
		if !s.pricingFallback {
			return time.Since(start), false // no fallback: the page fails
		}
		s.degraded.Add(1) // serve the cached price
	}
	rctx, rcancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	if s.revsFault.inject(rctx, s.r) != nil {
		s.degraded.Add(1) // render without reviews
	}
	rcancel()
	time.Sleep(time.Duration(2+s.r.Intn(4)) * time.Millisecond) // the page's own work
	return time.Since(start), true
}

type window struct {
	ok, total int
	lat       []time.Duration
}

func (w window) success() float64 { return float64(w.ok) / float64(w.total) }
func (w window) p99() time.Duration {
	sort.Slice(w.lat, func(i, j int) bool { return w.lat[i] < w.lat[j] })
	return w.lat[int(0.99*float64(len(w.lat)-1))]
}

func experiment(name string, pricingFallback bool) {
	s := &service{
		r:               rand.New(rand.NewSource(4)),
		pricingFault:    &Fault{LatencyRate: 0.3, Latency: 400 * time.Millisecond},
		revsFault:       &Fault{ErrorRate: 1},
		pricingFallback: pricingFallback,
	}
	fmt.Printf("\n%s\n", name)
	phases := []struct {
		name   string
		inject bool
		n      int
	}{{"baseline", false, 60}, {"inject", true, 120}, {"recover", false, 60}}
	const abortBelow = 0.99
	for _, ph := range phases {
		s.pricingFault.enabled.Store(ph.inject)
		s.revsFault.enabled.Store(ph.inject)
		var w window
		aborted := false
		for i := 0; i < ph.n; i++ {
			lat, ok := s.handle()
			w.total++
			w.lat = append(w.lat, lat)
			if ok {
				w.ok++
			}
			if ph.inject && w.total >= 20 && w.success() < abortBelow {
				s.pricingFault.enabled.Store(false) // ABORT: kill switch
				s.revsFault.enabled.Store(false)
				aborted = true
				break
			}
		}
		fmt.Printf("  %-9s requests %3d  success %6.2f%%  p99 %4dms", ph.name, w.total, 100*w.success(), w.p99().Milliseconds())
		if aborted {
			fmt.Printf("  ← ABORTED: success below %.0f%%, faults switched off", abortBelow*100)
			fmt.Println()
			break
		}
		fmt.Println()
	}
	fmt.Printf("  degraded responses: %d\n", s.degraded.Load())
}

func main() {
	experiment("hypothesis: the product page survives reviews down + slow pricing", true)
	experiment("same experiment after the pricing fallback was accidentally removed", false)
}

The first run confirms the hypothesis: every request succeeds, some degraded, with p99 held near the 150 ms pricing timeout. The second run aborts after 20 requests — exactly what an abort condition is for: the experiment found the regression and stopped before hurting more users.

Remember this#

  • Inject faults at the dependency boundary (interface wrapper, RoundTripper, middleware, interceptor) so the code above sees a realistic failure.
  • Latency, errors, hangs, partial data; always respect the context.
  • Controls: rate, scope (test traffic only), kill switch default off, expiry, metrics and logs.
  • An experiment runner measures baseline, injection and recovery, and aborts on the SLI.
  • The same wrapper makes resilience unit-testable in CI.

Try it#

  1. Run faults.go. Change the pricing timeout to 500 ms. What happens to the p99 during injection?
  2. Write a Go test that injects “pricing hangs forever” and asserts the handler returns within 200 ms.
  3. Implement the wrapper as an http.RoundTripper that reads an x-fault header.

Check yourself#

  1. Why inject at the dependency client rather than in the handler?
  2. Why must injected latency respect ctx.Done()?
  3. Which control stops a forgotten experiment from running for weeks?
  4. What does the abort condition protect in the second run?

Sources#

↑↓ navigate↵ openesc close

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