<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sanskar Mehta on Medium]]></title>
        <description><![CDATA[Stories by Sanskar Mehta on Medium]]></description>
        <link>https://medium.com/@sanskar.mehta?source=rss-afe0c8c1cb61------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yvjG2CkGHyKufXSf</url>
            <title>Stories by Sanskar Mehta on Medium</title>
            <link>https://medium.com/@sanskar.mehta?source=rss-afe0c8c1cb61------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:50:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanskar.mehta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Art of Reading Pub/Sub Message with Google Cloud Dataflow]]></title>
            <link>https://medium.com/mindful-engineering/the-art-of-reading-pub-sub-message-with-google-cloud-dataflow-a81139d40987?source=rss-afe0c8c1cb61------2</link>
            <guid isPermaLink="false">https://medium.com/p/a81139d40987</guid>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[apache-beam]]></category>
            <dc:creator><![CDATA[Sanskar Mehta]]></dc:creator>
            <pubDate>Wed, 08 Jan 2025 09:34:48 GMT</pubDate>
            <atom:updated>2025-01-08T09:34:48.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1omXpJQS2430NP_oJUI2A.png" /></figure><h3>Table of Contents</h3><p>1. <a href="#2143"><strong>Introduction</strong></a><br>2. <a href="#da4c"><strong>What is Pub/Sub?</strong></a><br>3. <a href="#a22a"><strong>How to create a Pub/Sub topic?</strong></a><br>4. <a href="#b771"><strong>Read messages from the Pub/Sub using the Dataflow Pipeline</strong></a><br>5. <a href="#a211"><strong>Conclusion</strong></a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F11842760980334684967&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Ffast-and-furious-car-gif-11842760980334684967&amp;image=https%3A%2F%2Fmedia.tenor.com%2FpFnwXbC0qycAAAAN%2Ffast-and.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad33b75e5254ed32c7e89217f7536b67/href">https://medium.com/media/ad33b75e5254ed32c7e89217f7536b67/href</a></iframe><h3>Introduction</h3><p>This blog post will take you through the process of creating Pub/Sub topics and default subscriptions in Google Cloud and then read messages from those subscriptions using Google Cloud Dataflow.</p><h3>What is Pub/Sub?</h3><p><a href="https://cloud.google.com/pubsub/docs/overview"><strong>Pub/Sub (Publish-Subscribe)</strong></a> is a messaging paradigm where senders of messages, called <strong>publishers</strong>, do not program the messages to be sent to specific receivers. Instead, publishers categorize messages into classes, and subscribers express interest in receiving messages that fall into certain classes.</p><p><strong>Key Concepts:</strong></p><ol><li><strong>Topic:</strong> A designated entity that represents a feed of messages; publishers send messages to one specific topic.</li><li><strong>Subscriber:</strong> An entity that expresses interest in receiving messages about a particular topic.</li><li><strong>Message:</strong> The data that gets transmitted between publishers and subscribers.</li></ol><p><strong>How it Works:</strong></p><ol><li><strong>Publishers:</strong> Send messages about a particular topic.</li><li><strong>Subscribers:</strong> Subscribe to a particular topic and receive the messages published on that topic.</li><li><strong>Message Broker:</strong> A middleman who handles the routing of the messages from the publishers to the subscribers.</li></ol><p><strong>Benefits of Pub/Sub:</strong></p><ul><li><strong>Decoupling:</strong> Publisher and subscriber are decoupled, so they need not be aware of each other’s presence. This makes the system much more flexible and scalable.</li><li><strong>Scalability:</strong> Pub/Sub can process very high volumes of messages, including hundreds or even thousands of subscribers.</li><li><strong>Reliability: </strong>Generally speaking, Pub/Sub is quite reliable because it makes sure that messages are received by subscribers even in cases where there is a short-term network failure.</li><li><strong>Asynchronous Communication:</strong> Pub/Sub promotes asynchronous communication, which generally may improve performance and efficiency.</li></ul><p><strong>Use Cases:</strong></p><ul><li><strong>Event-driven architectures:</strong> Pub/Sub is widely used to implement event-driven architectures, where events are published to a topic and subscribers react to those events.</li><li><strong>Microservices:</strong> Pub/Sub can be used to communicate between microservices in a distributed system.</li><li><strong>Data streaming:</strong> Pub/Sub can be used to stream data from one system to another.</li><li><strong>Real-time analytics:</strong> Pub/Sub can be used to collect and process real-time data.</li></ul><p><strong>Popular Pub/Sub Systems:</strong></p><ul><li><strong>Google Cloud Pub/Sub:</strong> A fully managed, real-time messaging service from Google Cloud.</li><li><strong>Amazon SNS (Simple Notification Service):</strong> A scalable, flexible, high-throughput, and highly available messaging service from AWS.</li><li><strong>Apache Kafka:</strong> An open-source distributed streaming platform.</li><li><strong>RabbitMQ:</strong> An open-source message broker that supports a variety of messaging protocols.</li></ul><h3>How to create a Pub/Sub topic?</h3><p>Step 1:</p><ul><li>In the Google Cloud Console, go to the Pub/Sub service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*NlYqfzPPBQMAM7THGJntQg.png" /><figcaption>Navigation to Pub/Sub</figcaption></figure><p>Step 2:</p><ul><li>Click “Create Topic”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yKmYCGNmVTwURpIf07w5SA.png" /><figcaption>Create Topic</figcaption></figure><p>Step 3:</p><ul><li>Enter a unique name for your topic.</li><li>Select the options shown in the image to create a default subscription.</li><li>Click “Create”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vqUb3ah_EEwNLkjf6FiunA.png" /><figcaption>Topic creation configuration details</figcaption></figure><h3>Read messages from the Pub/Sub using the Dataflow Pipeline</h3><p>In this chapter, we will go over the code that reads messages from a Pub/Sub subscription with Dataflow. We will outline what the code does and how it fits into the entire message-processing pipeline.</p><p>The project ID can be obtained in the Google Cloud Console as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*o32AyA8mlDWFqDBdOGy0-Q.png" /><figcaption>Project details</figcaption></figure><p>Below is the requirements.txt file:</p><pre>apache-beam==2.60.0 <br>python-dotenv==1.0.1</pre><p>Environment variables for the given code:</p><pre>PROJECT_ID=&quot;&lt;PROJECT_ID&gt;&quot; #Need to pass the project id within which we want to deploy the pipeline<br>_JOB_NAME=&quot;&lt;JOB_NAME&gt;&quot; #Need to write the name of the dataflow job<br>_TEMP_LOCATION=&quot;&lt;TEMP_LOCATION&gt;&quot; #Need to add gs uri for the temp folder<br>_STAGING_LOCATION=&quot;&lt;STAGING_LOCATION&gt;&quot; #Need to add gs uri for the staging folder<br>_REGION=&quot;&lt;REGION&gt;&quot; #Here we need to pass the region in which we want to deploy our pipeline<br>_SUBNETWORK_NAME=&quot;&lt;SUBNETWORK_NAME&gt;&quot; #Here we need to pass the name of the sub network if we have created any subnet or VPC<br>GOOGLE_APPLICATION_CREDENTIAL=&quot;&lt;GOOGLE_APPLICATION_CREDENTIAL&gt;&quot; # Need to pass the path of the service account file</pre><p>Demo .env file:</p><pre>PROJECT_ID=&quot;analog-decoder-443716-e2&quot; <br>_JOB_NAME=&quot;demo-job&quot;<br>_TEMP_LOCATION=&quot;gs://demo-bucket/demo-job/temp&quot;<br>_STAGING_LOCATION=&quot;gs://demo-bucket/demo-job/staging&gt;&quot;<br>_REGION=&quot;us-central1&quot;<br>_SUBNETWORK_NAME=&quot;default&quot;<br>GOOGLE_APPLICATION_CREDENTIAL=&quot;demo-service-account.json&quot;</pre><p><strong>Code:</strong></p><pre>import os<br>import logging<br><br>import apache_beam as beam<br>from apache_beam.options.pipeline_options import PipelineOptions, StandardOptions<br>from apache_beam.io.gcp.pubsub import ReadFromPubSub<br><br>from dotenv import load_dotenv, find_dotenv<br><br>load_dotenv(find_dotenv(), override=True)<br><br><br>def read_pubsub_message(message):<br>    &quot;&quot;&quot;<br>    Reading published message from PubSub and convert it to normal python dictionary<br>    :param message:<br>    :return:<br>    &quot;&quot;&quot;<br>    import json<br><br>    try:<br>        message_data = message.decode(&#39;utf-8&#39;)<br>        parsed_message = json.loads(message_data)<br>        logging.info(f&quot;Message data: {message_data} &quot;)<br>        return parsed_message<br>    except Exception as err:<br>        logging.error(f&quot;Error in reading message from the pubsub: {err}&quot;)<br>        return {}<br><br><br>def run(subscription_name):<br>    common_options = [<br>        f&#39;--runner=DataflowRunner&#39;,  # or DirectRunner for local execution<br>        f&#39;--project={os.getenv(&quot;PROJECT_ID&quot;)}&#39;,<br>        f&#39;--job_name={os.getenv(&quot;_JOB_NAME&quot;)}&#39;,  # write dataflow job name<br>        f&#39;--temp_location={os.getenv(&quot;_TEMP_LOCATION&quot;)}&#39;,<br>        # Required. Path for temporary files. Must be a valid Google Cloud Storage URL that begins with gs://.<br>        f&#39;--staging_location={os.getenv(&quot;_STAGING_LOCATION&quot;)}&#39;,<br>        # Optional. Cloud Storage bucket path for staging your binary and any temporary files. Must be a valid Cloud Storage URL that begins with gs://. If not set, defaults to a staging directory within temp_location.<br>        f&#39;--region={os.getenv(&quot;_REGION&quot;)}&#39;,<br>        f&#39;--subnetwork=https://www.googleapis.com/compute/v1/projects/{os.getenv(&quot;PROJECT_ID&quot;)}/regions/{os.getenv(&quot;_REGION&quot;)}/subnetworks/{os.getenv(&quot;_SUBNETWORK_NAME&quot;)}&#39;,<br>        f&#39;--save_main_session=True&#39;,<br>        # Save the main session state so that pickled functions and classes defined in __main__ (e.g. interactive session) can be unpickled. Default value is false.<br>        f&#39;--machine_type=n1-standard-1&#39;,<br>        # machine_type will be based on your requirement by default it gonna use n1-standard-2 for streaming and for batch it gonna use n1-standard-1<br>        f&#39;--requirements_file=requirements.txt&#39;,  # path of requirements.txt file<br>    ]<br><br>    logging.info(f&quot;PIPELINE OPTIONS : {common_options}&quot;)<br>    options = PipelineOptions(common_options)<br>    options.view_as(StandardOptions).streaming = True<br><br>    logging.info(&quot;PIPELINE WILL BE EXECUTED FROM HERE &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; &quot;)<br>    pipeline = beam.Pipeline(options=options)<br><br>    parsed_message = (<br>            pipeline<br>            | &quot;Read from PubSub&quot; &gt;&gt; ReadFromPubSub(subscription=subscription_name)<br>            | &quot;Process and log&quot; &gt;&gt; beam.Map(read_pubsub_message)<br>    )<br><br>    result = pipeline.run()<br>    result.wait_until_finish(duration=120000)  # Stop locally pipeline execution after 2 minutes<br>    logging.info(&quot;PIPELINE IS EXECUTED COMPLETELY &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    run(subscription_name=os.getenv(&quot;_SUBSCRIPTION_NAME&quot;))</pre><p>i ) <strong>Imports:</strong></p><ul><li>Imports the necessary libraries, including apache_beam for Dataflow functionalities, PipelineOptions and StandardOptions for pipeline configuration, and ReadFromPubSub for reading from Pub/Sub.</li><li><strong>NOTE: Import statements should generally be placed within the functions where they are used within Apache Beam’s </strong><strong>PTransform classes. This is primarily due to the </strong><a href="https://cloud.google.com/dataflow/docs/guides/common-errors#name-error"><strong>serialization</strong></a><strong> process employed by Dataflow.</strong></li></ul><p>ii) read_pubsub_message<strong> function:</strong></p><ul><li>It will decode the message and log it.</li></ul><p>iii) run<strong> function:</strong></p><ul><li>The run function initializes the pipeline of Dataflow by defining needed options. After that, the messages are read from the Pub/Sub subscription indicated and then passed with the read_pubsub_message function for processing before finally running and waiting for the pipeline to be done.</li></ul><h3>Conclusion</h3><p>This guide outlines the foundational steps to create a Pub/Sub topic with a default subscription and then leverage Google Cloud Dataflow to read and process messages from that subscription. Using the combined strengths of Pub/Sub and Dataflow, you can construct robust and scalable real-time data processing pipelines to meet your specific business needs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ohs7JG6cq7EWesFcQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fstudiosoriginals-3ohs7JG6cq7EWesFcQ&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExdGV5c2x4NGd2N3g1anVqaW1kYjJrbnRvMXpnMmM3ZGk3eWJ5M3hlcSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3ohs7JG6cq7EWesFcQ%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="291" frameborder="0" scrolling="no"><a href="https://medium.com/media/418a794f50810d82c01c5714f63fa431/href">https://medium.com/media/418a794f50810d82c01c5714f63fa431/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a81139d40987" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindful-engineering/the-art-of-reading-pub-sub-message-with-google-cloud-dataflow-a81139d40987">The Art of Reading Pub/Sub Message with Google Cloud Dataflow</a> was originally published in <a href="https://medium.com/mindful-engineering">Mindful Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>