Lesson 13 / 15 · Production & Operations

Deployment & configuration

Deploy a Go database: configuration with YAML, TOML and env vars, Docker and Docker Compose, Kubernetes manifests, backups and graceful shutdown.

2-3 hours advanced Not completed

On this page · 6 sections
  1. Configuration Management
  2. Docker Containerization
  3. Kubernetes Deployment
  4. Backup and Recovery
  5. Lab: Production Deployment
  6. Quiz

Shipping the database means configuration, packaging and a way back when things go wrong. You will load config from a file with environment overrides, build a small Docker image, run it on Kubernetes as a StatefulSet, and script backups you have actually restored from.

Configuration Management

Configuration File Formats

YAML Configuration

# config.yaml
server:
  host: "0.0.0.0"
  port: 6379
  max_connections: 10000

database:
  memtable_size: 67108864  # 64MB
  shard_count: 16
  wal_sync_interval: 100

replication:
  mode: "semi-sync"
  min_replicas: 1
  timeout_ms: 5000

cluster:
  nodes:
    - "node1:6379"
    - "node2:6379"
    - "node3:6379"
  
monitoring:
  metrics_port: 9090
  health_port: 8080

TOML Configuration

# config.toml
[server]
host = "0.0.0.0"
port = 6379
max_connections = 10000

[database]
memtable_size = 67108864
shard_count = 16
wal_sync_interval = 100

[replication]
mode = "semi-sync"
min_replicas = 1
timeout_ms = 5000

[[cluster.nodes]]
address = "node1:6379"

[[cluster.nodes]]
address = "node2:6379"

Loading Configuration

package config

import (
    "fmt"
    "os"
    "github.com/spf13/viper"
)

type Config struct {
    Server struct {
        Host           string
        Port           int
        MaxConnections int
    }
    
    Database struct {
        MemtableSize   int64
        ShardCount     int
        WalSyncInterval int
    }
    
    Replication struct {
        Mode        string
        MinReplicas int
        TimeoutMs   int
    }
    
    Cluster struct {
        Nodes []string
    }
    
    Monitoring struct {
        MetricsPort int
        HealthPort  int
    }
}

// LoadConfig loads configuration from file
func LoadConfig(filepath string) (*Config, error) {
    viper.SetConfigFile(filepath)
    viper.SetConfigType("yaml")
    
    // Read config file
    if err := viper.ReadInConfig(); err != nil {
        return nil, fmt.Errorf("error reading config: %w", err)
    }
    
    var cfg Config
    if err := viper.Unmarshal(&cfg); err != nil {
        return nil, fmt.Errorf("error unmarshaling config: %w", err)
    }
    
    return &cfg, nil
}

// LoadConfigWithDefaults loads with defaults
func LoadConfigWithDefaults() *Config {
    viper.SetDefault("server.host", "0.0.0.0")
    viper.SetDefault("server.port", 6379)
    viper.SetDefault("server.max_connections", 10000)
    viper.SetDefault("database.memtable_size", 67108864)
    viper.SetDefault("database.shard_count", 16)
    
    cfg, _ := LoadConfig("config.yaml")
    return cfg
}

Environment Variables

// Override config with environment variables
func LoadConfigFromEnv() *Config {
    viper.AutomaticEnv()
    viper.SetEnvPrefix("KVDB")
    
    // Usage: KVDB_SERVER_PORT=7000
    
    cfg, _ := LoadConfig("config.yaml")
    return cfg
}

// Example environment variables:
// KVDB_SERVER_HOST=0.0.0.0
// KVDB_SERVER_PORT=6379
// KVDB_DATABASE_SHARD_COUNT=32
// KVDB_REPLICATION_MODE=sync

Configuration Validation

// ValidateConfig checks configuration for errors
func (c *Config) Validate() error {
    if c.Server.Port <= 0 || c.Server.Port > 65535 {
        return fmt.Errorf("invalid port: %d", c.Server.Port)
    }
    
    if c.Database.MemtableSize <= 0 {
        return fmt.Errorf("invalid memtable size: %d", c.Database.MemtableSize)
    }
    
    if c.Database.ShardCount <= 0 || c.Database.ShardCount > 256 {
        return fmt.Errorf("invalid shard count: %d", c.Database.ShardCount)
    }
    
    if c.Replication.Mode != "async" && c.Replication.Mode != "sync" && c.Replication.Mode != "semi-sync" {
        return fmt.Errorf("invalid replication mode: %s", c.Replication.Mode)
    }
    
    if len(c.Cluster.Nodes) == 0 {
        return fmt.Errorf("no cluster nodes configured")
    }
    
    return nil
}

Docker Containerization

Dockerfile

# Multi-stage build for small image
FROM golang:1.21-alpine AS builder

WORKDIR /build

# Copy go mod files
COPY go.mod go.sum ./

# Download dependencies
RUN go mod download

# Copy source code
COPY . .

# Build binary
RUN CGO_ENABLED=0 GOOS=linux go build -o kvdb ./cmd/server

# Final stage
FROM alpine:3.18

# Install runtime dependencies
RUN apk add --no-cache ca-certificates tzdata

# Create app user
RUN addgroup -g 1000 app && adduser -D -u 1000 -G app app

WORKDIR /app

# Copy binary from builder
COPY --from=builder /build/kvdb .

# Copy config
COPY config.yaml .

# Change ownership
RUN chown -R app:app /app

# Switch to non-root user
USER app

# Expose ports
EXPOSE 6379 9090 8080

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost:8080/healthz || exit 1

# Run server
CMD ["./kvdb", "-config", "config.yaml"]

Docker Compose for Local Development

# docker-compose.yml
version: '3.8'

services:
  kvdb-1:
    build: .
    container_name: kvdb-1
    ports:
      - "6379:6379"
      - "9090:9090"
      - "8080:8080"
    environment:
      - KVDB_SERVER_HOST=0.0.0.0
      - KVDB_SERVER_PORT=6379
      - KVDB_CLUSTER_NODES=kvdb-1:6379,kvdb-2:6379,kvdb-3:6379
    volumes:
      - kvdb-1-data:/data
      - ./config.yaml:/app/config.yaml
    networks:
      - kvdb-network
    healthcheck:
      test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:8080/healthz"]
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 10s

  kvdb-2:
    build: .
    container_name: kvdb-2
    ports:
      - "6380:6379"
      - "9091:9090"
      - "8081:8080"
    environment:
      - KVDB_SERVER_HOST=0.0.0.0
      - KVDB_CLUSTER_NODES=kvdb-1:6379,kvdb-2:6379,kvdb-3:6379
    volumes:
      - kvdb-2-data:/data
      - ./config.yaml:/app/config.yaml
    networks:
      - kvdb-network
    depends_on:
      - kvdb-1

  kvdb-3:
    build: .
    container_name: kvdb-3
    ports:
      - "6381:6379"
      - "9092:9090"
      - "8082:8080"
    environment:
      - KVDB_SERVER_HOST=0.0.0.0
      - KVDB_CLUSTER_NODES=kvdb-1:6379,kvdb-2:6379,kvdb-3:6379
    volumes:
      - kvdb-3-data:/data
      - ./config.yaml:/app/config.yaml
    networks:
      - kvdb-network
    depends_on:
      - kvdb-1

volumes:
  kvdb-1-data:
  kvdb-2-data:
  kvdb-3-data:

networks:
  kvdb-network:
    driver: bridge

Building and Running

# Build Docker image
docker build -t kvdb:latest .

# Run container
docker run -p 6379:6379 -p 9090:9090 -p 8080:8080 kvdb:latest

# Run with custom config
docker run -p 6379:6379 \
  -v $(pwd)/config.yaml:/app/config.yaml \
  kvdb:latest ./kvdb -config /app/config.yaml

# Local cluster with Docker Compose
docker-compose up -d

# View logs
docker-compose logs -f kvdb-1

# Stop cluster
docker-compose down

Kubernetes Deployment

Deployment Manifest

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kvdb
  namespace: default
spec:
  replicas: 3
  selector:
    matchLabels:
      app: kvdb
  template:
    metadata:
      labels:
        app: kvdb
    spec:
      containers:
      - name: kvdb
        image: kvdb:latest
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 6379
          name: server
        - containerPort: 9090
          name: metrics
        - containerPort: 8080
          name: health
        
        env:
        - name: KVDB_SERVER_HOST
          value: "0.0.0.0"
        - name: KVDB_SERVER_PORT
          value: "6379"
        - name: KVDB_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: KVDB_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        
        livenessProbe:
          httpGet:
            path: /healthz
            port: health
          initialDelaySeconds: 10
          periodSeconds: 10
          timeoutSeconds: 3
          failureThreshold: 3
        
        readinessProbe:
          httpGet:
            path: /readyz
            port: health
          initialDelaySeconds: 5
          periodSeconds: 5
          timeoutSeconds: 3
          failureThreshold: 2
        
        resources:
          requests:
            cpu: 500m
            memory: 512Mi
          limits:
            cpu: 2000m
            memory: 2Gi
        
        volumeMounts:
        - name: data
          mountPath: /data
        - name: config
          mountPath: /app/config.yaml
          subPath: config.yaml
      
      volumes:
      - name: data
        emptyDir: {}
      - name: config
        configMap:
          name: kvdb-config

Service Manifest

# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: kvdb
  namespace: default
spec:
  type: ClusterIP
  ports:
  - port: 6379
    targetPort: 6379
    protocol: TCP
    name: server
  - port: 9090
    targetPort: 9090
    protocol: TCP
    name: metrics
  selector:
    app: kvdb
---
apiVersion: v1
kind: Service
metadata:
  name: kvdb-headless
  namespace: default
spec:
  type: ClusterIP
  clusterIP: None
  ports:
  - port: 6379
    targetPort: 6379
  selector:
    app: kvdb

ConfigMap

# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: kvdb-config
data:
  config.yaml: |
    server:
      host: "0.0.0.0"
      port: 6379
      max_connections: 10000
    
    database:
      memtable_size: 67108864
      shard_count: 16
      wal_sync_interval: 100
    
    replication:
      mode: "semi-sync"
      min_replicas: 1
      timeout_ms: 5000
    
    cluster:
      nodes:
        - "kvdb-0:6379"
        - "kvdb-1:6379"
        - "kvdb-2:6379"

Deploy to Kubernetes

# Create namespace
kubectl create namespace kvdb

# Apply ConfigMap
kubectl apply -f configmap.yaml

# Apply Deployment
kubectl apply -f deployment.yaml

# Apply Service
kubectl apply -f service.yaml

# Check deployment status
kubectl get deployment kvdb

# View pods
kubectl get pods -l app=kvdb

# View logs
kubectl logs deployment/kvdb -f

# Port forward for testing
kubectl port-forward svc/kvdb 6379:6379

# Scale replicas
kubectl scale deployment kvdb --replicas=5

# Delete deployment
kubectl delete deployment kvdb

Backup and Recovery

Backup Strategy

// BackupManager handles database backups
type BackupManager struct {
    backupDir  string
    store      Store
    logger     *zap.Logger
}

// CreateBackup creates point-in-time backup
func (bm *BackupManager) CreateBackup(name string) error {
    backupPath := filepath.Join(bm.backupDir, name)
    
    if err := os.MkdirAll(backupPath, 0755); err != nil {
        return err
    }
    
    // Get snapshot from store
    snapshot, err := bm.store.GetSnapshot()
    if err != nil {
        return err
    }
    defer snapshot.Release()
    
    // Write snapshot to backup directory
    iter := snapshot.Iterator()
    defer iter.Close()
    
    backupFile := filepath.Join(backupPath, "data.backup")
    f, err := os.Create(backupFile)
    if err != nil {
        return err
    }
    defer f.Close()
    
    encoder := json.NewEncoder(f)
    
    for iter.Next() {
        entry := map[string]interface{}{
            "key":   string(iter.Key()),
            "value": string(iter.Value()),
        }
        encoder.Encode(entry)
    }
    
    bm.logger.Info("backup created", zap.String("path", backupPath))
    return nil
}

// RestoreBackup restores database from backup
func (bm *BackupManager) RestoreBackup(name string) error {
    backupPath := filepath.Join(bm.backupDir, name)
    backupFile := filepath.Join(backupPath, "data.backup")
    
    f, err := os.Open(backupFile)
    if err != nil {
        return err
    }
    defer f.Close()
    
    decoder := json.NewDecoder(f)
    
    for {
        var entry map[string]interface{}
        if err := decoder.Decode(&entry); err != nil {
            if err == io.EOF {
                break
            }
            return err
        }
        
        key := []byte(entry["key"].(string))
        value := []byte(entry["value"].(string))
        
        bm.store.Put(context.Background(), key, value)
    }
    
    bm.logger.Info("backup restored", zap.String("path", backupPath))
    return nil
}

// ListBackups lists all available backups
func (bm *BackupManager) ListBackups() ([]string, error) {
    entries, err := os.ReadDir(bm.backupDir)
    if err != nil {
        return nil, err
    }
    
    var backups []string
    for _, entry := range entries {
        if entry.IsDir() {
            backups = append(backups, entry.Name())
        }
    }
    
    return backups, nil
}

// DeleteBackup deletes a backup
func (bm *BackupManager) DeleteBackup(name string) error {
    backupPath := filepath.Join(bm.backupDir, name)
    return os.RemoveAll(backupPath)
}

Scheduled Backups

// ScheduledBackupManager handles periodic backups
type ScheduledBackupManager struct {
    backupMgr   *BackupManager
    interval    time.Duration
    maxBackups  int
    ticker      *time.Ticker
    done        chan struct{}
}

// Start begins scheduled backups
func (sbm *ScheduledBackupManager) Start() {
    sbm.ticker = time.NewTicker(sbm.interval)
    
    go func() {
        for {
            select {
            case <-sbm.ticker.C:
                // Create backup with timestamp
                name := fmt.Sprintf("backup-%d", time.Now().Unix())
                if err := sbm.backupMgr.CreateBackup(name); err != nil {
                    log.Printf("backup failed: %v", err)
                    continue
                }
                
                // Clean old backups
                sbm.cleanOldBackups()
                
            case <-sbm.done:
                return
            }
        }
    }()
}

// cleanOldBackups removes old backups
func (sbm *ScheduledBackupManager) cleanOldBackups() {
    backups, _ := sbm.backupMgr.ListBackups()
    
    if len(backups) > sbm.maxBackups {
        // Sort by name (timestamp)
        sort.Strings(backups)
        
        // Delete oldest
        for i := 0; i < len(backups)-sbm.maxBackups; i++ {
            sbm.backupMgr.DeleteBackup(backups[i])
        }
    }
}

// Stop stops scheduled backups
func (sbm *ScheduledBackupManager) Stop() {
    sbm.ticker.Stop()
    close(sbm.done)
}

Lab: Production Deployment

Objective

Build a complete production deployment pipeline with configuration management, containerization, orchestration, and backup strategies.

Requirements

  • Configuration Management: YAML/TOML configs with validation

  • Docker Containerization: Multi-stage builds, health checks

  • Kubernetes Deployment: Deployments, Services, ConfigMaps

  • Backup System: Point-in-time backups, scheduled backups

  • Monitoring: Health checks, metrics, logging

  • CI/CD Pipeline: Automated testing and deployment

Starter code

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

// TODO: Implement configuration management
func LoadConfig(filepath string) (*Config, error) {
    // Load YAML/TOML configuration
    // Validate configuration
    // Return parsed config
}

// TODO: Implement Docker health checks
func (s *Server) HealthCheck() bool {
    // Check database connectivity
    // Check replication status
    // Check resource usage
    return true
}

// TODO: Implement backup system
func (s *Server) CreateBackup() error {
    // Create point-in-time backup
    // Compress backup data
    // Store backup metadata
    return nil
}

// TODO: Implement graceful shutdown
func (s *Server) GracefulShutdown(timeout time.Duration) error {
    // Stop accepting new connections
    // Wait for active connections to finish
    // Clean up resources
    return nil
}

Test Template

func TestConfiguration(t *testing.T) {
    cfg, err := LoadConfig("test-config.yaml")
    assert.NoError(t, err)
    assert.NotNil(t, cfg)
    
    // Test configuration validation
    err = cfg.Validate()
    assert.NoError(t, err)
    
    // Test environment variable override
    os.Setenv("KVDB_SERVER_PORT", "7000")
    cfg, _ = LoadConfigFromEnv()
    assert.Equal(t, 7000, cfg.Server.Port)
}

func TestDockerHealthCheck(t *testing.T) {
    server := NewServer()
    
    // Test health check
    healthy := server.HealthCheck()
    assert.True(t, healthy)
}

func TestBackupRestore(t *testing.T) {
    store := NewStore()
    backupMgr := NewBackupManager(store)
    
    // Create test data
    store.Put([]byte("key1"), []byte("value1"))
    store.Put([]byte("key2"), []byte("value2"))
    
    // Create backup
    err := backupMgr.CreateBackup("test-backup")
    assert.NoError(t, err)
    
    // Clear store
    store.Clear()
    
    // Restore backup
    err = backupMgr.RestoreBackup("test-backup")
    assert.NoError(t, err)
    
    // Verify data restored
    value, _ := store.Get([]byte("key1"))
    assert.Equal(t, "value1", string(value))
}

Acceptance Criteria

  • Configuration loads from YAML/TOML files

  • Environment variables override config

  • Docker image builds and runs correctly

  • Kubernetes deployment works

  • Health checks respond correctly

  • Backup and restore functionality works

  • Graceful shutdown handles connections

  • Monitoring and logging integrated

  • > 90% code coverage

  • All tests pass

Hints

  • Load in three layers: defaults, then the YAML file, then KVDB_* environment variables. Validate last, and report every problem at once with errors.Join.
  • Turn on KnownFields(true) in the YAML decoder so a typo in a key is an error instead of a silently ignored setting.
  • Write backups to a temp file and rename it into place, so a crash never leaves a half-written archive that looks valid. Record a checksum next to it.
  • Graceful shutdown order: fail readiness, stop accepting, wait for in-flight requests (with a timeout), force-close stragglers, then flush and close the engine.

Reference solution

Try the lab on your own first, then compare. It uses gopkg.in/yaml.v3 with explicit tags (the Viper example above needs mapstructure tags for keys like max_connections to load), environment overrides, validation, a health check, compressed backups with retention, and graceful shutdown. It compiles and passes its tests with go test -race (Go 1.22 or newer).

Reference solution: deploy.go
package deploy

import (
    "archive/tar"
    "compress/gzip"
    "context"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "io/fs"
    "net"
    "os"
    "path/filepath"
    "strconv"
    "strings"
    "sync"
    "time"

    "gopkg.in/yaml.v3"
)

// Config mirrors config.yaml. The yaml tags matter: without them "max_connections"
// would not map to MaxConnections.
type Config struct {
    Server struct {
        Host           string `yaml:"host"`
        Port           int    `yaml:"port"`
        MaxConnections int    `yaml:"max_connections"`
    } `yaml:"server"`
    Database struct {
        DataDir         string `yaml:"data_dir"`
        MemtableSize    int64  `yaml:"memtable_size"`
        ShardCount      int    `yaml:"shard_count"`
        WalSyncInterval int    `yaml:"wal_sync_interval"`
    } `yaml:"database"`
    Replication struct {
        Mode        string `yaml:"mode"`
        MinReplicas int    `yaml:"min_replicas"`
        TimeoutMs   int    `yaml:"timeout_ms"`
    } `yaml:"replication"`
    Cluster struct {
        Nodes []string `yaml:"nodes"`
    } `yaml:"cluster"`
    Backup struct {
        Dir  string `yaml:"dir"`
        Keep int    `yaml:"keep"`
    } `yaml:"backup"`
}

// Defaults are applied first, then the file, then KVDB_* environment variables.
func Defaults() *Config {
    c := &Config{}
    c.Server.Host, c.Server.Port, c.Server.MaxConnections = "0.0.0.0", 6379, 10000
    c.Database.DataDir, c.Database.MemtableSize, c.Database.ShardCount, c.Database.WalSyncInterval = "/var/lib/kvdb", 64<<20, 16, 100
    c.Replication.Mode, c.Replication.MinReplicas, c.Replication.TimeoutMs = "async", 0, 5000
    c.Backup.Dir, c.Backup.Keep = "/var/backups/kvdb", 7
    return c
}

// LoadConfig reads YAML, applies environment overrides and validates.
func LoadConfig(path string) (*Config, error) {
    cfg := Defaults()
    if path != "" {
        b, err := os.ReadFile(path)
        if err != nil {
            return nil, fmt.Errorf("read config: %w", err)
        }
        dec := yaml.NewDecoder(strings.NewReader(string(b)))
        dec.KnownFields(true) // a typo like "max_conections" is an error, not silently ignored
        if err := dec.Decode(cfg); err != nil && !errors.Is(err, io.EOF) {
            return nil, fmt.Errorf("parse %s: %w", path, err)
        }
    }
    if err := applyEnv(cfg, os.LookupEnv); err != nil {
        return nil, err
    }
    if err := cfg.Validate(); err != nil {
        return nil, fmt.Errorf("invalid config: %w", err)
    }
    return cfg, nil
}

// applyEnv maps KVDB_SECTION_FIELD variables onto the config, e.g. KVDB_SERVER_PORT=7000.
func applyEnv(c *Config, lookup func(string) (string, bool)) error {
    str := map[string]*string{
        "KVDB_SERVER_HOST": &c.Server.Host, "KVDB_DATABASE_DATA_DIR": &c.Database.DataDir,
        "KVDB_REPLICATION_MODE": &c.Replication.Mode, "KVDB_BACKUP_DIR": &c.Backup.Dir,
    }
    ints := map[string]*int{
        "KVDB_SERVER_PORT": &c.Server.Port, "KVDB_SERVER_MAX_CONNECTIONS": &c.Server.MaxConnections,
        "KVDB_DATABASE_SHARD_COUNT": &c.Database.ShardCount, "KVDB_DATABASE_WAL_SYNC_INTERVAL": &c.Database.WalSyncInterval,
        "KVDB_REPLICATION_MIN_REPLICAS": &c.Replication.MinReplicas, "KVDB_REPLICATION_TIMEOUT_MS": &c.Replication.TimeoutMs,
        "KVDB_BACKUP_KEEP": &c.Backup.Keep,
    }
    for k, p := range str {
        if v, ok := lookup(k); ok {
            *p = v
        }
    }
    for k, p := range ints {
        if v, ok := lookup(k); ok {
            n, err := strconv.Atoi(v)
            if err != nil {
                return fmt.Errorf("%s=%q is not a number", k, v)
            }
            *p = n
        }
    }
    if v, ok := lookup("KVDB_CLUSTER_NODES"); ok { // comma separated
        c.Cluster.Nodes = strings.Split(v, ",")
    }
    return nil
}

// Validate reports every problem at once, not just the first.
func (c *Config) Validate() error {
    var errs []error
    if c.Server.Port <= 0 || c.Server.Port > 65535 {
        errs = append(errs, fmt.Errorf("server.port %d out of range", c.Server.Port))
    }
    if c.Server.MaxConnections <= 0 {
        errs = append(errs, errors.New("server.max_connections must be > 0"))
    }
    if c.Database.MemtableSize < 1<<20 {
        errs = append(errs, errors.New("database.memtable_size must be at least 1 MiB"))
    }
    if c.Database.ShardCount <= 0 || c.Database.ShardCount > 256 || c.Database.ShardCount&(c.Database.ShardCount-1) != 0 {
        errs = append(errs, fmt.Errorf("database.shard_count %d must be a power of two between 1 and 256", c.Database.ShardCount))
    }
    switch c.Replication.Mode {
    case "async", "sync", "semi-sync":
    default:
        errs = append(errs, fmt.Errorf("replication.mode %q must be async, sync or semi-sync", c.Replication.Mode))
    }
    if c.Replication.Mode == "semi-sync" && (c.Replication.MinReplicas < 1 || c.Replication.MinReplicas >= len(c.Cluster.Nodes)) {
        errs = append(errs, errors.New("semi-sync needs 1 <= replication.min_replicas < number of cluster nodes"))
    }
    for _, n := range c.Cluster.Nodes {
        if _, _, err := net.SplitHostPort(n); err != nil {
            errs = append(errs, fmt.Errorf("cluster node %q: %v", n, err))
        }
    }
    return errors.Join(errs...)
}

// Engine is the storage engine as seen by ops code.
type Engine interface {
    Ping(ctx context.Context) error
    // Checkpoint flushes the memtable and returns once on-disk files are consistent.
    // Files under DataDir must not be rewritten until release is called.
    Checkpoint(ctx context.Context) (release func(), err error)
    Close() error
}

type Server struct {
    cfg      *Config
    engine   Engine
    listener net.Listener
    conns    sync.WaitGroup
    mu       sync.Mutex
    active   map[net.Conn]struct{}
    draining bool
}

func NewServer(cfg *Config, e Engine, ln net.Listener) *Server {
    return &Server{cfg: cfg, engine: e, listener: ln, active: map[net.Conn]struct{}{}}
}

// Track must wrap every client connection handler so shutdown can wait for it.
func (s *Server) Track(c net.Conn) (done func(), ok bool) {
    s.mu.Lock()
    defer s.mu.Unlock()
    if s.draining {
        return nil, false
    }
    s.active[c] = struct{}{}
    s.conns.Add(1)
    return func() {
        s.mu.Lock()
        delete(s.active, c)
        s.mu.Unlock()
        s.conns.Done()
    }, true
}

// HealthCheck backs the Docker HEALTHCHECK and the Kubernetes readiness probe.
func (s *Server) HealthCheck() bool {
    s.mu.Lock()
    draining := s.draining
    s.mu.Unlock()
    if draining {
        return false
    }
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    if s.engine.Ping(ctx) != nil {
        return false
    }
    // Refuse traffic when the data disk is almost full: writes would start failing.
    return diskFreeRatio(s.cfg.Database.DataDir) > 0.05
}

// BackupMeta is written next to each archive.
type BackupMeta struct {
    Created time.Time `json:"created"`
    Files   int       `json:"files"`
    Bytes   int64     `json:"bytes"`
    SHA256  string    `json:"sha256"`
}

// CreateBackup checkpoints the engine, writes DataDir to a .tar.gz, records metadata
// and prunes old backups. It writes to a temp file and renames, so a crash never
// leaves a half-written archive that looks valid.
func (s *Server) CreateBackup(ctx context.Context) (string, error) {
    release, err := s.engine.Checkpoint(ctx)
    if err != nil {
        return "", fmt.Errorf("checkpoint: %w", err)
    }
    defer release()
    if err := os.MkdirAll(s.cfg.Backup.Dir, 0o750); err != nil {
        return "", err
    }
    name := "kvdb-" + time.Now().UTC().Format("20060102T150405.000Z")
    final := filepath.Join(s.cfg.Backup.Dir, name+".tar.gz")
    tmp, err := os.CreateTemp(s.cfg.Backup.Dir, ".backup-*")
    if err != nil {
        return "", err
    }
    defer os.Remove(tmp.Name()) // no-op after a successful rename

    h := sha256.New()
    gz := gzip.NewWriter(io.MultiWriter(tmp, h))
    tw := tar.NewWriter(gz)
    meta := BackupMeta{Created: time.Now().UTC()}
    root := s.cfg.Database.DataDir
    err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
        if err != nil || d.IsDir() {
            return err
        }
        if err := ctx.Err(); err != nil {
            return err
        }
        info, err := d.Info()
        if err != nil {
            return err
        }
        hdr, _ := tar.FileInfoHeader(info, "")
        hdr.Name, _ = filepath.Rel(root, p)
        if err := tw.WriteHeader(hdr); err != nil {
            return err
        }
        f, err := os.Open(p)
        if err != nil {
            return err
        }
        n, err := io.Copy(tw, f)
        f.Close()
        meta.Files++
        meta.Bytes += n
        return err
    })
    if err == nil {
        err = errors.Join(tw.Close(), gz.Close(), tmp.Sync())
    }
    tmp.Close()
    if err != nil {
        return "", fmt.Errorf("backup: %w", err)
    }
    if err := os.Rename(tmp.Name(), final); err != nil {
        return "", err
    }
    meta.SHA256 = hex.EncodeToString(h.Sum(nil))
    mb, _ := json.MarshalIndent(meta, "", "  ")
    if err := os.WriteFile(filepath.Join(s.cfg.Backup.Dir, name+".json"), mb, 0o640); err != nil {
        return "", err
    }
    return final, s.pruneBackups()
}

func (s *Server) pruneBackups() error {
    matches, err := filepath.Glob(filepath.Join(s.cfg.Backup.Dir, "kvdb-*.tar.gz"))
    if err != nil || len(matches) <= s.cfg.Backup.Keep {
        return err
    }
    // Names sort by time, oldest first.
    for _, old := range matches[:len(matches)-s.cfg.Backup.Keep] {
        os.Remove(old)
        os.Remove(strings.TrimSuffix(old, ".tar.gz") + ".json")
    }
    return nil
}

// GracefulShutdown stops accepting, fails readiness so load balancers drain us,
// waits for in-flight connections, then force-closes stragglers and closes the engine
// (which flushes the memtable and syncs the WAL).
func (s *Server) GracefulShutdown(timeout time.Duration) error {
    s.mu.Lock()
    s.draining = true
    s.mu.Unlock()
    s.listener.Close()

    done := make(chan struct{})
    go func() { s.conns.Wait(); close(done) }()
    var forced error
    select {
    case <-done:
    case <-time.After(timeout):
        s.mu.Lock()
        n := len(s.active)
        for c := range s.active {
            c.Close()
        }
        s.mu.Unlock()
        select { // handlers return once their conn is closed; don't hang forever if one doesn't
        case <-done:
        case <-time.After(5 * time.Second):
        }
        forced = fmt.Errorf("closed %d connections that did not finish within %v", n, timeout)
    }
    return errors.Join(forced, s.engine.Close())
}
Disk-space helper: disk_unix.go
//go:build unix

package deploy

import "syscall"

// diskFreeRatio returns the share of the filesystem at path that is still free (1 if unknown).
func diskFreeRatio(path string) float64 {
    var st syscall.Statfs_t
    if err := syscall.Statfs(path, &st); err != nil || st.Blocks == 0 {
        return 1
    }
    return float64(st.Bavail) / float64(st.Blocks)
}
Tests: deploy_test.go
package deploy

import (
    "context"
    "net"
    "os"
    "path/filepath"
    "strings"
    "testing"
    "time"
)

type eng struct{ closed bool }

func (e *eng) Ping(context.Context) error                 { return nil }
func (e *eng) Checkpoint(context.Context) (func(), error) { return func() {}, nil }
func (e *eng) Close() error                               { e.closed = true; return nil }

func TestLoadConfig(t *testing.T) {
    dir := t.TempDir()
    p := filepath.Join(dir, "config.yaml")
    os.WriteFile(p, []byte("server:\n  port: 7000\nreplication:\n  mode: semi-sync\n  min_replicas: 1\ncluster:\n  nodes: [\"a:1\", \"b:1\", \"c:1\"]\n"), 0o644)
    t.Setenv("KVDB_DATABASE_SHARD_COUNT", "32")
    c, err := LoadConfig(p)
    if err != nil {
        t.Fatal(err)
    }
    if c.Server.Port != 7000 || c.Database.ShardCount != 32 || c.Server.MaxConnections != 10000 {
        t.Fatalf("%+v", c)
    }
    os.WriteFile(p, []byte("server:\n  max_conections: 5\n"), 0o644)
    if _, err := LoadConfig(p); err == nil {
        t.Fatal("typo accepted")
    }
    t.Setenv("KVDB_DATABASE_SHARD_COUNT", "12")
    t.Setenv("KVDB_REPLICATION_MODE", "fast")
    _, err = LoadConfig("")
    if err == nil || !strings.Contains(err.Error(), "shard_count") || !strings.Contains(err.Error(), "fast") {
        t.Fatal("expected both errors, got", err)
    }
}

func TestBackupAndShutdown(t *testing.T) {
    cfg := Defaults()
    cfg.Database.DataDir, cfg.Backup.Dir, cfg.Backup.Keep = t.TempDir(), t.TempDir(), 2
    os.WriteFile(filepath.Join(cfg.Database.DataDir, "000001.sst"), []byte("data"), 0o644)
    ln, _ := net.Listen("tcp", "127.0.0.1:0")
    e := &eng{}
    s := NewServer(cfg, e, ln)
    if !s.HealthCheck() {
        t.Fatal("unhealthy")
    }
    for i := 0; i < 3; i++ {
        if _, err := s.CreateBackup(context.Background()); err != nil {
            t.Fatal(err)
        }
        time.Sleep(2 * time.Millisecond)
    }
    if m, _ := filepath.Glob(filepath.Join(cfg.Backup.Dir, "*.tar.gz")); len(m) != 2 {
        t.Fatalf("kept %d backups", len(m))
    }
    c1, c2 := net.Pipe()
    defer c2.Close()
    done, _ := s.Track(c1)
    go func() { // a handler blocked on a client that never sends anything
        defer done()
        c1.Read(make([]byte, 1)) // returns once shutdown force-closes the conn
    }()
    err := s.GracefulShutdown(50 * time.Millisecond)
    if err == nil || !e.closed || s.HealthCheck() {
        t.Fatal("shutdown", err, e.closed)
    }
}

Quiz

  1. Why validate configuration at startup?
  2. Why use a multi-stage Dockerfile for a Go service?
  3. How does a ConfigMap help in Kubernetes?
Show answers
  1. To fail fast with a clear error instead of misbehaving later with a bad port, path or limit.
  2. Build in a full Go image, then copy only the binary into a small runtime image: smaller, faster to pull, less attack surface.
  3. It keeps configuration outside the image so the same image runs in every environment with different settings.

Done with this lesson?

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