Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DevOps Lifecycle
  • DevOps Roadmap
  • Docker Tutorial
  • Kubernetes Tutorials
  • Amazon Web Services [AWS] Tutorial
  • AZURE Tutorials
  • GCP Tutorials
  • Docker Cheat sheet
  • Kubernetes cheat sheet
  • AWS interview questions
  • Docker Interview Questions
  • Ansible Interview Questions
  • Jenkins Interview Questions
Open In App
Next Article:
Event-Driven Architecture Patterns in Cloud Native Applications
Next article icon

How to Use Cloud Pub/Sub for Event-driven Architecture on GCP?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Pre-requisites: Google Cloud Services

Cloud Pub/Sub is a fully managed, scalable messaging system offered by Google Cloud Platform (GCP) that enables asynchronous communication between applications. It is a simple and reliable way to exchange data between services and applications in real time. With its event-driven architecture, Cloud Pub/Sub provides a flexible way to build scalable, reliable, and loosely-coupled applications that can handle large-scale data processing.

In this article, we will explore how to use Cloud Pub/Sub for event-driven architecture on GCP. We will go through the steps required to set up a Cloud Pub/Sub topic and subscription, publish and consume messages, and demonstrate how to integrate Cloud Pub/Sub with other GCP services.

Key Terminologies

  • Topic: A named resource to which messages can be sent by publishers.
  • Subscription: A named resource representing the stream of messages from a single, specific topic, to be delivered to the subscribing application.
  • Publisher: An application or service that sends messages to a topic.
  • Subscriber: An application or service that receives messages from a subscription.
  • Message: The unit of data exchanged between publishers and subscribers.


Let's say you are building a simple application that sends notifications to users when a new post is added to a forum. You can use Cloud Pub/Sub to build an event-driven architecture where the application publishes a message to a Cloud Pub/Sub topic whenever a new post is added, and subscribers consume these messages to send notifications to users.

Steps to use Cloud Pub/Sub for event-driven architecture:

Step 1: Sign up for a Google Cloud Platform (GCP) account if you don’t already have one. You can sign up for a free trial that includes $300 in credit to use on GCP services.

Step 2: Enable Cloud Pub/Sub API: In the Cloud Console, navigate to APIs & Services > Dashboard, click Enable APIs and Services, search for Cloud Pub/Sub, and enable the API.

 

Step 3: Create a Topic: In the Cloud Console, navigate to Pub/Sub > Topics.

 

Step 4: After Clicking on 'Topics' , Click on Create Topic.

 

Step 5: Give a name to your Pub/Sub topic such as "new-post-topic" and keep all the things as default and Click on 'CREATE'.

 

Step 6: Create a Subscription: In the Cloud Console, navigate to your topic, click Create Subscription, give it a name such as "new-post-subscription", and choose the delivery type as "Pull". 

 

Step 7: Leave all other fields as it is and Click on 'Create'.

 

Now you have done with creating Cloud Pub/Sub for event-driven architecture. 

Step 8: Publish a Message 

In your application code, whenever a new post is added, publish a message to the "new-post-topic" with the post information as the payload. 


Here's an example code snippet in Python:

Python3
from google.cloud import pubsub_v1  publisher = pubsub_v1.PublisherClient() topic_path = "projects/<project-id>/topics/new-post-topic"  def publish_message(post):     data = post.encode("utf-8")     future = publisher.publish(topic_path, data=data)     print(future.result()) 

 

Step 9: Consume Messages

In your notification service code, set up a subscription to the "new-post-subscription" and consume messages whenever they are available. 


Here's an example code snippet in Python:

Python3
from google.cloud import pubsub_v1  subscriber = pubsub_v1.SubscriberClient() subscription_path = "projects/<project-id>/subscriptions/new-post-subscription"  def handle_message(message):     print(f"Received message: {message.data}")     # Send notification to users     message.ack()  subscriber.subscribe(subscription_path, callback=handle_message)  while True:     # Wait for messages     time.sleep(1) 

With these steps, your application can now use Cloud Pub/Sub to publish and consume messages and build a scalable and reliable notification system for new posts in the forum.


Next Article
Event-Driven Architecture Patterns in Cloud Native Applications
author
nayan_nand
Improve
Article Tags :
  • How To
  • DevOps
  • Google-Cloud-Platform
  • google-cloud-pub/sub

Similar Reads

  • How To Use Azure Functions For Event-Driven Architecture ?
    Azure Function is a service provided by Microsoft Azure for running serverless workloads. It provides support for building and developing event-driven applications without explicitly provisioning or managing infrastructure. It also provided for the development of applications based on functions in t
    4 min read
  • How to Use Cloud Debugger For Debugging Applications On GCP?
    Application debugging is a crucial step in the development process since it enables developers to quickly find and fix problems. Developers can debug their applications running on the Google Cloud Platform (GCP) with the help of a potent tool called Cloud Debugger without interfering with their regu
    4 min read
  • Event-Driven Architecture Patterns in Cloud Native Applications
    Event-driven architecture (EDA) transforms cloud-native applications by enabling real-time responsiveness and scalability. This article explores key EDA patterns, their benefits in dynamic cloud environments, and practical strategies for implementing them to optimize performance and resilience. Impo
    9 min read
  • How to Use Cloud SQL For MySQL with Automatic Failover on GCP?
    Google Cloud Platform (GCP) is a Cloud Service Provider that offers different service models like Iaas(Infrastructure as a service), Paas(Platform as a service), and Saas(Software as a service). Cloud SQL is a relational Database service offered by Google. Users can run MySQL, SQL Server, and Postgr
    7 min read
  • Resource Pooling Architecture in Cloud Computing
    Pre-requisite: Cloud Computing A resource pool is a group of resources that can be assigned to users. Resources of any kind, including computation, network, and storage, can be pooled. It adds an abstraction layer that enables uniform resource use and presentation. In cloud data centers, a sizable p
    3 min read
  • How To Create a Pub/Sub Topic on GCP?
    Pub/Sub is a messaging service that allows you to send and receive messages between independent applications. Separating the senders and receivers enables secure and consistent communication between independently developed applications. With Pub/Sub, you can expect quick delivery of messages while e
    2 min read
  • Event-Driven Architecture vs. Microservices Architecture
    In system design, choosing the right architecture is crucial for building scalable and efficient systems. Two popular approaches, Event-Driven Architecture (EDA) and Microservices Architecture, each offer unique benefits. This article explores their definitions, differences, use cases, and more. Tab
    4 min read
  • Edge-Cloud Architecture in Distributed System
    Edge-Cloud Architecture in Distributed Systems explores a modern approach to managing data and processing power. It discusses how combining edge computing (smaller, local data centers) with cloud computing (larger, centralized data centers) can improve efficiency and response times for applications.
    11 min read
  • Google Cloud Architecture Framework
    Pre-requisite: Google Cloud Google Cloud Architecture Framework is a set of best practices and guidelines provided by Google Cloud Platform (GCP) to help users design, build, and operate scalable, secure, and highly-available applications on GCP. The framework is designed to help users make the best
    8 min read
  • Event-Driven APIs in Microservice Architectures
    Event-driven APIs in Microservice Architectures explain how microservices, which are small, independent services in a larger system, can communicate through events. Instead of calling each other directly, services send and receive messages (events) when something happens, like a user action or a sys
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences