Implementing the Fan Out Pattern

Introduction

Welcome back! In this lesson, we will explore how to implement the fan-out messaging pattern using Google Cloud messaging services. The fan-out pattern allows a single publisher to send messages to multiple independent subscribers, enabling efficient and scalable communication between different parts of your application. By leveraging topics and multiple subscriptions, you can ensure that each subscriber receives a copy of every message published.

Initial setup

Consider a scenario with three services: Service A, Service B, and Service C. Service A needs to send updates to both Service B and Service C. Instead of sending messages directly to each service, we can create a topic that acts as a central channel. Both Service B and Service C can then subscribe to this topic, ensuring that they each receive all messages published by Service A.

Publishing to a Topic

Let's see how Service A can publish messages to a topic. We'll also include additional message attributes to provide more context to subscribers.

from google.cloud import pubsub_v1

# Initialize the publisher client
publisher = pubsub_v1.PublisherClient()

# Define the topic path
project_id = "your-gcp-project-id"
topic_id = "service-a-updates"
topic_path = publisher.topic_path(project_id, topic_id)

# Create the topic (if it doesn't exist)
try:
    publisher.create_topic(request={"name": topic_path})
    print(f"Topic created: {topic_path}")
except Exception:
    print(f"Topic already exists: {topic_path}")

# Publish a basic message
future = publisher.publish(topic_path, b"Updates for Services B and C")
print(f"Published message ID: {future.result()}")

# Publish a message with additional attributes
future_advanced = publisher.publish(
    topic_path,
    b"News update",
    priority="high",
    department="IT"
)
print(f"Published advanced message ID: {future_advanced.result()}")

Output:

Topic created: projects/your-gcp-project-id/topics/service-a-updates
Published message ID: 8234567890123456789
Published advanced message ID: 8234567890123456790

In these examples, a message is published to the service-a-updates topic. The second message includes attributes such as priority and department, which can be used by subscribers to filter or process messages accordingly.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal