Actor Model Pattern in Go

Go Concurrency Patterns Series: ← Semaphore Pattern | Series Overview What is the Actor Model? The Actor Model is a conceptual model for concurrent computation where “actors” are the fundamental units of computation. Each actor has its own isolated state, processes messages sequentially, and can create other actors, send messages, or change its behavior in response to messages. Key Principles: Isolated State: Each actor maintains its own private state Message Passing: Actors communicate only through asynchronous messages Sequential Processing: Each actor processes one message at a time Location Transparency: Actors can be local or remote Fault Tolerance: Actor failures are isolated and recoverable Real-World Use Cases Distributed Systems: Microservices communication Game Servers: Player state management IoT Systems: Device state and communication Financial Systems: Transaction processing Chat Applications: User session management Workflow Engines: Task orchestration Basic Actor Implementation package main import ( "context" "fmt" "sync" "time" ) // Message represents a message sent to an actor type Message interface{} // Actor represents the basic actor interface type Actor interface { Receive(message Message) Start(ctx context....

June 5, 2024 · 11 min · Rafiul Alam

Circuit Breaker Pattern in Go

Go Concurrency Patterns Series: ← Context Pattern | Series Overview | Rate Limiter → What is the Circuit Breaker Pattern? The Circuit Breaker pattern prevents cascading failures in distributed systems by monitoring for failures and temporarily stopping calls to failing services. Like an electrical circuit breaker, it “trips” when failures exceed a threshold, giving the failing service time to recover. States: Closed: Normal operation, requests pass through Open: Failing fast, requests are rejected immediately Half-Open: Testing if service has recovered Real-World Use Cases Microservices: Prevent cascade failures between services Database Connections: Handle database outages gracefully External APIs: Deal with third-party service failures Payment Processing: Handle payment gateway issues File Systems: Manage disk I/O failures Network Operations: Handle network partitions Basic Circuit Breaker Implementation package main import ( "context" "errors" "fmt" "sync" "time" ) // State represents the circuit breaker state type State int const ( StateClosed State = iota StateOpen StateHalfOpen ) func (s State) String() string { switch s { case StateClosed: return "CLOSED" case StateOpen: return "OPEN" case StateHalfOpen: return "HALF_OPEN" default: return "UNKNOWN" } } // CircuitBreaker implements the circuit breaker pattern type CircuitBreaker struct { mu sync....

June 5, 2024 · 11 min · Rafiul Alam