Go Goroutine Actor Pattern
Replace locks and atomic pointers with a single goroutine that owns all mutable state, accessed via channel-based request/response.
When to Apply
- •Multiple goroutines (HTTP handlers, background jobs) need to read/write shared state
- •Current code uses
sync.Mutexoratomic.Pointerto protect state - •You need a service that combines in-memory caching with persistent storage
Pattern Overview
See references/pattern.md for the complete implementation reference with code templates.
Implementation Steps
- •Create
internal/chanutil/chanutil.gowith generic channel helpers - •Define the public interface (what callers see)
- •Define command tags (enum of operations)
- •Define the command struct with a
result chan anyandWithResultmethod - •Implement the unexported struct with
commands chan,sync.WaitGroup - •Write the
run()goroutine — singlefor msg := range commandsloop owning all state - •Write public methods that use
SendReceive/SendReceiveErrorto talk to the goroutine - •Wire
Stop()/Wait()for clean shutdown - •Update callers (HTTP handlers, main.go) to use the new interface