technical

Caching and Logging with the Decorator Pattern in Go

Go interfaces and the decorator pattern can add caching and logging to a data layer without changing its core logic.

The decorator pattern adds behaviour to an object by wrapping it, without changing the object itself. In Go, it’s a clean way to keep things like caching, logging, or metrics out of the core logic.

The pattern needs only an interface and composition: every decorator implements the same interface as the thing it wraps, and holds a reference to it. Below I build a small data access layer with stackable behaviours.

A Data Source to Decorate

Say an app needs to fetch a user’s profile from a slow database. I want a cache in front of it to speed things up, and logging to see how long each request takes.

  classDiagram
    class DataSource {
        <<Interface>>
        +Get(id string) string, error
    }
    class DatabaseSource {
        +Get(id string) string, error
    }
    class CachedSource {
        +Source DataSource
        +Cache map[string]string
        +Get(id string) string, error
    }
    class LoggedSource {
        +Source DataSource
        +Get(id string) string, error
    }

    DataSource <|.. DatabaseSource : implements
    DataSource <|.. CachedSource : implements
    DataSource <|.. LoggedSource : implements
    CachedSource o-- DataSource : wraps
    LoggedSource o-- DataSource : wraps

The Interface

First, I define the DataSource interface. The database source and every decorator implement it.

type DataSource interface {
    Get(id string) (string, error)
}

The Database Source

Next, I implement DatabaseSource. It simulates fetching data from a slow database.

type DatabaseSource struct {
    // DB connection would go here
}

func (d *DatabaseSource) Get(id string) (string, error) {
    // Simulate a slow database call
    time.Sleep(100 * time.Millisecond)
    return "User Data for " + id, nil
}

A Caching Wrapper

CachedSource checks an in-memory map before calling the source it wraps. The map is not safe for concurrent use, so a real cache would need a mutex or sync.Map. Even with a lock, two requests that miss on the same ID at the same time would both hit the database, which singleflight prevents. This cache also never expires or evicts anything, so it grows forever and keeps serving a profile after it changes. A real one needs an expiry time and a size limit.

type CachedSource struct {
    Source DataSource
    Cache  map[string]string
}

func (c *CachedSource) Get(id string) (string, error) {
    if val, ok := c.Cache[id]; ok {
        log.Printf("cache hit for %s", id)
        return val, nil
    }

    val, err := c.Source.Get(id)
    if err != nil {
        return "", err
    }

    c.Cache[id] = val
    return val, nil
}

A Logging Wrapper

LoggedSource wraps any DataSource and logs how long each call took and whether it failed. The results are named so the deferred function can read err after the call returns.

type LoggedSource struct {
    Source DataSource
}

func (l *LoggedSource) Get(id string) (val string, err error) {
    start := time.Now()
    defer func() {
        log.Printf("Get(%s) took %v, err=%v", id, time.Since(start), err)
    }()

    return l.Source.Get(id)
}

Stacking Them

The useful part is composition. Each behaviour is its own small wrapper, so I pick exactly the ones I need. The order I stack them in still changes the result.

Here is how I put caching and logging around the database source:

func main() {
    // 1. Create the real database fetcher
    db := &DatabaseSource{}

    // 2. Wrap it with caching
    // Writing to a nil map panics, so create the map first
    cached := &CachedSource{
        Source: db,
        Cache:  make(map[string]string),
    }

    // 3. Wrap that with logging
    // The order matters! Logging is the outer layer, so it times every call,
    // cache check included: fast for cache hits, slow for misses.
    // Swap the two and the logger sits behind the cache, so it never sees the hits.
    finalSource := &LoggedSource{
        Source: cached,
    }

    // 4. Use the decorated source
    // First call: cache miss -> slow database call
    fmt.Println("--- First Call ---")
    val1, err := finalSource.Get("123")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(val1)

    // Second call: cache hit -> fast return
    fmt.Println("\n--- Second Call ---")
    val2, err := finalSource.Get("123")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(val2)
}

Why Bother

With decorators, the application code doesn’t need to know whether data comes from the database or the cache, or whether it’s being logged. It only depends on the DataSource interface.

Adding a RetrySource or MetricsSource later means writing one more wrapper and adding it where the stack is assembled. None of the existing types change.

The Catch

A decorator must implement every method of the interface it wraps. A real data layer has Get, List, Update and Delete, so every wrapper repeats all four, and the cache also has to drop entries on Update and Delete. Embedding the interface in the struct saves the typing, but then any method I forget to wrap quietly skips the decorator. That’s the main reason I keep these interfaces small.