Golang / GoLang Concurrency Mastery Interview Questions
Implement a simple publish-subscribe broker using Go channels.
A pub-sub system decouples publishers from subscribers. The idiomatic Go implementation uses a broker goroutine that owns the subscriber registry and distributes messages — a single goroutine owning a map eliminates all locking.
type Broker[T any] struct { publish chan T subscribe chan chan<- T cancel chan chan<- T quit chan struct{} } func NewBroker[T any]() *Broker[T] { b := &Broker[T]{ publish: make(chan T, 64), subscribe: make(chan chan<- T), cancel: make(chan chan<- T), quit: make(chan struct{}), } go b.run() return b } func (b *Broker[T]) run() { subs := map[chan<- T]struct{}{} for { select { case <-b.quit: for sub := range subs { close(sub) } return case sub := <-b.subscribe: subs[sub] = struct{}{} case sub := <-b.cancel: delete(subs, sub); close(sub) case msg := <-b.publish: for sub := range subs { select { case sub <- msg: // non-blocking: slow subscribers may miss default: } } } } } func (b *Broker[T]) Publish(v T) { b.publish <- v } func (b *Broker[T]) Subscribe() <-chan T { ch := make(chan T, 16) b.subscribe <- ch return ch } func (b *Broker[T]) Stop() { close(b.quit) }
More Related questions...