Sending and Receiving Messages with Google Cloud Pub/Sub

Google Cloud Pub/Sub is a fully managed messaging service that enables you to send and receive messages between applications or services in a scalable and reliable manner. In this guide, we'll explore the process of sending and receiving messages with Google Cloud Pub/Sub and provide sample Python code snippets for both tasks.

Key Concepts

Before we dive into the code, let's understand some key concepts related to Google Cloud Pub/Sub:

  • Topics: Messages are sent to topics, which are named resources that represent the stream of messages. Topics can have one or more subscribers.
  • Subscriptions: Subscriptions are named resources representing the stream of messages from a single, specific topic to be delivered to the subscribing application.
  • Publishers and Subscribers: Applications that send messages are called publishers, while applications that receive and process messages are called subscribers.

Sample Code: Sending and Receiving Messages with Pub/Sub

Publishing Messages to a Topic

Here's a sample Python code snippet for publishing messages to a Google Cloud Pub/Sub topic:

from import pubsub_v1
# Initialize the Publisher client
publisher = pubsub_v1.PublisherClient()
# Set your project ID and topic name
project_id = 'your-project-id'
topic_name = 'your-topic-name'
# Create a topic path
topic_path = publisher.topic_path(project_id, topic_name)
# Define a message
message_data = 'Hello, Pub/Sub!'
message_data = message_data.encode('utf-8')
# Publish the message
future = publisher.publish(topic_path, data=message_data)
print(f"Published message: {message_data}")

Subscribing to a Topic and Receiving Messages

Here's a sample Python code snippet for subscribing to a Google Cloud Pub/Sub topic and receiving messages:

from import pubsub_v1
# Initialize the Subscriber client
subscriber = pubsub_v1.SubscriberClient()
# Set your project ID, subscription name, and topic name
project_id = 'your-project-id'
subscription_name = 'your-subscription-name'
topic_name = 'your-topic-name'
# Create a subscription path
subscription_path = subscriber.subscription_path(project_id, subscription_name)
# Define a callback function to handle received messages
def callback(message):
print(f"Received message: {}")
# Subscribe to the topic and start receiving messages
subscriber.subscribe(subscription_path, callback=callback)
print(f"Subscribed to {subscription_name} for topic {topic_name}")
# Keep the script running to continue receiving messages
import time
while True:

Make sure to replace

, and other values with your specific project and configuration details.


Google Cloud Pub/Sub provides a powerful and reliable solution for sending and receiving messages in a distributed and scalable manner. By leveraging Pub/Sub, you can create event-driven systems and efficiently communicate between your cloud-based applications and services.