<?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 Tanmay Sakpal on Medium]]></title>
        <description><![CDATA[Stories by Tanmay Sakpal on Medium]]></description>
        <link>https://medium.com/@tanmay.sakpal?source=rss-b35ae0f531c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OEmm2fAdmBGe3Vv28JOdrg.jpeg</url>
            <title>Stories by Tanmay Sakpal on Medium</title>
            <link>https://medium.com/@tanmay.sakpal?source=rss-b35ae0f531c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:31:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanmay.sakpal/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[Streamlined Data Processing: Scheduling, Notification, and Auditing with PySpark on GCE]]></title>
            <link>https://blog.searce.com/streamlined-data-processing-scheduling-notification-and-auditing-with-pyspark-on-gce-60f73d111484?source=rss-b35ae0f531c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/60f73d111484</guid>
            <category><![CDATA[data-and-analytics]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Tanmay Sakpal]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 07:25:05 GMT</pubDate>
            <atom:updated>2023-10-12T07:25:05.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OZtL1Ze7AthkVF9u" /><figcaption>Architectural Diagram</figcaption></figure><p>An ingenious solution designed to navigate the data avalanche with finesse. In the sections that follow, we’ll unveil a carefully crafted architecture and delve into the Pyspark code that powers it. From ingesting JSONL files in Google Cloud Storage (GCS) to orchestrating data transformations with PySpark, loading data into Google BigQuery (BQ), and maintaining meticulous audit logs, this architecture is a testament to the power of automation and intelligence.</p><h3>Components of the Architecture:</h3><ol><li><strong>JSONL Files on GCS Buckets</strong>: Data is securely stored in Google Cloud Storage (GCS) buckets in JSONL format for easy access.</li><li><strong>GCE VM with PySpark Server:</strong> Google Compute Engine (GCE) hosts a powerful PySpark server for large-scale data transformations.</li><li><strong>PySpark Script</strong>: A crucial script in GCP VM that efficiently processes JSON files, converts them to Parquet, and loads them into BQ tables.</li><li><strong>Scheduled Execution with Crontab</strong>: PySpark script runs every 5 minutes, ensuring real-time access to the latest data.</li><li><strong>BQ Audit Table for Logging:</strong> Google BigQuery (BQ) Audit table maintains a transparent log of all processing activities.</li><li><strong>SMTP for Error Notifications:</strong> Robust error notification system sends alerts via email for prompt issue resolution.</li></ol><h3>PySpark Installation on GCE :</h3><p><strong>Step 1</strong> : Install Java — PySpark requires Java to be installed on your system. Install Java using the following command in your terminal :</p><pre>$sudo apt install default-jdk</pre><p><strong>Step 2</strong> : Install Apache Spark</p><p>a) Download Apache Spark from the official website (https://spark.apache.org/downloads.html)</p><pre>$wget https://archive.apache.org/dist/spark/spark-3.2.0/spark-3.2.0-bin-hadoop3.2.tgz</pre><p>b) Extract the file</p><pre>$tar -xvzf spark-3.2.0-bin-hadoop3.2.tgz</pre><p>c) Move the extracted folder to the /opt directory</p><pre>$sudo mv spark-3.2.0-bin-hadoop3.2 /opt/spark</pre><p><strong>Step 3</strong> : Set Up Environment Variables</p><p>a) To set permanent environment variables</p><pre>$sudo nano ~/.bashrc</pre><p>b) Write a line for each variable you wish to add using the following syntax</p><pre>export SPARK_HOME=/opt/spark<br>export PATH=$PATH:$SPARK_HOME/bin:$SPARK_HOME/sbin</pre><p>c) Source the updated ~/.bashrc file to apply the changes:</p><pre>$source ~/.bashrc</pre><p><strong>Step 4</strong> : Install PySpark</p><p>Install PySpark using pip:</p><pre>$pip install pyspark</pre><p><strong>Step 5</strong> : Install “gcs-connector-hadoop3-latest.jar” which allows you to read from and write to GCS buckets</p><pre>$wget https://storage.googleapis.com/hadoop-lib/gcs/gcs-connector-hadoop3-latest.jar</pre><p><strong>Step 6</strong> : Verify PySpark Installation</p><pre>$pyspark</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*HHuiOKvdKD0ISKL8" /><figcaption>Successful PySpark Installation</figcaption></figure><p>Kudos, you have successfully installed Spark on GCE</p><p>Now, we’ll dive into the Python spark code that powers each component of our architecture. These code snippets provide a step-by-step guide to how data is ingested, transformed and logged into the Audit Table.</p><h3>Code Walkthrough:</h3><ol><li><strong>Data Ingestion from GCS</strong>:</li></ol><pre>#Get the input bucket files<br>client = storage.Client()<br>gcs_bucket_json = &quot;in_datalake&quot;<br>bucket = client.get_bucket(gcs_bucket_json)<br>directory_path = &#39;in-ecommerce/orders/bronze/&#39;<br><br># Get the last 1 hour of gcs files<br>five_minutes_ago = datetime.utcnow() - timedelta(minutes=5)<br><br># List all the files in the specified directory<br>blobs = bucket.list_blobs(prefix=directory_path)<br><br>recent_objects = []<br>for blob in blobs:<br>   # Get the blob&#39;s creation time and convert it to a datetime object<br>   creation_time = blob.time_created.timestamp()<br>   creation_time_datetime = datetime.utcfromtimestamp(creation_time)<br>   # Check if the object was created in the last hour and it&#39;s not a directory<br>   if (<br>       creation_time_datetime &gt;= five_minutes_ago and<br>       not blob.name.endswith(&#39;/&#39;) <br>   ):<br>       recent_objects.append(&quot;gs://{}/{}&quot;.format(gcs_bucket_json, blob.name))</pre><p>This code sets up the data ingestion process. It connects to Google Cloud Storage (GCS), where JSONL files are stored. It lists all files in a specified directory, filtering for files created within the last 5 minutes. These recent files are collected in the recent_objects list for processing.</p><p>2. <strong>PySpark Data Transformation :</strong></p><pre>final_df = None<br>processed_files = [] # Initialize a list to store processed file names<br><br># Iterate through recent_objects and process only new files<br>for file_name in recent_objects:<br>   if file_name not in processed_files:<br>       # Process the file<br>       df = spark.read.json(file_name)<br>       # Add the processed file to the list<br>       processed_files.append(file_name)<br><br>       if final_df is None:<br>           final_df = df<br>       else:<br>           final_df = final_df.union(df)<br><br>if final_df is None:<br>    print(&quot;No data to process. Exiting...&quot;)<br>    #Make successful entry into Audit table as there are no files to process<br>    bigquery_project = &quot;your-project-id&quot;<br>    audit_dataset = &quot;Audit_dataset&quot;<br>    audit_table = &quot;audit_table&quot;<br>    bq_client = bigquery.Client()<br>    table_ref = bq_client.dataset(audit_dataset).table(audit_table)<br>    table = bq_client.get_table(table_ref)<br>    # Create a list of rows to insert<br>    rows_to_insert = []<br>    current_timestamp = datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br><br>    #Insert row to Audit table with schema Job_name, Job_status, run_timestamp, files_processed, error_details<br>    rows_to_insert.append((u&quot;orders_job&quot;, u&quot;Pass&quot;, current_timestamp,len(recent_objects), u&quot;&quot;))<br>    errors = bq_client.insert_rows(table, rows_to_insert)<br>    if errors == []:<br>      print(&quot;success&quot;)<br>    spark.stop()<br>    sys.exit()<br><br>  # Coalesce the DataFrame to a single partition (optional)<br>  json_files = final_df.coalesce(1)<br>  gcs_bucket_parquet = &quot;in_datalake&quot;<br>  parquet_path = &quot;gs://{}/in-ecommerce/orders/silver/&quot;.format(gcs_bucket_parquet)<br><br>  # Write the data as a single Parquet file to the output GCS path<br>  json_files.write.mode(&quot;overwrite&quot;).parquet(parquet_path)</pre><p>This code snippet JSON files are read into a DataFrame (df) and then appended to a final DataFrame (final_df). This process efficiently combines data from multiple JSON files. Then, we write this transformed data as a single Parquet file to a specific location in Google Cloud Storage (GCS).</p><p><strong><em>IF THERE’s NO DATA TO PROCESS, </em></strong>it prints a message indicating that there’s nothing to process. It then logs a “Pass” entry into an Audit table in BigQuery, indicating a successful run. The audit entry includes details like the job name, timestamp, the number of processed files (which is zero in this case), and an empty error message. Finally, it stops the Spark session and exits the script since there’s nothing to process further.</p><p>3. <strong>Loading Data into BigQuery</strong> :</p><pre># Define your GCS and BigQuery configurations<br>bigquery_dataset = &quot;IN_ecommerce&quot;<br>bigquery_table = &quot;orders&quot;<br><br># Read the Parquet file into a DataFrame<br>parquet_df = spark.read.parquet(parquet_path)<br><br># Append the DataFrame to a BigQuery table<br>parquet_df.write \<br>  .format(&quot;bigquery&quot;) \<br>  .option(&quot;temporaryGcsBucket&quot;, gcs_bucket_parquet) \<br>  .option(&quot;table&quot;, &quot;{}.{}.{}&quot;.format(bigquery_project, bigquery_dataset, bigquery_table)) \<br>  .option(&quot;schema_update_options&quot;, &quot;ALLOW_FIELD_ADDITION&quot;) \<br>  .mode(&quot;append&quot;) \<br>  .save()</pre><p>This code snippet handles the loading of data into Google BigQuery. The Parquet data, processed earlier, is read into a DataFrame (parquet_df) and then appended to the specified BigQuery table, allowing for schema updates. So, when new files are added to GCS with additional schema our this part of code will handle the dynamic schema updation.</p><p>4. <strong>Audit Logging </strong>:</p><pre>try : <br>    code snippet (1)<br>    code snippet (2)<br>    code snippet (3)<br>    <br>    #after the data is loaded into BQ table make successful audit entry<br>    audit_dataset = &quot;Audit_dataset&quot;<br>    audit_table = &quot;audit_table&quot;<br>    bq_client = bigquery.Client()<br>    table_ref = bq_client.dataset(audit_dataset).table(audit_table)<br>    table = bq_client.get_table(table_ref)<br>    rows_to_insert = []<br>    current_timestamp = datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>    #Insert row to Audit table with schema Job_name, Job_status, run_timestamp, files_processed, error_details<br>    rows_to_insert.append((u&quot;orders_job&quot;, u&quot;Pass&quot;, current_timestamp,len(recent_objects), u&quot;&quot;))<br>    errors = bq_client.insert_rows(table, rows_to_insert)<br>    if errors == []:<br>       print(&quot;success&quot;)<br><br>    # Stop the Spark session<br>    spark.stop()<br><br><br>#if there’s error, from exception block make error audit entry<br>except Exception as e:<br>    print(&quot;Error: {}&quot;.format(str(e)))<br>    bq_client = bigquery.Client()<br>    table_ref = bq_client.dataset(audit_dataset).table(audit_table)<br>    table = bq_client.get_table(table_ref)<br>    rows_to_insert = []<br>    # Define the error message<br>    error_message = str(e)<br>    current_timestamp = datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)<br>    #Insert row to Audit table with schema Job_name, Job_status, run_timestamp, files_processed, error_details<br>    rows_to_insert.append((u&quot;orders_job&quot;, u&quot;Fail&quot;, current_timestamp, -1, error_message))<br>    errors = bq_client.insert_rows(table, rows_to_insert)<br><br>    if errors == []:<br>      print(&quot;Error details inserted successfully&quot;)</pre><p>a) Successful job run : The code snippet handles audit logging. It creates a log entry into the audit table with information about the processing job, such as its status (in this case, “Pass”), the timestamp, the number of processed files, and an empty error message.</p><p>b) Unsuccessful Job run : In the event of an exception during script execution, this code block serves as the error-handling mechanism. It prepares a row of error details into the audit table, which includes the timestamp, job name, “Fail” status, and the error message.</p><p><strong><em>Once the PySpark script is ready, we are now ready to schedule the script</em></strong></p><h3>Scheduling Spark job script using Crontab Service :</h3><p><strong>Step 1</strong> : Create a bash file in the VM terminal</p><pre>$nano run_spark_job.sh</pre><p><strong>Step 2 </strong>: Write the following script and save the file :</p><pre>#!/bin/bash<br><br># Define the command for spark-submit with your desired configurations<br>spark_submit_command=&quot;/usr/local/bin/spark-submit \<br>--conf spark.jars=/path/to/gcs-connector-hadoop3-latest.jar \<br>--conf spark.hadoop.fs.gs.impl=com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem \<br>--packages com.google.cloud.spark:spark-bigquery-with-dependencies_2.12:0.21.1 \<br>/path/to/script_name.py&quot;<br><br># Run the spark-submit command<br>$spark_submit_command</pre><blockquote>The script defines a command for <strong>“spark-submit”</strong> with custom configurations. It includes necessary dependencies, such as the <strong>Google Cloud Storage connector</strong> and <strong>BigQuery package.</strong> When executed, the script runs the “spark-submit” command, triggering the PySpark job defined in <strong>gcs_to_bq.py</strong></blockquote><p>This is the same command you run in your terminal to execute the Spark job.</p><p><strong>Step 3 </strong>: Make the Script Executable. Ensure that the script has execute permissions.</p><pre>$sudo chmod +x /path/to/run_spark_job.sh</pre><p><strong>Step 4</strong> : Now, set up a crontab scheduler to run the command inside the run_spark_job.sh</p><pre>crontab -e</pre><p>Select the desired editor you work on and add the following</p><pre>*/5 * * * * /path/to/run_spark_job.sh</pre><p>Great, now the PySpark script will be executed at every 5 minutes frequency</p><p>In our architecture, we’ve also incorporated a proactive error notification system i.e Sending Email Notification that plays a vital role in maintaining the reliability and integrity of our data processing workflow.</p><h3>Sending Email Notifications:</h3><p>When errors occur during the execution of our PySpark script, our system doesn’t simply log them and move on. Instead, it takes a proactive approach by promptly notifying the relevant stakeholders. This is achieved through email notifications sent via SMTP (Simple Mail Transfer Protocol).</p><p><strong>Error Notification Setup :</strong></p><pre>try :<br>    #code logic<br>    #audit entry to Audit table after successful run with pass status<br>except exception as e :<br>    #audit entry to Audit table after unsuccessful run with fail status<br>    <br>    #setting up SMTP to send email notification with error after unsuccessful run<br>    gmail_user = &quot;test-report@xxxx.com&quot;<br>    gmail_password = &quot;app-password&quot;        #app password <br>    to_email = &quot;recipient@gmail.com&quot;       #recipient&#39;s email address<br>    <br>#you can also set multiple recipients email address or group email address <br><br>    msg = MIMEMultipart()<br>    msg[&#39;From&#39;] = gmail_user<br>    msg[&#39;To&#39;] = to_email<br>    msg[&#39;Subject&#39;] = &quot;Error Notification&quot;<br>    body = &quot;An error occurred in your Spark job: {} :\n\n{}&quot;.format(job_name,str(e))<br>    msg.attach(MIMEText(body, &#39;plain&#39;))<br><br>    try:<br>       server = smtplib.SMTP(&#39;smtp.gmail.com&#39;, 587)<br>       server.starttls()<br>       server.login(gmail_user, gmail_password)<br>       server.sendmail(gmail_user, to_email, msg.as_string())<br>       server.quit()<br>       print(&quot;Error notification sent successfully&quot;)<br>   except Exception as e:<br>       print(&quot;Error sending notification: {}&quot;.format(str(e)))</pre><p>This code handles error notification in case of script failure. If an exception occurs, it logs the error message, updates the audit table with a “Fail” status and the error details, and sends an email notification using SMTP to inform relevant personnel about the issue.</p><p>After completion of the entire setup, let’s explore the outcomes.</p><h3>Results :</h3><h4><strong>Data Ingestion into BQ</strong> :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DKwk881EGRFZVcR5" /><figcaption>BQ Result Table</figcaption></figure><p>The data from GCS is ingested into BQ table named orders</p><h4>Auditing &amp; Notification :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F9DJ3bl8iipWtkxD" /><figcaption>BQ Audit Table</figcaption></figure><p>The above image shows the Audit Entries made by spark script after <em>every 5 minutes run</em></p><p>The error occurred at 2023–10–01 07:30:30 UTC, that also means the recipient’s email address should have received an error Notification email at run_timestamp UTC + 5:30 i.e<em> 2023–10–01 1:00 PM</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlNTSR3CEHUQz-9nMLPf3w.png" /><figcaption>Email Notification</figcaption></figure><p>Here we go, we have an email notification with error message at 1:00PM</p><h3>Conclusion :</h3><p>In this blog, we’ve explored how we can schedule, notify, and log audits within the GCE i.e Google Compute Engine itself through Spark code without involving other cloud services.</p><p>We’ve also explored the art of automating data processing in the cloud. With a robust architecture, near real-time processing, and proactive error handling, we’ve unveiled the secrets to efficient data management.</p><p>If you’ve any questions/queries related to the blog, feel free to post them in the comment section or you can ping me on <a href="http://www.linkedin.com/in/tanmay-sakpal">linkedIn</a>, I’ll be happy to assist you with the queries. Your feedback is greatly appreciated!</p><p>Happy Reading!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60f73d111484" width="1" height="1" alt=""><hr><p><a href="https://blog.searce.com/streamlined-data-processing-scheduling-notification-and-auditing-with-pyspark-on-gce-60f73d111484">Streamlined Data Processing: Scheduling, Notification, and Auditing with PySpark on GCE</a> was originally published in <a href="https://blog.searce.com/">Searce</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redshift Performance & Load Testing using Apache Jmeter]]></title>
            <link>https://blog.searce.com/redshift-performance-load-testing-using-apache-jmeter-34b8be6c305a?source=rss-b35ae0f531c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/34b8be6c305a</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[jmeter]]></category>
            <category><![CDATA[redshift]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Tanmay Sakpal]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 11:07:38 GMT</pubDate>
            <atom:updated>2023-10-09T11:07:38.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*91O5CI-0OBuTN4bLjvWhHw.jpeg" /></figure><h3>Business use-case :</h3><p>For businesses which are heavily reliant on Amazon Redshift for data warehousing and analytics, scaling with business growth is crucial. However, data volume increases can lead to slower query responses, hampering timely insights. To address this, Apache JMeter comes into play. It helps identify bottlenecks, test query performance, evaluate scalability, and optimize Redshift configurations eradicating over-provision or under-provision of the resources. By fine-tuning resources and ensuring efficient query execution, businesses can make data-driven decisions faster and enhance customer experiences, all while optimizing costs.</p><h3>ABOUT JMeter</h3><p>The Apache JMeter™ application is an open-source software which is platform independent and a 100% pure Java application designed for load testing functional behaviour and measuring performance. It was originally designed for testing web applications but has since expanded to other test functions.JMeter can conduct load and performance tests for many different server types — Web — HTTP, HTTPS, SOAP, Database via JDBC etc.</p><h3>Installation of Apache Jmeter on AWS EC2 Instance :</h3><p><strong>Step 1</strong> : Configure and Create an EC2 instance with Linux/Ubuntu as Amazon Machine Image (AMI).</p><p><strong>Step 2</strong> : SSH into the EC2 instance.<br><em>Java8 or above is required for Apache JMeter because JMeter is a Java-based application</em></p><p><strong>Step 3</strong> : Use java –version or javac –version to check if java is already installed on your EC2 instance. If not, install openjdk-11-jdk using the following command:</p><pre>$sudo apt-get install openjdk-11-jdk</pre><p><strong>Step 4</strong> : Configure the JAVA_HOME Path:</p><pre>$export JAVA_HOME=/path/to/lib//java-11-openjdk-amd64/</pre><p><strong>Step 5 </strong>: Install Apache Jmeter :</p><pre>$wget https://dlcdn.apache.org//jmeter/binaries/apache-jmeter-5.6.2.tgz</pre><p><strong>Step 6 </strong>: Extract the Jmeter archive using the command :</p><pre>$tar -xf apache-jmeter-5.6.2.tgz</pre><p><strong>Step 7 </strong>: <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection.html">Download the Redshift JDBC driver</a></p><pre>$wget https://s3.amazonaws.com/redshift-downloads/drivers/jdbc/2.1.0.19/redshift-jdbc42-2.1.0.19.jar</pre><p><strong>Step 8 </strong>: Add the driver .jar file to JMeter’s /lib . When configuring the JDBC connection in the JMeter GUI, specify com.amazon.redshift.jdbc.Driver as the driver class name.</p><pre>$cp redshift-jdbc42-2.1.0.19.jar apache-jmeter-5.6.2/lib/</pre><p><strong>Step 9</strong> : Verify if the Jmeter is installed successfully</p><pre>$cd apache-jmeter-5.6.2/bin/<br>$./jmeter -v</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zdlHz5BoMYN8GRTe" /><figcaption>Fig : Jmeter Successfully installed</figcaption></figure><p>Kudos, you have successfully installed Apache Jmeter on the AWS EC2 Instance.</p><h3>Installation of TightVNC on AWS EC2 :</h3><p>Installing TightVNC on a Linux EC2 instance allows you to access the JMeter graphical user interface (GUI) remotely, making it easier to create and configure test plans visually. While the GUI provides a convenient way to create and configure test plans, CLI execution offers better scalability, automation, and resource efficiency for running tests. <br><strong><em>We will be running our test plan for Redshift using CLI and not GUI.</em></strong></p><p>Now, let’s install TightVNC Server on EC2, configure it, and use it for remote desktop connections.</p><p><strong>Step 1</strong> : If your firewall for EC2 instance is enabled, you need to open ports for incoming VNC connections. For a single connection, simply open port 5901. If you require multiple concurrent connections, use ports like 5902, 5903, and so on.</p><p><strong>Step 2</strong> : Install TightVNC server</p><pre>$sudo apt install xfce4 xfce4-goodies tightvncserver</pre><p><strong>Step 3</strong> : Start the TightVNC Server for the first time. It will create the files necessary for work and ask to create a password.</p><pre>$vncserver</pre><p>Set a password and confirm it. To restrict remote desktop control, opt for a read-only password.</p><p><strong>Step 4</strong> : Stop your TightVNC session to adjust other settings</p><pre>$vncserver -kill :1</pre><p><strong>Step 5</strong> : Open the TightVNC config file</p><pre>$nano ~/.vnc/xstartup</pre><p>Add the following line to the end of script</p><blockquote>startxfce4</blockquote><p><strong>Step 6</strong> : Start the server again</p><pre>$vncserver</pre><p><strong>Step 7</strong> : Connecting to a Remote Desktop.</p><p>Start any VNC client, you can use RealVNC or TightVNC Viewer. Use the Public IP address of your EC2 instance with port 5901 to connect remotely to the linux EC2 instance.</p><p>[Your_EC2_Public_IP]:5901<br>Enter your previously created password to access the remote desktop.</p><blockquote>Once you have connected to Linux EC2 instance using remote desktop(RealVNC) Start JMeter by running the jmeter executable in the bin directory. <br>Open the terminal in the remote desktop and navigate to <br><strong>cd /root/apache-jmeter-5.6.2/bin</strong><br>And run <br><strong>./jmeter.sh</strong></blockquote><h4><strong><em>Apache JMeter GUI will get launched</em></strong></h4><h3>Configuration of Jmeter Test Plan to do Load &amp; Performance Testing on the Redshift Cluster:</h3><p><strong>Step 1</strong> : Create a New Test Plan</p><p>a) Click on “File” &gt; “New” to create a new test plan.</p><p>b) Give your test plan a meaningful name by right-clicking on the “Test Plan” in the tree view on the left and selecting “Add” &gt; “Threads (Users)” &gt; “Thread Group.”</p><p>c)In the Thread Group panel, you can configure the number of threads (virtual users), ramp-up period, and loop count based on your load testing requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D2BzR26G9MFa40OV" /><figcaption>Thread Group</figcaption></figure><blockquote><strong>Number of Threads (users)</strong> — the number of virtual users that simultaneously execute the given test case. Here, we are testing with 100 threads.<br><strong>Ramp-up Period</strong> — the period (in seconds) that tells JMeter how long it takes to start the full number of threads chosen. For example, here with 100 threads and 10 seconds ramp-up period, each second 10 threads will start execution.<br> <strong>Loop Count </strong>— the number of times each user would execute the test.</blockquote><p><strong>Step 2</strong> : Add Sampler for Database Requests</p><p>a) Right-click on your Thread Group, select “Add” &gt; “Sampler,” and choose “JDBC Request.”</p><p>b) Configure the JDBC Connection Configuration by right-clicking on your Test Plan, selecting “Add” &gt; “Config Element,” and choosing “JDBC Connection Configuration.” Here, you’ll need to provide the necessary database connection details for your Amazon Redshift instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9aGGkZ2TZHq16RGMT7YPQ.png" /><figcaption>JDBC Connection Configuration</figcaption></figure><blockquote><strong>Database URL</strong>: Enter the JDBC URL for your Redshift Database Cluster. <br><strong>JDBC</strong> <strong>Driver Class </strong>: Use com.amazon.redshift.jdbc.Driver as the driver class.<br><strong>Username </strong>: Input the username of your Redshift database for the connection. <strong>Password :</strong> Enter the password corresponding to the provided username.</blockquote><p><strong>Step 3</strong> : Configure JDBC Request: Go back to the JDBC Request sampler you added earlier. In the “JDBC Request” panel, proceed to configure the following.</p><p>a) Variable Name Bound to Pool: Give the same name you have given in Variable Name for created pool in the above image ref (<em>JDBC Connection Configuration</em>).</p><p>b) SQL Query: Enter your SQL query to test Redshift. For example, you can execute a simple query like “SELECT * FROM your_table.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AN1bBV0EVQ-WXtEb" /><figcaption>JDBC Request Sampler</figcaption></figure><p><strong>Step 4</strong> : Add Listeners for Reporting</p><p>a) To view the test results, add listeners by right-clicking on your Thread Group, selecting “Add” &gt; “Listener,” and choosing the desired listener(s). Common listeners include “View Results Tree,” “Summary Report,” and “Graph Results.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yINOppApf06XY-gx" /><figcaption>Listeners for Reporting</figcaption></figure><p><strong>Step 5</strong> : Save the Test Plan as and give the Test Plan file a name : Here I have given RedshiftLoadTest.jmx (jmx is an extension of Apache Jmeter). The .jmx file gets saved in the bin folder by default.</p><p><strong>Step 6</strong> : SSH into your EC2 instance terminal and navigate to bin directory</p><pre>$cd apache-jmeter-5.6.2/bin/</pre><p><strong>Step</strong> <strong>7</strong> : Run the .jmx file saved using following command</p><pre>$./jmeter.sh -n -t RedshiftLoadTest.jmx </pre><p>Remember to carefully configure your test plan based on your specific Redshift workload and performance testing objectives.</p><p><strong><em>Additionally, ensure that your JMeter EC2 instance has network access to your Redshift cluster, and you’ve configured the JDBC driver correctly in JMeter.</em></strong></p><h3>Results of Load &amp; Performance testing of Redshift Cluster :</h3><p>After running the .jxm file we get the below as the result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ce-TUVy_TbDChebI" /><figcaption>Results</figcaption></figure><p>We are running 100 threads with a ramp-up period of 10 seconds. That means every 1 second 10 threads will start executing.<br><strong>a)</strong> The above image indicates that during the test, 100 requests were sent, and they were processed in 10 seconds. The average throughput was 10 requests per second.<br><strong>b)</strong> The average response time in milliseconds was 91ms.<br><strong>c) </strong>The minimum response time observed was 70 ms.<br><strong>d)</strong> The maximum response time 543 ms.<br><strong>e)</strong> Err represents the number of error requests and the percentage of error requests. Here, all the 100 requests were successfully sent to the Redshift database.</p><p>Now, let’s also take a look at the results of performance &amp; load testing of Redshift Cluster.</p><h3>Redshift Performance Metrics :</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VdMiDCyWBKJfLaCb" /><figcaption>Redshift Cluster CPU Utiliization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*16aqWCHnta8v6CUS" /><figcaption>Database Connections</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s2Lw4JdiJQEt9IYe" /><figcaption>Query Throughput Metrics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eut6dlrJeeQ9nWyI" /><figcaption>Query Duration Metrics</figcaption></figure><p>We can monitor &amp; Analyze the CPU Utilization, Database Connections, Query Throughput, Query Duration and many more metrics regarding the Redshift cluster.</p><p><strong>Based on the above Redshift metrics result business can take decisions regarding Redshift</strong> :</p><ul><li>Through load and performance testing with JMeter, the business can optimize Redshift’s query performance, ensuring reports are generated quickly, which aids in faster decision-making.</li><li>The business can confidently scale Redshift to accommodate growing data without concerns about performance degradation.</li><li>Cost savings by optimizing Redshift resources based on actual usage patterns. Depending upon the Performance of load testing Business can over-provision or under-provision the Redshift resources.</li></ul><h3>Conclusion :</h3><p>In conclusion, Apache JMeter plays a crucial role in ensuring the performance, scalability, and reliability of Amazon Redshift, which is essential for data-driven decision-making in a business that relies on data warehousing and analytics. <br>While we’ve explored this use case with Amazon’s Redshift, Apache Jmeter can seamlessly extend to other databases and data warehouses such as Google’s BigQuery, Teradata, Snowflake, Oracle and more, making it a valuable asset for testing and fine-tuning.</p><p>If you’ve any questions/queries related to the blog, feel free to post them in the comment section or you can ping me on <a href="http://www.linkedin.com/in/tanmay-sakpal">linkedIn</a>, I’ll be happy to assist you with the queries. Your feedback is greatly appreciated!</p><p>Happy Reading!!!</p><h3>References :</h3><ul><li><a href="https://jmeter.apache.org/">Apache JMeter™</a></li><li><a href="https://aws.amazon.com/blogs/big-data/building-high-quality-benchmark-tests-for-amazon-redshift-using-apache-jmeter/">Building high-quality benchmark tests for Amazon Redshift using Apache JMeter | Amazon Web Services</a></li><li><a href="https://docs.aws.amazon.com/redshift/latest/mgmt/jdbc20-download-driver.html">Download the Amazon Redshift JDBC driver, version 2.1</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34b8be6c305a" width="1" height="1" alt=""><hr><p><a href="https://blog.searce.com/redshift-performance-load-testing-using-apache-jmeter-34b8be6c305a">Redshift Performance &amp; Load Testing using Apache Jmeter</a> was originally published in <a href="https://blog.searce.com/">Searce</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL to BigQuery CDC with Dynamic Column and Table Addition]]></title>
            <link>https://blog.searce.com/postgresql-to-bigquery-cdc-with-dynamic-column-and-table-addition-a98add9a7f96?source=rss-b35ae0f531c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a98add9a7f96</guid>
            <category><![CDATA[dataflow]]></category>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Tanmay Sakpal]]></dc:creator>
            <pubDate>Fri, 14 Oct 2022 09:50:12 GMT</pubDate>
            <atom:updated>2022-10-14T09:50:12.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2OD-e8YbAfJMh2eAvvxsA.png" /></figure><p>New technologies such as on-demand advanced analytics, machine learning, AI, Natural Language Processing are on the rise and data plays a vital role in empowering these technologies. This has created the need for serverless computing power, cost-effective storage and performance that scales with your business. And this is the reason why modern data warehouses like Google’s BigQuery, Snowflake, Amazon’s Redshift are preferred over traditional databases such as PostgreSQL, MySQL, SQL Server, as they provide on-demand advanced analytics processing capabilities.</p><p><strong>Business Case:<br></strong>In this blog, we will see how the data can be migrated from PostgreSQL to BigQuery in real-time using Debezium, Pub/Sub and Dataflow.<br>It also covers handling of the dynamic schema whenever the PostgreSQL table schema gets updated; dynamic addition of tables is also included in the solution.<br>Currently, Google Cloud native services don’t support PostgreSQL to BigQuery in real-time, hence a custom solution has been developed.</p><h3>Cloud Services Deployed:</h3><ul><li><strong>Debezium</strong> : Debezium is an open source distributed platform for change data capture (CDC). You just need to start it up, point it at your databases, and your apps can start responding to all of the inserts, updates, and deletes that other apps commit to your databases.</li><li><strong>Pub/Sub</strong> : Google Cloud Pub/Sub is a messaging service that allows apps and services to share event data. Publisher applications can send messages to a “topic” and other applications can subscribe to that topic to receive the messages.</li><li><strong>Dataflow</strong> : Google Cloud Dataflow is a Unified stream and batch data processing that’s serverless, fast, and cost-effective. It is a fully managed data processing service based on Apache Beam.</li></ul><h3>Scenario 1 :</h3><h3>Prerequisites :</h3><ul><li><a href="https://hevodata.com/blog/postgresql-cdc/"><strong>PostgreSQL</strong></a><strong> </strong>with enabled change data capture.</li><li><strong>Debezium Server</strong> for capturing data change from PostgreSQL database.</li><li><strong>BigQuery Table</strong> to which CDC workload is to be ingested.</li><li><strong>PubSub Topic</strong> with subscription named in the following pattern for all tables as :<br>&lt;&lt;db_name.schema.all&gt;&gt;</li><li><strong>Debezium Server compliant Pub/Sub Topic</strong> attached to the above Topic</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cMZqBs_YEdAEGrv-" /><figcaption><em>Technical Architecture</em></figcaption></figure><p>Alright let’s start and get to the implementation of the same:</p><h3>Debezium Server Configuration :</h3><ul><li>Download and install the Debezium Server.</li><li>Configure the source database,sink and applicable transformations within the configuration file placed at: /conf/application.properties file.</li><li>The configuration file with CloudSQL — PostgreSQL database as the source and Google Cloud PubSub as messaging infrastructure will look like this:</li></ul><pre>debezium.sink.type=pubsub<br>debezium.sink.pubsub.project.id=storied-parser-350704<br>debezium.source.connector.class=io.debezium.connector.postgresql.PostgresConnector<br>debezium.source.offset.storage.file.filename=/root/piyush/offsets.dat<br>debezium.source.offset.flush.interval.ms=0<br>debezium.source.database.hostname=35.225.64.133<br>debezium.source.database.port=5432<br>debezium.source.database.user=searce_test<br>debezium.source.database.password=searce@123<br>debezium.source.database.dbname=kuldeep_db<br>debezium.source.plugin.name=wal2json<br>debezium.source.database.server.name=kuldeep_db<br>debezium.sink.pravega.scope=empty<br>debezium.source.schema.include.list=public<br>debezium.snapshots.new.table=parallel<br>debezium.source.database.history.file.filename=/tmp/FileDatabaseHistory.dat<br>debezium.source.database.history=io.debezium.relational.history.FileDatabaseHistory<br>debezium.source.plugin.name=pgoutput<br>debezium.transforms=Reroute<br>debezium.transforms.Reroute.type=io.debezium.transforms.ByLogicalTableRouter<br>debezium.transforms.Reroute.topic.regex=(.*)public(.*)<br>debezium.transforms.Reroute.topic.replacement=$1public.all</pre><ul><li>Debezium.source.connector.class : The name of this PostgreSQL connector class.</li><li>Debezium.source.schema.include.list : An optional, comma-separated list of regular expressions that match names of schemas for which you want to capture changes.</li><li>Debezium.source.plugin.name : The name of the PostgreSQL <a href="https://debezium.io/documentation/reference/stable/connectors/postgresql.html#postgresql-output-plugin">logical decoding plug-in</a> installed on the PostgreSQL server.</li><li>debezium.transforms.Reroute.topic.regex : Specifies a regex that the transformation applies to each change event record to determine if it should be routed to an appropriate topic.</li><li>debezium.transforms.Reroute.topic.replacement : Specifies a regex that denotes the destination topic name. The transformation routes each matching record to the topic identified by this regex.</li></ul><p><strong>Initiate</strong> the Debezium Server.</p><pre><strong>&lt;&lt;Debezium_Server_Path/run.sh&gt;&gt;</strong></pre><h3>Sample message from Debezium :</h3><pre>{“schema”:{“type”:”struct”,”fields”:[{“type”:”struct”,”fields”:[{“type”:”int32&quot;,”optional”:false,”field”:”id”},{“type”:”string”,”optional”:true,”field”:”name”},{“type”:”int32&quot;,”optional”:true,”field”:”city_id”},{“type”:”int64&quot;,”optional”:true,”name”:”io.debezium.time.MicroTimestamp”,”version”:1,”default”:0,”field”:”created”},{“type”:”int32&quot;,”optional”:true,”name”:”io.debezium.time.Date”,”version”:1,”field”:”the_date”},{“type”:”int64&quot;,”optional”:true,”name”:”io.debezium.time.MicroTime”,”version”:1,”field”:”time_without”},{“type”:”string”,”optional”:true,”name”:”io.debezium.time.ZonedTime”,”version”:1,”field”:”time_with”},{“type”:”string”,”optional”:true,”name”:”io.debezium.time.ZonedTimestamp”,”version”:1,”default”:”1970–01–01T00:00:00Z”,”field”:”modified”},{“type”:”string”,”optional”:true,”field”:”school”}],”optional”:true,”name”:”kuldeep_db.public.all.Value”,”field”:”before”},{“type”:”struct”,”fields”:[{“type”:”int32&quot;,”optional”:false,”field”:”id”},{“type”:”string”,”optional”:true,”field”:”name”},{“type”:”int32&quot;,”optional”:true,”field”:”city_id”},{“type”:”int64&quot;,”optional”:true,”name”:”io.debezium.time.MicroTimestamp”,”version”:1,”default”:0,”field”:”created”},{“type”:”int32&quot;,”optional”:true,”name”:”io.debezium.time.Date”,”version”:1,”field”:”the_date”},{“type”:”int64&quot;,”optional”:true,”name”:”io.debezium.time.MicroTime”,”version”:1,”field”:”time_without”},{“type”:”string”,”optional”:true,”name”:”io.debezium.time.ZonedTime”,”version”:1,”field”:”time_with”},{“type”:”string”,”optional”:true,”name”:”io.debezium.time.ZonedTimestamp”,”version”:1,”default”:”1970–01–01T00:00:00Z”,”field”:”modified”},{“type”:”string”,”optional”:true,”field”:”school”}],”optional”:true,”name”:”kuldeep_db.public.all.Value”,”field”:”after”},{“type”:”struct”,”fields”:[{“type”:”string”,”optional”:false,”field”:”version”},{“type”:”string”,”optional”:false,”field”:”connector”},{“type”:”string”,”optional”:false,”field”:”name”},{“type”:”int64&quot;,”optional”:false,”field”:”ts_ms”},{“type”:”string”,”optional”:true,”name”:”io.debezium.data.Enum”,”version”:1,”parameters”:{“allowed”:”true,last,false”},”default”:”false”,”field”:”snapshot”},{“type”:”string”,”optional”:false,”field”:”db”},{“type”:”string”,”optional”:true,”field”:”sequence”},{“type”:”string”,”optional”:false,”field”:”schema”},{“type”:”string”,”optional”:false,”field”:”table”},{“type”:”int64&quot;,”optional”:true,”field”:”txId”},{“type”:”int64&quot;,”optional”:true,”field”:”lsn”},{“type”:”int64&quot;,”optional”:true,”field”:”xmin”}],”optional”:false,”name”:”io.debezium.connector.postgresql.Source”,”field”:”source”},{“type”:”string”,”optional”:false,”field”:”op”},{“type”:”int64&quot;,”optional”:true,”field”:”ts_ms”},{“type”:”struct”,”fields”:[{“type”:”string”,”optional”:false,”field”:”id”},{“type”:”int64&quot;,”optional”:false,”field”:”total_order”},{“type”:”int64&quot;,”optional”:false,”field”:”data_collection_order”}],”optional”:true,”field”:”transaction”}],”optional”:false,”name”:”kuldeep_db.public.all.Envelope”},<strong>”payload”</strong>:{“before”:null,<strong>”after”:{“id”:30001,”name”:”Tanmay”,”city_id”:111,”created”:1659980659369251,”the_date”:19212,”time_without”:63859369251,”time_with”:”12:14:19.369251Z”,”modified”:”2022–08–08T12:14:19.369251Z”,”school”:”Pune”}</strong>,”source”:{“version”:”1.6.0.Final”,”connector”:”postgresql”,”name”:”kuldeep_db”,”ts_ms”:1659960859369,”snapshot”:”false”,<strong>”db”:”kuldeep_db”</strong>,”sequence”:”[\”2944693384\”,\”2944693384\”]”,”schema”:”public”,<strong>”table”:”tanmay_table”</strong>,”txId”:4651958,”lsn”:2944695392,”xmin”:null},<strong>”op”:”c”</strong>,”ts_ms”:1659960859746,”transaction”:null}}</pre><ol><li>In this sample message received from Debezium at Pub/Sub end, [‘payload’][‘after’] is the only subsequent message we require to ingest into BigQuery.</li><li>[‘payload’][‘source’][‘name’] key consists of the source database name.</li><li>[‘payload’][‘source’][‘table’] key consists of the table name of the source table.</li><li>[‘payload’][‘source’][‘op’] key consists of operations performed.<br> i) Insert : When you add a record you receive Pub/Sub message with “op” : “c”<br> ii) Update : When you update a record you receive Pub/Sub message with “op” : “u”<br> iii) Delete : When you delete a record you receive Pub/Sub message with “op” : “d”</li></ol><h3>Dataflow :</h3><ul><li>Now, as we received messages from Pub/Sub we will be running a streaming Dataflow job to migrate data from Pub/Sub to BigQuery and also be handling schema change and new table addition in Dataflow code.</li><li>Dataflow Design looks like:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NFpPITB6nMdL_pig" /><figcaption>Dataflow Diagram</figcaption></figure><h3>Code Snippets :</h3><ol><li>First we’ll read the message from Pub/Sub.</li></ol><pre>with beam.Pipeline(options=pipeline_options) as pipeline:<br>      realtime_data=(<br>              pipeline<br>              |&quot;ReadFromPubSub&quot;&gt;&gt; beam.io.gcp.pubsub.ReadFromPubSub(subscription=options.input_subscription1, with_attributes=True)<br>)</pre><p>2. Pass the Pub/Sub message through Beam.ParDo Clean message function to urge payload data consisting of required data as record and add table name as column to classify tables accordingly.</p><pre>class CleanDataForBQ(beam.DoFn):</pre><pre>def process(self, pubsub_message):<br>        attributes = dict(pubsub_message.attributes)<br>        data = json.loads(pubsub_message.data.decode(“utf-8”))</pre><pre># To ingest the messages to BQ, filter the messages according to the table name<br>        data[‘payload’][‘after’][‘table_name’]=data[‘payload’]<br>[‘source’][‘table’]</pre><pre># We need to use datetime library for handling the epoch integer values and convert them to timestamp,date and time format<br>        for i in range(len(data[‘schema’][‘fields’][1][‘fields’])):<br>           name=data[‘schema’][‘fields’][1][‘fields’]  [i].get(‘name’,None)<br>           if(name==’io.debezium.time.MicroTimestamp’ and data[‘schema’][‘fields’][1][‘fields’][i][‘type’]==’int64&#39;):<br>             key=data[‘schema’][‘fields’][1][‘fields’][i][‘field’]<br>             value=data[‘payload’][‘after’][key]<br>             if(value!=None):<br>                new_value=<br>                    datetime.datetime.fromtimestamp(value/1000000.0)<br>                data[‘payload’][‘after’][key]=str(new_value)</pre><pre>if(name==’io.debezium.time.Date’ and data[‘schema’][‘fields’][1][‘fields’][i][‘type’]==’int32&#39;):<br>             key=data[‘schema’][‘fields’][1][‘fields’][i][‘field’]<br>             value=data[‘payload’][‘after’][key]<br>             if(value!=None):<br>                new_date = datetime.datetime(1970,1,1,0,0) +     datetime.timedelta(value)<br>                new_value=new_date.strftime(“%Y-%m-%d”)<br>                data[‘payload’][‘after’][key]=str(new_value)</pre><pre>if(name==’io.debezium.time.MicroTime’ and data[‘schema’][‘fields’][1][‘fields’][i][‘type’]==’int64&#39;):<br>             key=data[‘schema’][‘fields’][1][‘fields’][i][‘field’]<br>             value=data[‘payload’][‘after’][key]<br>             if(value!=None):<br>                new_time=(datetime.datetime.fromtimestamp(value/1000000.0))<br>                new_value = new_time.strftime(“%X.%f”)<br>                data[‘payload’][‘after’][key]=str(new_value)</pre><pre>yield (data[‘payload’][‘after’])</pre><p>3. Write the successful records into BigQuery :</p><pre>from google.cloud import BigQuery<br>client = BigQuery.Client()<br>dataset_id = ‘stream’</pre><pre>table_ref = client.dataset(dataset_id).table(data[‘payload’]  [‘after’][‘table_name’])<br>table_id = client.get_table(table_ref)</pre><pre># insert record data into BigQuery<br>er=client.insert_rows(table_id, [data[‘payload’][‘after’]])</pre><h3>BUT!</h3><blockquote><strong>If the Pub/Sub message accommodates new fields which are not present in BigQuery Schema we would get failed records.</strong></blockquote><p>So, we will be using <a href="https://pypi.org/project/bigquery-schema-generator/"><strong><em>BigQuery Schema Generator</em></strong></a><strong><em> </em></strong>library to generate new schema for additional columns by comparing already existing BigQuery schema and payload data i.e Pub/Sub message fetched in real-time from Pub/Sub topic. Once the new schema is generated we will try to re-insert the failed records again into BigQuery. You can read more about this <a href="https://medium.com/inside-league/streaming-data-to-bigquery-with-dataflow-and-real-time-schema-updating-c7a3deba3bad">here</a>.</p><p>4. Generating new schema and re-inserting the records failed due to the schema changes.</p><pre>from BigQuery_schema_generator.generate_schema import SchemaGenerator, read_existing_schema_from_file<br>from google.cloud import BigQuery</pre><pre>generator = SchemaGenerator(input_format=’dict’, quoted_values_are_strings=True)</pre><pre># Get original schema to assist the deduce_schema function.<br># If the table doesn’t exist<br># proceed with empty original_schema_map<br>   try:<br>       table_file_name = f”original_schema_{data[‘payload’][‘after’][‘table_name’]}.json”<br>       table = client.get_table(table_ref)<br>       client.schema_to_json(table.schema, table_file_name)<br>       original_schema_map=<br>                     read_existing_schema_from_file(table_file_name)<br>   except Exception:<br>       logging.info(f”{table_ref} table not exists. Proceed without getting schema”)<br>        original_schema_map = {}</pre><pre># generate the new schema<br>   schema_map, error_logs = generator.deduce_schema(<br>    input_data=[data[‘payload’][‘after’]],<br>    schema_map=original_schema_map)<br>   schema = generator.flatten_schema(schema_map)</pre><pre>job_config = BigQuery.LoadJobConfig(<br>       source_format=BigQuery.SourceFormat.NEWLINE_DELIMITED_JSON,<br># schema_update_options updates the schema in BigQuery table<br>       schema_update_options=[<br>                 BigQuery.SchemaUpdateOption.ALLOW_FIELD_ADDITION],<br># passing the new schema generated<br>       write_disposition=BigQuery.WriteDisposition.WRITE_APPEND,<br>       schema=schema<br>       )</pre><pre>try:<br>           load_job = client.load_table_from_json(<br>           [data[‘payload’][‘after’]],<br>           table_id,<br>           job_config=job_config,<br>           ) # Make an API request.</pre><pre>print(load_job)<br>           load_job.result() # Waits for the job to complete.</pre><p>Now, what if new tables get added into the PostgreSQL database?</p><p>The dataflow code will throw an error stating that the table <strong>NOT_FOUND</strong> in the dataset in the BigQuery.</p><p>In such a scenario, we will be catching this error in the exception block and we will be creating the table along with the schema by using the <em>Schema Generator library</em>. After creating the table, we will be inserting the records into the table.</p><p>5. Creating a new table in the BigQuery when the table gets added to PostgreSQL database.</p><pre>except Exception as error:</pre><pre>table = BigQuery.Table(table_ref, schema=schema)<br>    table = client.create_table(table)<br>    #print(‘table created’)<br>    table_id = client.get_table(table_ref)<br>    load_job = client.load_table_from_json(<br>         [data[‘payload’][‘after’]],<br>         table_id,<br>         job_config=job_config,<br>         ) # Make an API request.</pre><pre>print(load_job)<br>    load_job.result()</pre><p>Run the dataflow code :</p><pre>$ PostgresqlToBq_realtime.py — project &lt;”project-id”&gt; — region &lt;region&gt; — runner DataflowRunner — requirements_file &lt;file location&gt;</pre><p>Also, create a requirement text file for BigQuery schema generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZSme_m7bLEKpGCRG" /><figcaption>requirements file</figcaption></figure><p>The dataflow code is written in the GCP provided editor. You can also run the code on your local machine or VM and install the required dependencies.</p><ul><li>After implementing the dataflow code and running the streaming job dataflow graph looks like:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C9XNuyycaZGQ1nzA" /><figcaption>Dataflow graph</figcaption></figure><p>And here we go we have the CDC data in tabular format in BigQuery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V3rFCTtzOY6jzMJe" /><figcaption>Result</figcaption></figure><p>The pipeline will stream real-time data from PostgreSQL to BigQuery, and can handle the table schema change and replicate the identical table schema in BigQuery as of PostgreSQ table.</p><h3>Scenario 2 :</h3><h3>Now, what if there are a fixed number of tables whose data needs to be migrated to BigQuery in real-time?</h3><blockquote><strong>For this, we can use a static approach in which we pre-define the topics in Pub/Sub and create tables in BigQuery for those tables.</strong></blockquote><p>For this approach, we need to make small changes in application.properties file in Debezium as follows:</p><ol><li>Replace debezium.source.table.include.list =public TO debezium.source.table.include.list=public.table1,public.table2,public.table3</li><li>Create the PubSub Topic with subscription in the following pattern for every table as: &lt;&lt;db_name.schema.table_name&gt;&gt; and remove the transform and re-route parameters from application.properties file.</li></ol><p>In this approach, particular table data will first flow into to its subsequent topic created in Pub/Sub and then Dataflow will</p><ol><li>Read the data from Pub/Sub subscription.</li><li>Clean message function i.e ParDO function will clean and extract the data required to insert into BigQuery.</li><li>Write successful records into the subsequent BigQuery Table.</li><li>If there are failed records due to schema change, we will use the window function to create a batch window of 1 minute for all the failed records.</li><li>By using the Schema-Generator API library we will create a new schema of BigQuery Table and re-insert the batch failed records again into BigQuery.</li></ol><h3>Dataflow:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*XAaTVbZm9LN_Rh84" /><figcaption>Dataflow Diagram</figcaption></figure><ul><li>After implementing the dataflow code and running the streaming job dataflow graph looks like:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*w68yDHsTVJenf8G5" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/0*aISGc1p6N2Vo9EPi" /><figcaption>Dataflow Graph</figcaption></figure><p>The static approach i.e multiple Pub/Sub topics to multiple BigQuery tables is one of the approaches developed initially to migrate data from PostgreSQL to BigQuery in real-time. But the dynamic approach i.e single Pub/Sub topic to multiple BigQuery tables discussed initially is a more robust and resilient approach to migrate data from PostgreSQL to BigQuery in real-time.</p><h3>Challenges :</h3><ol><li>Timestamp without time zone, date and time without time zone data types need to be handled in the dataflow code as they get converted into integers (epoch values) in BigQuery.<br>In the dataflow code above, this challenge has been handled.</li><li>The solution works for a single database, implementing for multiple databases is a challenge.</li></ol><h3>Conclusion :</h3><p>In this blog, we have explored how to migrate data from PostgreSQL to BigQuery using Debezium, Pub/Sub and Dataflow. The solution also includes handling schema changes using BigQuery Schema Generator and dynamic table addition.</p><p>I would like to give special thanks to <a href="https://medium.com/u/e2308397371d">Piyush Bajaj</a> for his contribution in designing and implementing the above solution and motivating me to write this blog.</p><p>Thank you so much for reading this blog, Happy Reading!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a98add9a7f96" width="1" height="1" alt=""><hr><p><a href="https://blog.searce.com/postgresql-to-bigquery-cdc-with-dynamic-column-and-table-addition-a98add9a7f96">PostgreSQL to BigQuery CDC with Dynamic Column and Table Addition</a> was originally published in <a href="https://blog.searce.com/">Searce</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>