How to Implement Publish-Subscribe Fanout with Multiple Subscribers in Python

Create a simple publish-subscribe system in Python that broadcasts messages to multiple subscriber callbacks for a given topic.

Easy Python 3.9+ Aug 9, 2026 Streaming & messaging 14 views 0 copies

Python code

33 lines
Python 3.9+
import time

class PubSub:
    def __init__(self):
        self.subscribers = {}

    def subscribe(self, topic, callback):
        if topic not in self.subscribers:
            self.subscribers[topic] = []
        self.subscribers[topic].append(callback)

    def publish(self, topic, message):
        if topic in self.subscribers:
            for callback in self.subscribers[topic]:
                callback(message)


def subscriber_1(msg):
    print(f"Subscriber 1 received: {msg}")

def subscriber_2(msg):
    print(f"Subscriber 2 received: {msg}")

def subscriber_3(msg):
    print(f"Subscriber 3 received: {msg}")


pubsub = PubSub()
pubsub.subscribe("news", subscriber_1)
pubsub.subscribe("news", subscriber_2)
pubsub.subscribe("news", subscriber_3)

pubsub.publish("news", "Breaking story")

Output

stdout
Subscriber 1 received: Breaking story
Subscriber 2 received: Breaking story
Subscriber 3 received: Breaking story

How it works

The PubSub class maintains a dictionary mapping topics to lists of callback functions. The subscribe method appends a callback to the topic's list, creating the list if the topic is new. When publish is called, it retrieves the list of callbacks for the topic and invokes each one with the message. This decouples the sender (publisher) from receivers (subscribers), allowing multiple subscribers to react to the same event without direct coupling.

Common mistakes

  • Forgetting to initialize the subscriber list for a new topic before appending
  • Publishing to a topic that has no subscribers, which silently does nothing
  • Assuming subscribers are called in a specific order or synchronously without considering thread safety

Variations

  1. Use `asyncio` to implement an asynchronous pub-sub for non-blocking event handling
  2. Use a queue (e.g., `queue.Queue`) to buffer messages for asynchronous processing by subscribers

Real-world use cases

  • Event-driven microservices: a service publishes order-created events to notify inventory and notification services.
  • Real-time notification systems: broadcasting new messages to multiple connected WebSocket clients.
  • Decoupling analytics: publishing user actions to multiple listeners for logging, tracking, and feature flag evaluation.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Streaming & messaging

Related tutorials and quizzes for this topic.