Topic-based Filtering: Subscribers only get messages for specific topics they are interested in.
Scalability: The system needs to handle multiple publishers, multiple subscribers, and high message throughput concurrently. It shouldn't block publishers on slow subscribers (ideally).
Language: Go (Golang) is implied by the context of "scalable" and "concurrent" system implementation requests usually, and it's the best fit for this type of problem due to goroutines and channels. I will assume Go.
Core Components:
Broker: The central entity managing topics, subscriptions, and message distribution.
Topic: A string identifier (e.g., "sports/football", "news/politics").
Subscriber: A client that listens for messages.
Publisher: A client that sends messages.
Design Decisions:
Storage: How to store subscribers? A map where keys are topics and values are lists of subscriber channels.
Filtering: Simple string matching? Wildcards? The prompt asks for "topic-based filtering". I should support at least exact matching, but a hierarchical approach (e.g., "sports.*") adds significant value and demonstrates "filtering" better. Let's start with exact matching for simplicity but structure it so it could expand, or better yet, implement a simple pattern matching logic if I want to be fancy. Let's stick to exact topic matching for the core logic to keep the code clean, but I'll mention how to extend it. Actually, a map of topic -> []subscriber is the standard approach.
Concurrency:
The Broker needs a thread-safe map (or a goroutine managing the state) to handle concurrent subscriptions and publications.
Option A: sync.RWMutex protecting the map. Fast, standard.
Option B: Single goroutine managing state via channels (Actor model). Very idiomatic in Go, eliminates race conditions by design.
I will go with Option A (Mutex) for the registry because it's often more performant for read-heavy loads (many subscribers) and easier to integrate with a generic interface, but for the distribution logic, I need to ensure the Publisher doesn't block. Sending to a subscriber's channel should be non-blocking (using select with default or a buffered channel).
Buffering: Subscribers should have buffered channels so the Broker doesn't block if a subscriber is slow (backpressure handling).
Step-by-Step Implementation Plan:
Define the Message struct: Needs a topic and a payload.
Define the Subscriber interface/struct: Needs an ID and a channel to receive messages.
When Publishing: Iterate over subscribers for that topic. Send the message.
Crucial: The send must be non-blocking. If a subscriber's channel is full, drop the message or handle it. (Let's drop for simplicity in this demo, or use a select block).
Refining the Logic:
Let's make a Client struct that holds the message channel.
Let's implement a PubSub struct.
Drafting the Code (Mental or Scratchpad):
go
type Message struct {
Topic string
Data interface{}
}
type Subscriber struct {
ID string
MsgChan chan Message
}
type PubSub struct {
mu sync.RWMutex
subscriptions map[string]map[*Subscriber]struct{} // topic -> set of subscribers
}
Wait, a map[string]map[*Subscriber]bool (set) is better than a slice for O(1) removal.
Adding Wildcards (Optional but good):
Simple string matching is easiest. subscriptions[topic].
If the user meant "Filtering" like SQL style, that's too complex. Usually, topic filtering means string prefixes or specific tokens.
I will implement simple exact matching, but structure the Broker to allow adding regex/prefix logic easily.
Refining the "Scalable" aspect:
To make it truly scalable, we shouldn't have one global lock that blocks everything.
However, for a single-node implementation (which this likely is), a sync.RWMutex is the standard starting point.
To improve throughput, the Publish method should spin off a goroutine for every message dispatch? No, that creates too much overhead. It should iterate and send.
Actually, a very scalable pattern in Go is to have the Broker be an "Actor". All operations (Subscribe, Publish, Unsubscribe) are messages sent to a central loop. This serializes state access but allows concurrent processing of the actual network/IO logic.
Decision: I'll stick to the Mutex approach. It's robust, easy to understand, and performant enough for most use cases unless we are talking millions of QPS on a single instance.
Let's write the actual implementation.
Broker: Manages subscriptions.
Publish: Acquires RLock, finds topic, loops through subscribers, sends via channel.
Subscribe: Acquires Lock, adds subscriber.
Unsubscribe: Acquires Lock, removes subscriber.
Edge Cases:
Subscriber slow (channel full): Use select with default to skip or drop. Dropping is a common strategy in scalable fire-and-forget pub/sub.
Closing: Need a Close method.
Code Structure:
Message struct.
Subscriber struct.
Broker struct.
main function demonstrating multiple publishers and subscribers running concurrently.
Reviewing the prompt: "topic-based filtering".
Maybe I should support basic pattern matching?
Example: sports.* matches sports.football.
This complicates the lookup. Instead of map[topic]subscribers, we might need to check all keys or use a Trie.
To keep the code concise and readable, I will implement exact matching but explain how to extend it to wildcards. Self-correction: The user asked for filtering. I should probably support a simple prefix or specific map. Let's stick to exact match for the core logic but use a dedicated function getSubscribers(topic) so the logic is encapsulated.
Let's refine the architecture for maximum clarity.
Subscriber: Contains a channel chan interface{}.
Broker:
subs map[string][]*Subscriber
AddSub(topic, sub)
RemoveSub(topic, sub)
Publish(topic, payload)
Implementation Details:
Use sync.RWMutex.
In Publish: defer rUnlock. Get the slice of subs. Range over them.
Inside the loop: select { case sub.Chan <- msg: default: log.Println("sub full") }.
Let's put it together.
Additional thought: Distributed scalability?
The prompt says "scalable". In a real-world scenario, this implies distributed systems (Kafka, NATS, RabbitMQ). Implementing a distributed system from scratch in a single response is too long and complex. I must assume "scalable" here means "efficient concurrency handling in a single node". I will clarify this in the explanation.
Final Polish:
Add comments explaining the concurrency primitives.
Use wait groups in main to demonstrate timing.
Ensure no deadlocks (e.g., don't send while holding the lock? No, sending while holding RLock is fine, but if the channel is unbuffered and blocks, it blocks the read lock. That's bad.
Better approach: Copy the slice of subscribers under lock, release lock, then iterate and send. This prevents a slow subscriber from blocking the Broker from accepting new subscriptions/publishes.
Revised Plan:
Broker struct with RWMutex.
Publish(topic, msg):
RLock.
Copy the list of subscriber pointers for that topic.
RUnlock.
Iterate over the copy and send.
This ensures the broker is highly available.
Let's write the code.
go
package main
import (
"fmt"
"sync"
"time"
)
// Message represents the data being passed around.
type Message struct {
Topic string
Content interface{}
}
// Subscriber represents a client listening to a specific topic.
type Subscriber struct {
ID string
Chan chan Message
}
// PubSub is the central broker managing topics and subscriptions.
type PubSub struct {
mu sync.RWMutex
// topics maps a topic string to a slice of Subscriber pointers.
topics map[string][]*Subscriber
}
// NewPubSub creates a new PubSub instance.
func NewPubSub() *PubSub {
return &PubSub{
topics: make(map[string][]*Subscriber),
}
}
// Subscribe adds a subscriber to a topic.
func (ps *PubSub) Subscribe(topic string, sub *Subscriber) {
ps.mu.Lock()
defer ps.mu.Unlock()
// Check if topic exists, if not create it
ps.topics[topic] = append(ps.topics[topic], sub)
fmt.Printf("Subscribed %s to topic '%s'\n", sub.ID, topic)
}
// Unsubscribe removes a subscriber from a topic.
// (Implementation omitted for brevity in thought process, but will include in final code)
// It involves finding the index and slicing it out.
// Publish sends a message to all subscribers of a topic.
func (ps *PubSub) Publish(topic string, msg interface{}) {
ps.mu.RLock()
// Critical for scalability: We copy the subscriber list to a new slice
// so we can release the lock immediately.
// If we kept the lock while sending to channels, a slow subscriber
// would block the entire system.
subs := make([]*Subscriber, len(ps.topics[topic]))
copy(subs, ps.topics[topic])
ps.mu.RUnlock()
message := Message{Topic: topic, Content: msg}
for _, sub := range subs {
select {
case sub.Chan <- message:
// Sent successfully
default:
fmt.Printf("Warning: Subscriber %s buffer full, dropping message\n", sub.ID)
}
}
}
This looks solid. The "copy slice" pattern is the key to scalability here. The select/default pattern prevents blocking.
Let's write the full solution.
I will structure the response as follows:
Explanation: Briefly explain the architecture (Broker, Publisher, Subscriber) and the concurrency patterns used (Mutex, Buffered Channels, Non-blocking writes).
Code: The complete Go implementation.
Example Usage: A main function showing multiple goroutines publishing and subscribing.
Key Scalability Features: Highlight why this implementation is scalable (lock duration, non-blocking IO).
Topic Filtering:
I'll implement basic exact matching. I will add a note about wildcards.
Actually, to make it slightly more impressive, I can add a very simple "multi-topic" subscription or just mention that the topic key is the filter. Let's stick to exact string matching for the map key to ensure O(1) lookup, which is crucial for scalability.
Wait, one edge case:
Closing the subscriber channels. If a subscriber disconnects, we need to remove them to avoid sending to closed channels (panic) or accumulating garbage.
I'll add an Unsubscribe method that removes the subscriber from the slice.
Subscriber Management:
In a map topic -> []sub, removing a sub requires iterating. For high scalability, topic -> map[subID]*sub is O(1) removal.
Let's use map[string]map[string]*Subscriber where the inner map keys are Subscriber IDs.
Actually, using pointers as keys in the inner map is faster than strings if we have the pointer, but usually, we lookup by ID.
Let's stick to map[string][]*Subscriber for simplicity unless the user asked for optimization of unsubscribes specifically. Deleting from a slice is O(N). Given the constraints of a code snippet, map[string]map[string]*Subscriber is safer for concurrent modification issues, but slice is easier to read.
I'll use map[string]map[string]*Subscriber. It prevents duplicate subscriptions automatically and makes unsubscription fast.
Wait, map[string]map[*Subscriber]bool is more idiomatic if we have the pointer. But we often identify by ID.
Let's stick to map[string][]*Subscriber for the code snippet to keep it looking like a standard "list of listeners", but I'll iterate to remove. It's fine for a demo.
Let's refine the "Copy" logic in Publish.
If the topic doesn't exist, ps.topics[topic] returns nil, range over nil is safe.
Concurrency: sync.RWMutex, buffered channels (size 100?), select for non-blocking send.
Let's go.
Here is a complete, scalable implementation of a Publish-Subscribe (Pub/Sub) system in Go.
Design Highlights
Concurrency Safety: Uses sync.RWMutex to manage topics, allowing multiple concurrent readers (publishers) but locking for writes (subscriptions).
Non-Blocking Operations: The Publish function uses a select block with a default case. This ensures that slow subscribers do not block the entire system; if a subscriber's buffer is full, the message is dropped for that specific client (a common pattern in high-throughput systems to prevent backpressure crashes).
Asynchronous Consumers: Subscribers run in their own Goroutines.
Scalable Architecture: Publishers and Subscribers are decoupled via channels.
Implementation
go
How it works
The Broker (PubSub struct): This is the central hub. It maintains a map where the key is the Topic and the value is another map of Subscriber IDs to Subscriber Objects.
Locking Strategy (sync.RWMutex):
Read Lock (RLock): Used during Publish. This allows thousands of publishers to send messages simultaneously without blocking each other.
Write Lock (Lock): Used only during Subscribe or Unsubscribe. This ensures the topic map isn't modified while we are adding/removing clients.
Buffered Channels: Notice make(chan Message, 10). This acts as a queue. If a publisher sends 5 messages instantly, they sit in the buffer waiting for the subscriber to process them.
Non-Blocking Send (select + default): Inside Publish, we try to send to sub.Chan.
If the channel isn't full, it sends.
If the channel is full (the default case triggers), it means the subscriber is too slow. Instead of freezing the entire system, we log a warning and drop that specific message. This is crucial for scalability.
Scalability Notes
Memory: Subscribers are lightweight. You can scale to thousands of topics and subscribers.
Throughput: Because Publish does not wait for the actual processing logic of the subscribers (fire-and-forget), the throughput is extremely high.
Filtering: The filtering is O(1) map lookups. Looking up who is subscribed to "sports" is instant, regardless of how many other topics exist.
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
// Message represents the data sent through the system.
type Message struct {
Topic string
Content interface{}
}
// Subscriber represents a client listening to a topic.
// It contains a channel to receive messages.
type Subscriber struct {
ID string
Chan chan Message
}
// PubSub is the central broker managing topics and subscriptions.
type PubSub struct {
mu sync.RWMutex
// topics maps a topic name to a map of subscriber ID -> Subscriber struct
topics map[string]map[string]*Subscriber
}
// NewPubSub initializes the broker.
func NewPubSub() *PubSub {
return &PubSub{
topics: make(map[string]map[string]*Subscriber),
}
}
// Subscribe adds a subscriber to a specific topic.
func (ps *PubSub) Subscribe(topic string, subID string) *Subscriber {
ps.mu.Lock()
defer ps.mu.Unlock()
// Initialize topic map if it doesn't exist
if _, ok := ps.topics[topic]; !ok {
ps.topics[topic] = make(map[string]*Subscriber)
}
// Create a new subscriber with a buffered channel
// Buffer size of 10 allows for brief bursts before dropping messages
sub := &Subscriber{
ID: subID,
Chan: make(chan Message, 10),
}
ps.topics[topic][subID] = sub
fmt.Printf("[System] %s subscribed to '%s'\n", subID, topic)
return sub
}
// Unsubscribe removes a subscriber from a topic.
func (ps *PubSub) Unsubscribe(topic string, subID string) {
ps.mu.Lock()
defer ps.mu.Unlock()
if subs, ok := ps.topics[topic]; ok {
if sub, exists := subs[subID]; exists {
close(sub.Chan) // Close the channel to signal the client
delete(subs, subID)
fmt.Printf("[System] %s unsubscribed from '%s'\n", subID, topic)
}
}
}
// Publish sends a message to all subscribers of a topic.
// It uses non-blocking sends to ensure the publisher isn't slowed down by slow consumers.
func (ps *PubSub) Publish(topic string, msg interface{}) {
ps.mu.RLock()
// We create a slice of pointers to avoid copying the struct and to release the lock fast
subs := make([]*Subscriber, 0, len(ps.topics[topic]))
for _, sub := range ps.topics[topic] {
subs = append(subs, sub)
}
ps.mu.RUnlock()
// Dispatch messages asynchronously (or non-blocking synchronously)
message := Message{Topic: topic, Content: msg}
for _, sub := range subs {
select {
case sub.Chan <- message:
// Message sent successfully
default:
// Channel full: Message dropped (Handle backpressure)
fmt.Printf("[Warning] Dropped message for %s (buffer full)\n", sub.ID)
}
}
}
// ---------------------------------------------------------
// Demonstration
// ---------------------------------------------------------
func main() {
broker := NewPubSub()
var wg sync.WaitGroup
// 1. Create Subscribers
// Sub1 listens to "sports"
sub1 := broker.Subscribe("sports", "Sub-1")
// Sub2 listens to "sports"
sub2 := broker.Subscribe("sports", "Sub-2")
// Sub3 listens to "news"
sub3 := broker.Subscribe("news", "Sub-3")
// 2. Start Listener Routines (Consumers)
// These run in the background processing incoming messages
// Listener for Sub-1
wg.Add(1)
go func(s *Subscriber) {
defer wg.Done()
for msg := range s.Chan {
fmt.Printf("[%s] Received: %v\n", s.ID, msg.Content)
// Simulate processing time
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
}
fmt.Printf("[%s] Channel closed, exiting.\n", s.ID)
}(sub1)
// Listener for Sub-2 (This one is slow)
wg.Add(1)
go func(s *Subscriber) {
defer wg.Done()
for msg := range s.Chan {
fmt.Printf("[%s] (Slow) Received: %v\n", s.ID, msg.Content)
// Simulate heavy processing (200ms)
time.Sleep(200 * time.Millisecond)
}
fmt.Printf("[%s] Channel closed, exiting.\n", s.ID)
}(sub2)
// Listener for Sub-3
wg.Add(1)
go func(s *Subscriber) {
defer wg.Done()
for msg := range s.Chan {
fmt.Printf("[%s] Received: %v\n", s.ID, msg.Content)
}
}(sub3)
// 3. Start Publishers
// Publisher 1: Sports
go func() {
for i := 0; i < 5; i++ {
broker.Publish("sports", fmt.Sprintf("Game Score Update %d", i))
time.Sleep(50 * time.Millisecond)
}
}()
// Publisher 2: News
go func() {
for i := 0; i < 3; i++ {
broker.Publish("news", fmt.Sprintf("Breaking News %d", i))
time.Sleep(100 * time.Millisecond)
}
}()
// Allow time for messages to flow
time.Sleep(1 * time.Second)
// 4. Cleanup
fmt.Println("\n[System] Shutting down...")
broker.Unsubscribe("sports", "Sub-1")
broker.Unsubscribe("sports", "Sub-2")
broker.Unsubscribe("news", "Sub-3")
wg.Wait()
fmt.Println("[System] All done.")
}