What is Pub/Sub in GCP: Simple Explanation and Example
Pub/Sub in Google Cloud Platform (GCP) is a messaging service that lets applications send and receive messages asynchronously. It works like a mail system where publishers send messages to a topic, and subscribers receive those messages from subscriptions to that topic.How It Works
Imagine you want to send letters to many friends without calling each one. You put your letters in a mailbox labeled with a topic name. Your friends subscribe to that mailbox and get the letters when they arrive. In GCP Pub/Sub, the mailbox is called a topic, the letters are messages, and your friends are subscribers.
When a publisher sends a message to a topic, Pub/Sub stores it and delivers it to all subscribers of that topic. Subscribers can be apps or services that process the messages independently. This setup helps systems talk to each other without waiting, making them faster and more reliable.
Example
This example shows how to publish a message to a Pub/Sub topic using Python. It sends a simple text message that subscribers can receive.
from google.cloud import pubsub_v1 project_id = "your-project-id" topic_id = "your-topic-id" publisher = pubsub_v1.PublisherClient() topic_path = publisher.topic_path(project_id, topic_id) message_text = "Hello, Pub/Sub!" message_data = message_text.encode("utf-8") future = publisher.publish(topic_path, data=message_data) print(f"Published message ID: {future.result()}")
When to Use
Use Pub/Sub when you want to connect different parts of your system without making them wait for each other. It is great for:
- Sending notifications or alerts to many users or services.
- Processing data streams like logs or sensor data in real time.
- Decoupling microservices so they work independently and scale easily.
- Building event-driven systems where actions happen after certain events.
Key Points
- Pub/Sub uses topics and subscriptions to send messages.
- Publishers send messages; subscribers receive them asynchronously.
- It helps build scalable, reliable, and loosely connected systems.
- Supports multiple programming languages and integrates with many GCP services.