Lab 08: Actor Model

Time: 60 minutes | Level: Architect | Docker: golang:1.22-alpine

Overview

Actor model in Go: Actor interface with Receive, ActorSystem (spawn/send/stop), mailbox with buffered channel, supervision strategies (restart/stop/escalate), actor hierarchy, request-reply pattern, and actor benchmarks.


Step 1: Actor Interface

package actor

import "context"

// Message: anything sent to an actor's mailbox
type Message interface{}

// Actor: processes messages sequentially from its mailbox
type Actor interface {
	Receive(ctx context.Context, msg Message) error
}

// ActorRef: handle to an actor (send messages without direct access)
type ActorRef struct {
	name    string
	mailbox chan envelope
}

type envelope struct {
	msg    Message
	sender *ActorRef // For request-reply
	replyTo chan<- Message
}

func (ref *ActorRef) Send(msg Message) {
	ref.mailbox <- envelope{msg: msg}
}

func (ref *ActorRef) Ask(msg Message) <-chan Message {
	ch := make(chan Message, 1)
	ref.mailbox <- envelope{msg: msg, replyTo: ch}
	return ch
}

func (ref *ActorRef) Name() string { return ref.name }

Step 2: ActorSystem


Step 3: Request-Reply Pattern


Step 4: Actor Hierarchy


Step 5: Typed Messages with Generic Actor


Step 6: Actor Benchmarks


Step 7: Stash and Become Patterns


Step 8: Capstone — Actor System with 3 Actors

📸 Verified Output:


Summary

Component
Pattern
Notes

Actor

Receive(ctx, msg) error

Sequential processing

Mailbox

Buffered channel

Async message delivery

ActorRef

Opaque handle

No direct access

ActorSystem

Spawn/Send/Stop

Lifecycle management

Request-Reply

Ask()<-chan Message

Sync on async

Supervision

Restart/Stop/Escalate

Fault tolerance

Hierarchy

Parent spawns children

Fault isolation tree

Become

Replace behavior func

State machine actors

Last updated