Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Publish-Subscribe Architecture

1. Introduction

The Publish-Subscribe (Pub-Sub) architecture is a messaging pattern where senders (publishers) send messages without knowing the receivers (subscribers). This pattern is widely used in distributed systems, enabling decoupling of components.

2. Key Concepts

  • **Publisher**: The component that sends messages.
  • **Subscriber**: The component that receives messages.
  • **Message Broker**: An intermediary that facilitates communication between publishers and subscribers.
  • **Topics**: Channels through which messages are sent and received.

3. Architecture Overview

The architecture typically includes the following components:

Components

  • Message Producers: Generate messages based on events.
  • Message Broker: Receives messages from producers and routes them to subscribers.
  • Message Consumers: Receive messages from the broker and process them.

Flowchart


    graph TD;
        A[Publisher] -->|Publish Message| B[Message Broker];
        B -->|Distribute Message| C[Subscriber];
    

4. Implementation

Here's an example of implementing a simple Pub-Sub system using Python with a basic in-memory message broker:


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

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

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

class Subscriber:
    def __init__(self, name):
        self.name = name

    def receive(self, message):
        print(f"{self.name} received: {message}")

broker = MessageBroker()

sub1 = Subscriber("Subscriber 1")
sub2 = Subscriber("Subscriber 2")

broker.subscribe("news", sub1)
broker.subscribe("news", sub2)

broker.publish("news", "New article published!")
        

5. Best Practices

  • Use topics wisely to avoid message overload.
  • Implement message acknowledgment to ensure delivery.
  • Consider message persistence for reliability.
  • Monitor performance and scale the message broker as necessary.

6. FAQ

What are the advantages of Pub-Sub architecture?

It provides scalability, flexibility, and loose coupling between components.

When should I use Pub-Sub architecture?

When you have multiple producers and consumers and need to decouple them for better system organization.