Lesson 08 / 15 · Networking & Client

Client library & networking

Write a Go client library for your database: connection pooling, retries with exponential backoff, circuit breakers, pipelining and timeout handling.

3-4 hours advanced Not completed

On this page · 5 sections
  1. Client Implementation
  2. Advanced Networking Features
  3. Error Handling
  4. Lab: build the client library
  5. Quiz

A server is only pleasant to use with a good client. This lesson builds one: a connection pool, timeouts on every call, retries that do not resend non-idempotent writes, and errors that tell the caller what actually went wrong.

Client Implementation

Connection Management

A client needs to manage connections to the database server efficiently. Let’s start with basic connection handling and evolve to production-grade pooling.

Basic Connection

// Simple client without pooling
type Client struct {
    conn net.Conn
    reader *bufio.Reader
    writer *bufio.Writer
}

func NewClient(addr string) (*Client, error) {
    conn, err := net.Dial("tcp", addr)
    if err != nil {
        return nil, err
    }
    
    return &Client{
        conn: conn,
        reader: bufio.NewReader(conn),
        writer: bufio.NewWriter(conn),
    }, nil
}

func (c *Client) Get(key string) (string, error) {
    // Send GET command
    cmd := fmt.Sprintf("*2\r\n$3\r\nGET\r\n$%d\r\n%s\r\n", len(key), key)
    if _, err := c.writer.WriteString(cmd); err != nil {
        return "", err
    }
    if err := c.writer.Flush(); err != nil {
        return "", err
    }
    
    // Parse response
    marker, _ := c.reader.ReadByte()
    
    if marker == '-' {
        // Error response
        line, _ := bufio.NewReader(c.reader).ReadString('\n')
        return "", fmt.Errorf(line)
    }
    
    if marker == '$' {
        // Bulk string
        line, _ := bufio.NewReader(c.reader).ReadString('\n')
        length, _ := strconv.Atoi(strings.TrimSpace(line))
        
        if length == -1 {
            return "", nil  // Null
        }
        
        data := make([]byte, length)
        c.reader.Read(data)
        c.reader.ReadBytes('\n')  // Read trailing \r\n
        
        return string(data), nil
    }
    
    return "", fmt.Errorf("unexpected response type: %c", marker)
}

func (c *Client) Close() error {
    return c.conn.Close()
}

Problem: One connection per client means:

  • Limited concurrency (connection blocks on read)

  • New connection overhead for each operation

  • No connection reuse

Connection Pooling

Connection Pool: Maintain multiple reusable connections

// Pool of connections to single server
type ConnPool struct {
    addr        string
    conns       chan net.Conn
    maxConns    int
    idleTimeout time.Duration
    closed      bool
    mu          sync.Mutex
}

func NewConnPool(addr string, maxConns int) *ConnPool {
    return &ConnPool{
        addr:        addr,
        conns:       make(chan net.Conn, maxConns),
        maxConns:    maxConns,
        idleTimeout: 5 * time.Minute,
    }
}

// Get retrieves connection from pool or creates new
func (cp *ConnPool) Get(ctx context.Context) (net.Conn, error) {
    select {
    case conn := <-cp.conns:
        // Connection available from pool
        
        // Test if still alive (optional)
        if err := cp.testConn(conn); err == nil {
            return conn, nil
        }
        conn.Close()
        // Fall through to create new
        
    case <-ctx.Done():
        return nil, ctx.Err()
    default:
    }
    
    // Create new connection
    conn, err := net.Dial("tcp", cp.addr)
    if err != nil {
        return nil, err
    }
    
    return conn, nil
}

// Put returns connection to pool
func (cp *ConnPool) Put(conn net.Conn) error {
    cp.mu.Lock()
    if cp.closed {
        cp.mu.Unlock()
        return conn.Close()
    }
    cp.mu.Unlock()
    
    select {
    case cp.conns <- conn:
        return nil
    default:
        // Pool full, close connection
        return conn.Close()
    }
}

// testConn verifies connection is still alive
func (cp *ConnPool) testConn(conn net.Conn) error {
    // Set short timeout for test
    conn.SetDeadline(time.Now().Add(100 * time.Millisecond))
    defer conn.SetDeadline(time.Time{})
    
    // Send PING (simple test)
    fmt.Fprintf(conn, "*1\r\n$4\r\nPING\r\n")
    
    // Read response
    reader := bufio.NewReader(conn)
    resp, err := reader.ReadString('\n')
    return err
}

Pooled Client

type PooledClient struct {
    pool    *ConnPool
    timeout time.Duration
}

func NewPooledClient(addr string, maxConns int) *PooledClient {
    return &PooledClient{
        pool:    NewConnPool(addr, maxConns),
        timeout: 5 * time.Second,
    }
}

func (pc *PooledClient) Get(key string) (string, error) {
    ctx, cancel := context.WithTimeout(context.Background(), pc.timeout)
    defer cancel()
    
    conn, err := pc.pool.Get(ctx)
    if err != nil {
        return "", err
    }
    defer pc.pool.Put(conn)
    
    // Send command and read response
    return pc.sendCommand(conn, "GET", key)
}

func (pc *PooledClient) Close() error {
    return pc.pool.Close()
}

Retry Logic and Exponential Backoff

Problem: Transient failures (temporary network issues)

Attempt 1: Connection refused
Attempt 2 (wait 10ms): Connection refused
Attempt 3 (wait 100ms): Success!
// RetryConfig configures retry behavior
type RetryConfig struct {
    MaxAttempts int
    InitialWait time.Duration
    MaxWait     time.Duration
}

// Retry executes operation with exponential backoff
func Retry(cfg RetryConfig, fn func() error) error {
    var lastErr error
    wait := cfg.InitialWait
    
    for attempt := 0; attempt < cfg.MaxAttempts; attempt++ {
        if attempt > 0 {
            time.Sleep(wait)
            // Exponential backoff: wait = wait * 2, capped at MaxWait
            if wait < cfg.MaxWait {
                wait *= 2
                if wait > cfg.MaxWait {
                    wait = cfg.MaxWait
                }
            }
        }
        
        err := fn()
        if err == nil {
            return nil
        }
        
        // Check if error is retryable
        if !isRetryable(err) {
            return err
        }
        
        lastErr = err
    }
    
    return fmt.Errorf("max retries exceeded: %w", lastErr)
}

// isRetryable determines if error should trigger retry
func isRetryable(err error) bool {
    if err == nil {
        return false
    }
    
    // Network errors are retryable
    if ne, ok := err.(net.Error); ok {
        return ne.Temporary() || ne.Timeout()
    }
    
    // Check error message
    errStr := err.Error()
    retryable := []string{
        "connection refused",
        "connection reset",
        "i/o timeout",
        "temporary failure",
    }
    
    for _, msg := range retryable {
        if strings.Contains(strings.ToLower(errStr), msg) {
            return true
        }
    }
    
    return false
}

Circuit Breaker Pattern

Problem: Retry loop can overwhelm failing server

Server crashes:
  Client retries → Sends traffic to dead server
  More clients retry → Thundering herd
  Server recovers but overloaded

Solution: Circuit Breaker - Stops sending requests when failures exceed threshold

// CircuitBreaker prevents cascading failures
type CircuitBreaker struct {
    maxFailures  int
    resetTimeout time.Duration
    
    failures     int
    lastFailTime time.Time
    state        CircuitState
    mu           sync.RWMutex
}

type CircuitState int

const (
    CircuitClosed CircuitState = iota  // Normal operation
    CircuitOpen                        // Too many failures
    CircuitHalfOpen                    // Testing recovery
)

func NewCircuitBreaker(maxFailures int, resetTimeout time.Duration) *CircuitBreaker {
    return &CircuitBreaker{
        maxFailures:  maxFailures,
        resetTimeout: resetTimeout,
        state:        CircuitClosed,
    }
}

// Do executes operation, managing circuit state
func (cb *CircuitBreaker) Do(fn func() error) error {
    cb.mu.Lock()
    
    // Check if should reset from Open to HalfOpen
    if cb.state == CircuitOpen {
        if time.Since(cb.lastFailTime) > cb.resetTimeout {
            cb.state = CircuitHalfOpen
            cb.failures = 0
        } else {
            cb.mu.Unlock()
            return ErrCircuitOpen
        }
    }
    
    cb.mu.Unlock()
    
    // Execute operation
    err := fn()
    
    cb.mu.Lock()
    defer cb.mu.Unlock()
    
    if err != nil {
        cb.failures++
        cb.lastFailTime = time.Now()
        
        if cb.failures >= cb.maxFailures {
            cb.state = CircuitOpen
            return fmt.Errorf("circuit open after %d failures: %w", cb.failures, err)
        }
        
        return err
    }
    
    // Success: reset circuit
    cb.failures = 0
    if cb.state == CircuitHalfOpen {
        cb.state = CircuitClosed
    }
    
    return nil
}

Advanced Networking Features

Pipelining for Throughput

Problem: Without pipelining:

Client sends command 1  →
                        ← Server sends response 1
Client sends command 2  →
                        ← Server sends response 2
Client sends command 3  →
                        ← Server sends response 3

Round-trip latency: 3 × 10ms = 30ms

Solution: Pipelining sends multiple commands before waiting for responses

Client sends commands 1,2,3 →
                             ← Server sends responses 1,2,3

Latency: 1 × 10ms = 10ms (3x faster!)
// Pipeline sends multiple commands without waiting
type Pipeline struct {
    conn    net.Conn
    writer  *bufio.Writer
    reader  *bufio.Reader
    commands []*Command
}

type Command struct {
    Name string
    Args []string
    Response chan interface{}
    Error chan error
}

func NewPipeline(conn net.Conn) *Pipeline {
    return &Pipeline{
        conn:     conn,
        writer:   bufio.NewWriter(conn),
        reader:   bufio.NewReader(conn),
        commands: make([]*Command, 0),
    }
}

// Add queues command for execution
func (p *Pipeline) Add(name string, args ...string) <-chan interface{} {
    cmd := &Command{
        Name:     name,
        Args:     args,
        Response: make(chan interface{}, 1),
        Error:    make(chan error, 1),
    }
    
    p.commands = append(p.commands, cmd)
    return cmd.Response
}

// Execute sends all queued commands and reads responses
func (p *Pipeline) Execute(ctx context.Context) error {
    // Send all commands
    for _, cmd := range p.commands {
        req := p.formatCommand(cmd)
        if _, err := p.writer.WriteString(req); err != nil {
            return err
        }
    }
    
    if err := p.writer.Flush(); err != nil {
        return err
    }
    
    // Read all responses
    for _, cmd := range p.commands {
        select {
        case <-ctx.Done():
            return ctx.Err()
        default:
        }
        
        resp, err := p.readResponse()
        if err != nil {
            cmd.Error <- err
        } else {
            cmd.Response <- resp
        }
    }
    
    p.commands = p.commands[:0]  // Clear for next pipeline
    return nil
}

Multiplexing Connections

Problem: Multiple goroutines on same connection conflicts

// BAD: Race condition
conn := shared connection
go func() {
    conn.Write(command1)
    conn.Read(response1)
}()
go func() {
    conn.Write(command2)
    conn.Read(response2)
}()
// Commands/responses may interleave!

Solution: Multiplex with request ID matching

// Multiplexer allows concurrent operations on single connection
type Multiplexer struct {
    conn        net.Conn
    requestID   uint64
    responses   map[uint64]chan interface{}
    mu          sync.Mutex
}

// Request with unique ID
type MuxRequest struct {
    ID    uint64
    Name  string
    Args  []string
}

// Send sends request and returns channel for response
func (m *Multiplexer) Send(name string, args ...string) (<-chan interface{}, error) {
    m.mu.Lock()
    
    requestID := m.requestID
    m.requestID++
    
    respCh := make(chan interface{}, 1)
    m.responses[requestID] = respCh
    
    m.mu.Unlock()
    
    // Send request with ID
    req := fmt.Sprintf("%d %s %s\r\n", requestID, name, strings.Join(args, " "))
    _, err := m.conn.Write([]byte(req))
    if err != nil {
        m.mu.Lock()
        delete(m.responses, requestID)
        m.mu.Unlock()
        return nil, err
    }
    
    return respCh, nil
}

Request Timeouts

// Timeout ensures requests don't hang forever
func (pc *PooledClient) GetWithTimeout(key string, timeout time.Duration) (string, error) {
    ctx, cancel := context.WithTimeout(context.Background(), timeout)
    defer cancel()
    
    resultCh := make(chan string, 1)
    errCh := make(chan error, 1)
    
    go func() {
        val, err := pc.Get(key)
        if err != nil {
            errCh <- err
        } else {
            resultCh <- val
        }
    }()
    
    select {
    case result := <-resultCh:
        return result, nil
    case err := <-errCh:
        return "", err
    case <-ctx.Done():
        return "", fmt.Errorf("timeout exceeded")
    }
}

Error Handling

Network Error Types

import "errors"
import "net"

// Classify network errors
func classifyError(err error) string {
    if err == nil {
        return "none"
    }
    
    if errors.Is(err, io.EOF) {
        return "connection_closed"
    }
    
    if errors.Is(err, context.DeadlineExceeded) {
        return "timeout"
    }
    
    if ne, ok := err.(net.Error); ok {
        if ne.Timeout() {
            return "timeout"
        }
        if ne.Temporary() {
            return "temporary"
        }
        return "permanent"
    }
    
    return "unknown"
}

// Common network errors
var (
    ErrConnectionRefused = fmt.Errorf("connection refused")
    ErrConnectionReset   = fmt.Errorf("connection reset")
    ErrTimeout           = fmt.Errorf("operation timeout")
    ErrCircuitOpen       = fmt.Errorf("circuit breaker open")
)

Partial Failure Handling

// Multi-key operation with partial failures
func (pc *PooledClient) MGet(keys ...string) (map[string]string, error) {
    results := make(map[string]string)
    var lastErr error
    
    for _, key := range keys {
        val, err := pc.Get(key)
        if err != nil {
            lastErr = err
            continue
        }
        results[key] = val
    }
    
    // Return partial results even if some failed
    return results, lastErr
}

Client-Side Retries

// Transient vs permanent errors
func isTransient(err error) bool {
    if err == nil {
        return false
    }
    
    if ne, ok := err.(net.Error); ok {
        return ne.Temporary() || ne.Timeout()
    }
    
    // Check for specific errors
    errMsg := err.Error()
    transient := []string{
        "ECONNREFUSED",
        "ETIMEDOUT",
        "ECONNRESET",
        "temporary failure",
    }
    
    for _, msg := range transient {
        if strings.Contains(errMsg, msg) {
            return true
        }
    }
    
    return false
}

// Retry with backoff
func (pc *PooledClient) GetWithRetry(key string, maxRetries int) (string, error) {
    var lastErr error
    
    for attempt := 0; attempt < maxRetries; attempt++ {
        if attempt > 0 {
            backoff := time.Duration(math.Pow(2, float64(attempt-1))) * 100 * time.Millisecond
            time.Sleep(backoff)
        }
        
        val, err := pc.Get(key)
        if err == nil {
            return val, nil
        }
        
        if !isTransient(err) {
            return "", err  // Permanent error, don't retry
        }
        
        lastErr = err
    }
    
    return "", fmt.Errorf("max retries exceeded: %w", lastErr)
}

Lab: build the client library

Objective

Implement a feature-complete, production-grade client library with pooling, retries, and advanced features.

Requirements

  • Connection Pooling: Configurable pool size, connection reuse, idle cleanup

  • Retry Logic: Exponential backoff, configurable max attempts, transient error detection

  • Circuit Breaker: Prevent cascading failures, automatic recovery, state tracking

  • Pipelining: Batch multiple commands, single flush to server, collect all responses

  • Error Handling: Proper error types, timeout handling, partial failure support

  • Testing: Test with real server, test error scenarios, test concurrent operations

Starter code

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

package client

import (
    "bufio"
    "context"
    "net"
    "sync"
    "time"
)

// Client is a production-ready database client
type Client struct {
    // TODO: Add connection pool, circuit breaker, retry config
}

// NewClient creates a new client
// TODO: Implement with sensible defaults
func NewClient(addr string, opts ...Option) (*Client, error) {
    return nil, nil
}

// Get retrieves a value with automatic retry and timeout
// TODO: Implement with connection pooling
func (c *Client) Get(key string) (string, error) {
    return "", nil
}

// Set stores a value
// TODO: Implement
func (c *Client) Set(key, value string) error {
    return nil
}

// Delete removes a key
// TODO: Implement
func (c *Client) Delete(key string) error {
    return nil
}

// Pipeline returns a new pipeline for batching
// TODO: Implement
func (c *Client) Pipeline() *Pipeline {
    return nil
}

// Close gracefully closes the client
// TODO: Implement
func (c *Client) Close() error {
    return nil
}

// Option configures client behavior
type Option func(*Client)

// WithPoolSize sets connection pool size
func WithPoolSize(size int) Option {
    return func(c *Client) {
        // TODO: Implement
    }
}

// WithTimeout sets operation timeout
func WithTimeout(t time.Duration) Option {
    return func(c *Client) {
        // TODO: Implement
    }
}

// WithRetry configures retry behavior
func WithRetry(maxAttempts int, initialWait time.Duration) Option {
    return func(c *Client) {
        // TODO: Implement
    }
}

Test Template

func TestClientPooling(t *testing.T) {
    // Start test server
    server := startTestServer()
    defer server.Stop()
    
    // Create client with pool size 5
    client := NewClient(server.Addr(), WithPoolSize(5))
    defer client.Close()
    
    // Concurrent operations
    var wg sync.WaitGroup
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func(idx int) {
            defer wg.Done()
            key := fmt.Sprintf("key-%d", idx)
            client.Set(key, "value")
            val, _ := client.Get(key)
            assert.Equal(t, "value", val)
        }(i)
    }
    
    wg.Wait()
}

func TestClientRetry(t *testing.T) {
    // Use flaky server that fails then succeeds
    server := startFlakyServer(failCount: 2)
    defer server.Stop()
    
    client := NewClient(server.Addr(), WithRetry(5, 10*time.Millisecond))
    
    // Should succeed after retries
    val, err := client.Get("key")
    assert.NoError(t, err)
}

func BenchmarkClientThroughput(b *testing.B) {
    server := startTestServer()
    defer server.Stop()
    
    client := NewClient(server.Addr())
    defer client.Close()
    
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        client.Set("key", "value")
    }
}

Acceptance Criteria

  • All tests pass

  • Connection pooling working

  • Retries succeed with flaky servers

  • Circuit breaker prevents cascading failures

  • Pipelining achieves 10x throughput improvement

  • 100K+ operations/sec on single client

  • > 85% code coverage

  • No goroutine leaks

Hints

  • Model the pool as a buffered channel of idle connections plus a semaphore channel that caps how many are open.
  • Only retry errors that are safe to retry: network errors and timeouts. A -ERR reply from the server or a missing key is an answer, not a failure.
  • Back off exponentially with jitter (for example 50–100% of the current wait) so clients that failed together do not retry together.
  • Circuit breaker states: closed (normal), open (fail fast until a cooldown passes), half-open (let one trial request through).
  • Do not auto-retry a pipeline: some of its commands may already have run on the server.

Reference solution

Try the lab on your own first, then compare. It talks to the Lesson 7 server and includes the connection pool, retries with jittered backoff, a circuit breaker, pipelining and per-operation timeouts. It compiles and passes its tests with go test -race (Go 1.22 or newer).

Reference solution: client.go
package client

import (
    "bufio"
    "context"
    "errors"
    "fmt"
    "io"
    "math/rand"
    "net"
    "strconv"
    "sync"
    "time"
)

var (
    ErrNil         = errors.New("key not found") // GET on a missing key
    ErrClosed      = errors.New("client closed")
    ErrCircuitOpen = errors.New("circuit breaker open")
)

// ServerError is an error reply (-ERR ...) from the server. It is not retried.
type ServerError string

func (e ServerError) Error() string { return string(e) }

// Client is a pooled, retrying, circuit-breaking client for the RESP server.
type Client struct {
    addr        string
    poolSize    int
    timeout     time.Duration
    maxAttempts int
    initialWait time.Duration
    maxWait     time.Duration

    pool    chan *conn    // idle connections
    sem     chan struct{} // limits open connections to poolSize
    breaker *breaker

    mu     sync.Mutex
    closed bool
}

type conn struct {
    net.Conn
    r *bufio.Reader
    w *bufio.Writer
}

// Option configures client behavior.
type Option func(*Client)

// WithPoolSize sets the maximum number of open connections.
func WithPoolSize(size int) Option { return func(c *Client) { c.poolSize = size } }

// WithTimeout sets the per-operation timeout (dial + write + read).
func WithTimeout(t time.Duration) Option { return func(c *Client) { c.timeout = t } }

// WithRetry sets the attempts per operation and the first backoff wait.
func WithRetry(maxAttempts int, initialWait time.Duration) Option {
    return func(c *Client) { c.maxAttempts, c.initialWait = maxAttempts, initialWait }
}

// NewClient creates a client with sensible defaults and checks the server is reachable.
func NewClient(addr string, opts ...Option) (*Client, error) {
    c := &Client{addr: addr, poolSize: 10, timeout: 2 * time.Second, maxAttempts: 3, initialWait: 50 * time.Millisecond, maxWait: 2 * time.Second}
    for _, o := range opts {
        o(c)
    }
    if c.poolSize < 1 || c.maxAttempts < 1 {
        return nil, errors.New("pool size and attempts must be >= 1")
    }
    c.pool = make(chan *conn, c.poolSize)
    c.sem = make(chan struct{}, c.poolSize)
    c.breaker = newBreaker(5, 10*time.Second)
    // Fail fast if the server is not there.
    if _, err := c.do(context.Background(), "PING"); err != nil {
        return nil, fmt.Errorf("connect %s: %w", addr, err)
    }
    return c, nil
}

func (c *Client) get(ctx context.Context) (*conn, error) {
    select {
    case cn := <-c.pool:
        return cn, nil
    default:
    }
    select {
    case cn := <-c.pool:
        return cn, nil
    case c.sem <- struct{}{}: // room for a new connection
        d := net.Dialer{Timeout: c.timeout}
        nc, err := d.DialContext(ctx, "tcp", c.addr)
        if err != nil {
            <-c.sem
            return nil, err
        }
        return &conn{Conn: nc, r: bufio.NewReader(nc), w: bufio.NewWriter(nc)}, nil
    case <-ctx.Done():
        return nil, ctx.Err()
    }
}

// put returns a healthy connection to the pool, or closes a broken one.
func (c *Client) put(cn *conn, broken bool) {
    c.mu.Lock()
    closed := c.closed
    c.mu.Unlock()
    if broken || closed {
        cn.Close()
        <-c.sem
        return
    }
    c.pool <- cn
}

// do runs one command with timeout, retries (exponential backoff + jitter) and the circuit breaker.
func (c *Client) do(ctx context.Context, args ...string) (any, error) {
    var lastErr error
    wait := c.initialWait
    for attempt := 1; attempt <= c.maxAttempts; attempt++ {
        if !c.breaker.allow() {
            return nil, ErrCircuitOpen
        }
        reply, err := c.once(ctx, args)
        var se ServerError
        if err == nil || errors.As(err, &se) || errors.Is(err, ErrNil) {
            c.breaker.success()
            return reply, err
        }
        c.breaker.failure()
        lastErr = err
        if attempt == c.maxAttempts || ctx.Err() != nil || errors.Is(err, ErrClosed) {
            break
        }
        sleep := wait/2 + time.Duration(rand.Int63n(int64(wait/2)+1)) // jitter: 50-100% of wait
        select {
        case <-time.After(sleep):
        case <-ctx.Done():
            return nil, ctx.Err()
        }
        if wait *= 2; wait > c.maxWait {
            wait = c.maxWait
        }
    }
    return nil, lastErr
}

func (c *Client) once(ctx context.Context, args []string) (any, error) {
    c.mu.Lock()
    closed := c.closed
    c.mu.Unlock()
    if closed {
        return nil, ErrClosed
    }
    ctx, cancel := context.WithTimeout(ctx, c.timeout)
    defer cancel()
    cn, err := c.get(ctx)
    if err != nil {
        return nil, err
    }
    deadline, _ := ctx.Deadline()
    cn.SetDeadline(deadline)
    writeCommand(cn.w, args)
    if err := cn.w.Flush(); err != nil {
        c.put(cn, true)
        return nil, err
    }
    reply, err := readReply(cn.r)
    var se ServerError
    c.put(cn, err != nil && !errors.As(err, &se) && !errors.Is(err, ErrNil))
    return reply, err
}

// Get returns the value for key, or ErrNil if it does not exist.
func (c *Client) Get(key string) (string, error) {
    r, err := c.do(context.Background(), "GET", key)
    if err != nil {
        return "", err
    }
    return r.(string), nil
}

// Set stores a value.
func (c *Client) Set(key, value string) error {
    _, err := c.do(context.Background(), "SET", key, value)
    return err
}

// Delete removes a key.
func (c *Client) Delete(key string) error {
    _, err := c.do(context.Background(), "DEL", key)
    return err
}

// Pipeline batches commands and sends them in one round trip.
type Pipeline struct {
    c    *Client
    cmds [][]string
}

// Pipeline returns a new, empty pipeline.
func (c *Client) Pipeline() *Pipeline { return &Pipeline{c: c} }

func (p *Pipeline) Get(key string) *Pipeline { p.cmds = append(p.cmds, []string{"GET", key}); return p }
func (p *Pipeline) Set(key, value string) *Pipeline {
    p.cmds = append(p.cmds, []string{"SET", key, value})
    return p
}
func (p *Pipeline) Delete(key string) *Pipeline {
    p.cmds = append(p.cmds, []string{"DEL", key})
    return p
}

// Exec sends all queued commands, then reads every reply in order.
// Per-command errors (ErrNil, ServerError) are returned in errs; err is a connection failure.
// A pipeline is not retried automatically, because some commands may already have run.
func (p *Pipeline) Exec(ctx context.Context) (replies []any, errs []error, err error) {
    if !p.c.breaker.allow() {
        return nil, nil, ErrCircuitOpen
    }
    ctx, cancel := context.WithTimeout(ctx, p.c.timeout)
    defer cancel()
    cn, err := p.c.get(ctx)
    if err != nil {
        p.c.breaker.failure()
        return nil, nil, err
    }
    deadline, _ := ctx.Deadline()
    cn.SetDeadline(deadline)
    for _, args := range p.cmds {
        writeCommand(cn.w, args)
    }
    if err := cn.w.Flush(); err != nil {
        p.c.put(cn, true)
        p.c.breaker.failure()
        return nil, nil, err
    }
    for range p.cmds {
        r, e := readReply(cn.r)
        var se ServerError
        if e != nil && !errors.As(e, &se) && !errors.Is(e, ErrNil) {
            p.c.put(cn, true)
            p.c.breaker.failure()
            return replies, errs, e
        }
        replies, errs = append(replies, r), append(errs, e)
    }
    p.c.put(cn, false)
    p.c.breaker.success()
    p.cmds = nil
    return replies, errs, nil
}

// Close closes idle connections; connections in use are closed when returned.
func (c *Client) Close() error {
    c.mu.Lock()
    if c.closed {
        c.mu.Unlock()
        return nil
    }
    c.closed = true
    c.mu.Unlock()
    for {
        select {
        case cn := <-c.pool:
            cn.Close()
            <-c.sem
        default:
            return nil
        }
    }
}

func writeCommand(w *bufio.Writer, args []string) {
    w.WriteString("*" + strconv.Itoa(len(args)) + "\r\n")
    for _, a := range args {
        w.WriteString("$" + strconv.Itoa(len(a)) + "\r\n" + a + "\r\n")
    }
}

// readReply parses one RESP2 reply.
func readReply(r *bufio.Reader) (any, error) {
    line, err := r.ReadString('\n')
    if err != nil {
        return nil, err
    }
    if len(line) < 3 {
        return nil, fmt.Errorf("short reply %q", line)
    }
    body := line[1 : len(line)-2]
    switch line[0] {
    case '+':
        return body, nil
    case '-':
        return nil, ServerError(body)
    case ':':
        return strconv.ParseInt(body, 10, 64)
    case '$':
        n, err := strconv.Atoi(body)
        if err != nil {
            return nil, err
        }
        if n < 0 {
            return nil, ErrNil
        }
        buf := make([]byte, n+2)
        if _, err := io.ReadFull(r, buf); err != nil {
            return nil, err
        }
        return string(buf[:n]), nil
    case '*':
        n, err := strconv.Atoi(body)
        if err != nil || n < 0 {
            return nil, err
        }
        out := make([]any, 0, n)
        for i := 0; i < n; i++ {
            v, err := readReply(r)
            if err != nil && !errors.Is(err, ErrNil) {
                return nil, err
            }
            out = append(out, v)
        }
        return out, nil
    }
    return nil, fmt.Errorf("unknown reply type %q", line[0])
}

// breaker is a closed / open / half-open circuit breaker.
type breaker struct {
    mu        sync.Mutex
    failures  int
    threshold int
    cooldown  time.Duration
    openUntil time.Time
    halfOpen  bool
}

func newBreaker(threshold int, cooldown time.Duration) *breaker {
    return &breaker{threshold: threshold, cooldown: cooldown}
}

func (b *breaker) allow() bool {
    b.mu.Lock()
    defer b.mu.Unlock()
    if b.openUntil.IsZero() {
        return true
    }
    if time.Now().Before(b.openUntil) {
        return false
    }
    if b.halfOpen {
        return false // one trial request is already in flight
    }
    b.halfOpen = true
    return true
}

func (b *breaker) success() {
    b.mu.Lock()
    b.failures, b.openUntil, b.halfOpen = 0, time.Time{}, false
    b.mu.Unlock()
}

func (b *breaker) failure() {
    b.mu.Lock()
    defer b.mu.Unlock()
    b.failures++
    if b.halfOpen || b.failures >= b.threshold {
        b.openUntil = time.Now().Add(b.cooldown)
        b.halfOpen = false
    }
}
Tests: client_test.go (runs against the Lesson 7 server)
package client

import (
    "context"
    "errors"
    "fmt"
    "sync"
    "testing"
    "time"

    "kvdb/server"
)

type mem struct {
    mu sync.Mutex
    m  map[string][]byte
}

func (s *mem) Get(_ context.Context, k []byte) ([]byte, error) {
    s.mu.Lock()
    defer s.mu.Unlock()
    v, ok := s.m[string(k)]
    if !ok {
        return nil, server.ErrNotFound
    }
    return v, nil
}
func (s *mem) Put(_ context.Context, k, v []byte) error {
    s.mu.Lock()
    s.m[string(k)] = v
    s.mu.Unlock()
    return nil
}
func (s *mem) Delete(_ context.Context, k []byte) error {
    s.mu.Lock()
    delete(s.m, string(k))
    s.mu.Unlock()
    return nil
}

func start(t *testing.T) *server.Server {
    s := server.NewServer("localhost:0", &mem{m: map[string][]byte{}})
    if err := s.Start(); err != nil {
        t.Fatal(err)
    }
    t.Cleanup(s.Stop)
    return s
}

func TestClientCRUDAndPool(t *testing.T) {
    s := start(t)
    c, err := NewClient(s.Addr(), WithPoolSize(4), WithTimeout(time.Second))
    if err != nil {
        t.Fatal(err)
    }
    defer c.Close()
    var wg sync.WaitGroup
    for i := 0; i < 20; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            k := fmt.Sprint("k", i)
            if err := c.Set(k, "v"); err != nil {
                t.Error(err)
            }
            if v, err := c.Get(k); err != nil || v != "v" {
                t.Error(v, err)
            }
        }(i)
    }
    wg.Wait()
    if err := c.Delete("k1"); err != nil {
        t.Fatal(err)
    }
    if _, err := c.Get("k1"); !errors.Is(err, ErrNil) {
        t.Fatalf("want ErrNil, got %v", err)
    }
    p := c.Pipeline().Set("a", "1").Set("b", "2").Get("a").Get("missing")
    replies, errs, err := p.Exec(context.Background())
    if err != nil || replies[2] != "1" || !errors.Is(errs[3], ErrNil) {
        t.Fatal(replies, errs, err)
    }
}

func TestRetryAndBreaker(t *testing.T) {
    s := start(t)
    c, err := NewClient(s.Addr(), WithRetry(2, 5*time.Millisecond), WithTimeout(200*time.Millisecond))
    if err != nil {
        t.Fatal(err)
    }
    s.Stop() // server goes away
    for i := 0; i < 5; i++ {
        c.Get("x")
    }
    if _, err := c.Get("x"); !errors.Is(err, ErrCircuitOpen) {
        t.Fatalf("expected open circuit, got %v", err)
    }
}

Quiz

  1. Why add jitter to exponential backoff?
  2. What does a circuit breaker do when it’s open?
  3. How does pipelining improve throughput?
Show answers
  1. So many clients that failed together don’t retry in lock-step and overload the server again.
  2. Fails calls immediately without contacting the server, then after a cool-down lets a few trial requests through (half-open) to test recovery.
  3. The client sends many commands without waiting for each reply, so one round trip covers many requests.

Done with this lesson?

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