Lesson 12 / 15 · Production & Operations

Performance tuning

Performance tuning for a Go database: finding bottlenecks with pprof, cutting allocations with object pools, load testing and capacity planning.

3-4 hours advanced Not completed

On this page · 6 sections
  1. Identifying Bottlenecks
  2. Memory Optimization
  3. Load Testing
  4. Capacity Planning
  5. Lab: Performance Testing
  6. Quiz

With metrics in place you can tune with data instead of guesses. You will read a CPU profile, find lock contention, cut allocations with sync.Pool, write a load test that reports p50 and p99 latency, and find the throughput at which latency starts to climb.

Identifying Bottlenecks

Using CPU Profiler

$ go tool pprof cpu.prof

(pprof) top -cum
Showing top functions by cumulative time:
  40%  compaction
  25%  lock_acquire
  20%  serialization
  15%  memcpy

Interpretation

  • compaction is using 40% of CPU time → Focus optimization there first

  • lock_acquire is using 25% of CPU time → Check for lock contention

  • serialization is using 20% of CPU time → Optimize data encoding

  • memcpy is using 15% of CPU time → Ignore (not worth optimizing)

Lock Contention

Bad: Lock held too long

func (s *Store) Get(key string) interface{} {
    s.mu.Lock()
    defer s.mu.Unlock()
    
    val := s.data[key]          // Fast: 1µs
    processed := expensiveWork(val)  // Slow: 100µs
    return processed
}

Better: Minimize critical section

func (s *Store) Get(key string) interface{} {
    s.mu.Lock()
    val := s.data[key]
    s.mu.Unlock()
    
    // Do expensive work OUTSIDE lock
    return expensiveWork(val)
}

Memory Optimization

Object Pooling

import "sync"

var bufferPool = sync.Pool{
    New: func() interface{} {
        return make([]byte, 4096)
    },
}

// Get from pool
buf := bufferPool.Get().([]byte)
defer bufferPool.Put(buf)

// Use buffer
// ... work with buf ...

// Result: Reuse instead of allocate

Reduce Allocations

Bad

func formatKey(key []byte) string {
    return "prefix:" + string(key)  // Allocation every time
}

Better

func formatKey(key []byte) []byte {
    result := make([]byte, 7+len(key))
    copy(result[0:], []byte("prefix:"))
    copy(result[7:], key)
    return result  // Single allocation
}

Load Testing

Benchmark in Go

func BenchmarkGet(b *testing.B) {
    store := NewStore()
    store.Put("key", []byte("value"))
    
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        store.Get("key")
    }
}

// Run: go test -bench=. -benchmem
// Output: 50000000    20 ns/op    0 B/alloc

Load Test

type LoadTest struct {
    concurrency  int
    duration     time.Duration
    client       *Client
}

func (lt *LoadTest) Run() {
    done := time.Now().Add(lt.duration)
    count := 0
    errors := 0
    
    for i := 0; i < lt.concurrency; i++ {
        go func() {
            for time.Now().Before(done) {
                _, err := lt.client.Get("key")
                count++
                if err != nil {
                    errors++
                }
            }
        }()
    }
    
    fmt.Printf("Requests: %d, Errors: %d\n", count, errors)
}

Capacity Planning

Headroom

Desired throughput:     10,000 ops/sec
Target utilization:     70%
Required capacity:      14,286 ops/sec

Why headroom?
- Traffic spikes
- Maintenance
- Graceful degradation
- SLA buffer

Tuning by Workload

type Config struct {
    // Read-heavy workload
    CacheSize     int64   // Large: 512MB
    ShardCount    int     // High: cores × 4
    WalSyncFreq   int     // Low: every 1000 writes
    
    // Write-heavy workload
    MemtableSize  int64   // Large: 256MB
    ShardCount    int     // Medium: cores × 2
    WalSyncFreq   int     // High: every 100 writes
}

Lab: Performance Testing

Objective

Build a load-testing tool that records latency per worker, writes CPU and heap profiles, and finds the throughput knee.

Requirements

  • CPU and Memory Profiling: Identify bottlenecks with pprof

  • Load Testing: Multi-threaded stress testing framework

  • Memory Optimization: Object pooling and allocation reduction

  • Capacity Planning: Throughput and latency analysis

  • Benchmark Suite: Automated performance regression testing

  • Performance Monitoring: Real-time metrics during testing

Starter code

Fill in every TODO. The hints and a tested reference solution are further down.

type PerformanceTest struct {
    name   string
    store  Store
    result *TestResult
}

type TestResult struct {
    Operations    int64
    Errors        int64
    Throughput    float64
    AvgLatency    time.Duration
    P99Latency    time.Duration
}

func (pt *PerformanceTest) Run(concurrency int, duration time.Duration) *TestResult {
    // Run load test
    // Collect metrics
    // Return results
    return pt.result
}

// TODO: Implement profiling
func (pt *PerformanceTest) StartProfiling() {
    // Start CPU and memory profiling
}

// TODO: Implement load testing
func (pt *PerformanceTest) RunLoadTest(concurrency int, duration time.Duration) {
    // Multi-threaded load test
}

// TODO: Implement capacity planning
func (pt *PerformanceTest) AnalyzeCapacity() *CapacityReport {
    // Analyze throughput, latency, and capacity
    return &CapacityReport{}
}

Test Template

func TestPerformance(t *testing.T) {
    store := NewStore()
    pt := &PerformanceTest{
        name:  "GetOperation",
        store: store,
    }
    
    // Run performance test
    result := pt.Run(100, 30*time.Second)
    
    // Verify performance targets
    assert.True(t, result.Throughput > 10000, "Throughput too low")
    assert.True(t, result.AvgLatency < 1*time.Millisecond, "Latency too high")
    assert.True(t, result.P99Latency < 10*time.Millisecond, "P99 latency too high")
    assert.True(t, result.Errors == 0, "Should have no errors")
}

func BenchmarkGet(b *testing.B) {
    store := NewStore()
    store.Put("key", []byte("value"))
    
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        store.Get("key")
    }
}

func TestMemoryUsage(t *testing.T) {
    // Test memory allocation patterns
    // Verify object pooling is working
    // Check for memory leaks
}

Acceptance Criteria

  • CPU profiling identifies bottlenecks

  • Memory profiling shows optimization opportunities

  • The load test reports throughput and p50/p99 latency for your machine

  • go test -bench . -benchmem shows fewer allocations per op with pooling than without

  • The capacity estimate is based on those measured numbers

  • Benchmark suite catches performance regressions

  • Real-time monitoring during testing

  • > 90% code coverage

  • All tests pass

Hints

  • Give each worker goroutine its own latency slice and merge them at the end; a shared, locked slice would measure your lock instead of the database.
  • Report percentiles (p50, p99) rather than only the average: users feel the tail.
  • Compare runtime.MemStats.Mallocs before and after a run to get allocations per operation.
  • For capacity, double the concurrency until throughput stops growing. The knee is where you start queueing; plan for about 70% of the best rate that still meets your p99 target.

Reference solution

Try the lab on your own first, then compare. It runs a read/write load test with per-worker latency recording, reports throughput, p50/p99/max latency and allocations per op, writes CPU and heap profiles, and finds the throughput knee for capacity planning. It compiles and passes its tests with go test -race (Go 1.22 or newer).

Reference solution: perf.go
package perf

import (
    "context"
    "fmt"
    "math/rand"
    "os"
    "runtime"
    "runtime/pprof"
    "sort"
    "strconv"
    "sync"
    "sync/atomic"
    "time"
)

// Store is the database under test.
type Store interface {
    Get(ctx context.Context, key []byte) ([]byte, error)
    Put(ctx context.Context, key, value []byte) error
}

type TestResult struct {
    Concurrency int
    Duration    time.Duration
    Operations  int64
    Errors      int64
    Throughput  float64 // ops per second
    AvgLatency  time.Duration
    P50Latency  time.Duration
    P99Latency  time.Duration
    MaxLatency  time.Duration
    AllocsPerOp float64
}

type CapacityReport struct {
    Runs            []*TestResult
    BestConcurrency int
    PeakThroughput  float64
    // SafeThroughput is the highest measured rate whose p99 met the target, minus 30% headroom.
    SafeThroughput float64
    P99Target      time.Duration
    Notes          []string
}

type PerformanceTest struct {
    name      string
    store     Store
    ReadRatio float64 // share of operations that are reads, e.g. 0.8
    KeySpace  int
    ValueSize int
    results   []*TestResult
    stopProf  func() error
}

func NewPerformanceTest(name string, s Store) *PerformanceTest {
    return &PerformanceTest{name: name, store: s, ReadRatio: 0.8, KeySpace: 100_000, ValueSize: 128}
}

// StartProfiling writes a CPU profile now and a heap profile when the returned func is called.
func (pt *PerformanceTest) StartProfiling(dir string) (stop func() error, err error) {
    cpu, err := os.Create(fmt.Sprintf("%s/%s.cpu.pprof", dir, pt.name))
    if err != nil {
        return nil, err
    }
    if err := pprof.StartCPUProfile(cpu); err != nil {
        cpu.Close()
        return nil, err
    }
    return func() error {
        pprof.StopCPUProfile()
        cpu.Close()
        heap, err := os.Create(fmt.Sprintf("%s/%s.heap.pprof", dir, pt.name))
        if err != nil {
            return err
        }
        defer heap.Close()
        runtime.GC() // up-to-date live-heap numbers
        return pprof.WriteHeapProfile(heap)
        // Inspect with: go tool pprof -http=:8080 <file>
    }, nil
}

// Run is RunLoadTest plus bookkeeping for AnalyzeCapacity.
func (pt *PerformanceTest) Run(concurrency int, d time.Duration) *TestResult {
    r := pt.RunLoadTest(concurrency, d)
    pt.results = append(pt.results, r)
    return r
}

// RunLoadTest runs `concurrency` workers doing a read/write mix for duration d.
// Each worker keeps its own latency slice, so measuring does not add lock contention.
func (pt *PerformanceTest) RunLoadTest(concurrency int, d time.Duration) *TestResult {
    ctx, cancel := context.WithTimeout(context.Background(), d)
    defer cancel()
    // Preload some keys so reads hit.
    value := make([]byte, pt.ValueSize)
    for i := 0; i < min(pt.KeySpace, 10_000); i++ {
        pt.store.Put(context.Background(), []byte("key:"+strconv.Itoa(i)), value)
    }

    var ops, errs atomic.Int64
    lat := make([][]time.Duration, concurrency)
    var ms0, ms1 runtime.MemStats
    runtime.ReadMemStats(&ms0)
    start := time.Now()
    var wg sync.WaitGroup
    for w := 0; w < concurrency; w++ {
        wg.Add(1)
        go func(w int) {
            defer wg.Done()
            rng := rand.New(rand.NewSource(int64(w)))
            local := make([]time.Duration, 0, 4096)
            for ctx.Err() == nil {
                key := []byte("key:" + strconv.Itoa(rng.Intn(pt.KeySpace)))
                t0 := time.Now()
                var err error
                if rng.Float64() < pt.ReadRatio {
                    _, err = pt.store.Get(ctx, key)
                } else {
                    err = pt.store.Put(ctx, key, value)
                }
                local = append(local, time.Since(t0))
                ops.Add(1)
                if err != nil && ctx.Err() == nil {
                    errs.Add(1)
                }
            }
            lat[w] = local
        }(w)
    }
    wg.Wait()
    elapsed := time.Since(start)
    runtime.ReadMemStats(&ms1)

    var all []time.Duration
    for _, l := range lat {
        all = append(all, l...)
    }
    sort.Slice(all, func(i, j int) bool { return all[i] < all[j] })
    r := &TestResult{Concurrency: concurrency, Duration: elapsed, Operations: ops.Load(), Errors: errs.Load()}
    if n := len(all); n > 0 {
        var sum time.Duration
        for _, x := range all {
            sum += x
        }
        r.AvgLatency = sum / time.Duration(n)
        r.P50Latency = all[n*50/100]
        r.P99Latency = all[min(n-1, n*99/100)]
        r.MaxLatency = all[n-1]
        r.Throughput = float64(n) / elapsed.Seconds()
        r.AllocsPerOp = float64(ms1.Mallocs-ms0.Mallocs) / float64(n)
    }
    return r
}

// AnalyzeCapacity runs the load test at rising concurrency until throughput stops
// growing, then reports the knee and a safe planning number.
func (pt *PerformanceTest) AnalyzeCapacity(p99Target time.Duration, step time.Duration) *CapacityReport {
    rep := &CapacityReport{P99Target: p99Target}
    prev := 0.0
    for c := 1; c <= 256; c *= 2 {
        r := pt.Run(c, step)
        rep.Runs = append(rep.Runs, r)
        if r.Throughput > rep.PeakThroughput {
            rep.PeakThroughput, rep.BestConcurrency = r.Throughput, c
        }
        if r.P99Latency <= p99Target && r.Throughput*0.7 > rep.SafeThroughput {
            rep.SafeThroughput = r.Throughput * 0.7
        }
        if prev > 0 && r.Throughput < prev*1.05 {
            rep.Notes = append(rep.Notes, fmt.Sprintf("throughput flattened at concurrency %d: likely lock contention or CPU saturation, profile here", c))
            break
        }
        prev = r.Throughput
    }
    if rep.SafeThroughput == 0 {
        rep.Notes = append(rep.Notes, "p99 target never met: optimise before planning capacity")
    }
    return rep
}

func (r *TestResult) String() string {
    return fmt.Sprintf("c=%d ops=%d err=%d %.0f ops/s avg=%v p50=%v p99=%v max=%v allocs/op=%.1f",
        r.Concurrency, r.Operations, r.Errors, r.Throughput, r.AvgLatency, r.P50Latency, r.P99Latency, r.MaxLatency, r.AllocsPerOp)
}
Tests: perf_test.go
package perf

import (
    "context"
    "sync"
    "testing"
    "time"
)

type mapStore struct {
    mu sync.RWMutex
    m  map[string][]byte
}

func (s *mapStore) Get(_ context.Context, k []byte) ([]byte, error) {
    s.mu.RLock()
    defer s.mu.RUnlock()
    return s.m[string(k)], nil
}
func (s *mapStore) Put(_ context.Context, k, v []byte) error {
    s.mu.Lock()
    s.m[string(k)] = v
    s.mu.Unlock()
    return nil
}

func TestLoadAndCapacity(t *testing.T) {
    pt := NewPerformanceTest("map", &mapStore{m: map[string][]byte{}})
    stop, err := pt.StartProfiling(t.TempDir())
    if err != nil {
        t.Fatal(err)
    }
    r := pt.Run(4, 200*time.Millisecond)
    if err := stop(); err != nil {
        t.Fatal(err)
    }
    t.Log(r)
    if r.Operations == 0 || r.Errors != 0 || r.P99Latency < r.P50Latency {
        t.Fatal(r)
    }
    rep := pt.AnalyzeCapacity(10*time.Millisecond, 100*time.Millisecond)
    t.Logf("peak %.0f ops/s at c=%d, plan for %.0f; %v", rep.PeakThroughput, rep.BestConcurrency, rep.SafeThroughput, rep.Notes)
    if rep.PeakThroughput <= 0 {
        t.Fatal("no throughput")
    }
}

Quiz

  1. A CPU profile shows most time in sync.(*Mutex).Lock. What does it mean?
  2. What does sync.Pool help with?
  3. Why plan capacity with headroom instead of running near 100%?
Show answers
  1. Lock contention: goroutines wait for the same lock. Shard the data, shorten critical sections or use read locks.
  2. Reusing short-lived objects such as buffers, cutting allocations and garbage-collector pressure.
  3. Latency rises sharply near saturation, and spikes or a failed node would push the system over.

Done with this lesson?

Marking it complete updates the sidebar, the course page and the Continue button.