<?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 Alaa haggag on Medium]]></title>
        <description><![CDATA[Stories by Alaa haggag on Medium]]></description>
        <link>https://medium.com/@alaahgag34?source=rss-29c8fa55692------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AfQ_toV-qH8drHHpEG-4YQ.jpeg</url>
            <title>Stories by Alaa haggag on Medium</title>
            <link>https://medium.com/@alaahgag34?source=rss-29c8fa55692------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:34:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alaahgag34/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[Real-Time Sales Data Analysis Application: Leveraging Kafka, Spark, Airflow, and Apache superset.]]></title>
            <link>https://medium.com/@alaahgag34/real-time-sales-data-analysis-application-leveraging-kafka-spark-airflow-and-apache-superset-f7db6a31823a?source=rss-29c8fa55692------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7db6a31823a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <dc:creator><![CDATA[Alaa haggag]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 14:21:14 GMT</pubDate>
            <atom:updated>2023-11-27T22:32:40.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSy_ZwHx2I49GYxDHkWc9Q.png" /></figure><p><a href="https://github.com/alaahgag/Real-Time-Sales-Data-Analysis-Application">GitHub - alaahgag/Real-Time-Sales-Data-Analysis-Application: A real-time sales data analysis Application using Spark Structured Streaming, Kafka as a messaging system, PostgreSQL as a storage for processed data, and Superset for creating a dashboard.</a></p><h3>Introduction</h3><p>In the dynamic landscape of retail, the absence of real-time insights can be a significant hindrance to growth. This article unveils the journey of building a Real-Time Sales Data Analysis Application, a groundbreaking project designed to tackle the challenges faced by Mya Gon Yaung, a Men’s traditional clothing retail shop. The goal is simple yet transformative: to harness the power of technology, leveraging Spark Structured Streaming, Kafka, PostgreSQL, and Apache Superset, to revolutionize the way sales data is understood and utilized.</p><h3>Tech Stack</h3><ul><li>Apache Airflow</li><li>Apache Kafka</li><li>Apache Zookeeper</li><li>Apache Spark</li><li>Apache superset</li><li>PostgreSQL</li></ul><h3>The Challenge: Manual Record-Keeping Woes</h3><p>Mya Gon Yaung grapples with a manual record-keeping system, limiting its ability to understand monthly and yearly sales trends, identify top-selling products, and efficiently manage stock levels. The lack of insights has led to overstocking and understocking, significantly impacting profits. The Real-Time Sales Data Analysis Application emerges as a potential solution, aiming to answer critical questions and transform the way business operates.</p><h3>Task at Hand</h3><p>The project sets out to answer fundamental questions through real-time data analysis:</p><ul><li>What is the monthly and yearly sales performance?</li><li>Which products consistently yield the highest sales?</li><li>How can sales trends be analyzed on a monthly basis?</li><li>What stocks are running low, and when should they be replenished?</li></ul><p>The objective is clear: evaluate the efficacy of a real-time data analysis system or Point of Sales (POS) System in addressing the business challenges.</p><h3>Breaking Down the Project Files</h3><h4>1) create_db_schema.py:</h4><pre>import psycopg2<br>from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT<br><br>def create_database():<br>    &quot;&quot;&quot;<br>    - Connects to the default database.<br>    - Creates the &#39;sales&#39; database if it doesn&#39;t exist.<br>    - Returns the connection and cursor to &#39;sales&#39;.<br>    &quot;&quot;&quot;<br><br>    # Connect to the default database<br>    conn = psycopg2.connect(&quot;host=localhost dbname=postgres user=postgres password=your_password&quot;)<br>    conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)<br>    cur = conn.cursor()<br><br>    # Check if &#39;sales&#39; database exists<br>    cur.execute(&quot;SELECT 1 FROM pg_database WHERE datname=&#39;sales&#39;&quot;)<br>    exists = cur.fetchone()<br><br>    if not exists:<br>        # Create &#39;sales&#39; database with UTF8 encoding if it doesn&#39;t exist<br>        cur.execute(&quot;CREATE DATABASE sales WITH ENCODING &#39;utf8&#39; TEMPLATE template0&quot;)<br><br>    # Close the connection to the default database<br>    conn.close()<br><br>    # Connect to &#39;sales&#39; database<br>    conn = psycopg2.connect(&quot;host=localhost dbname=sales user=postgres password=your_password&quot;)<br>    cur = conn.cursor()<br><br>    return cur, conn<br><br>tables_name = [&#39;sales&#39;, &#39;stocks&#39;]<br><br>def drop_tables(cur, conn):<br>    &quot;&quot;&quot;<br>    Drops each table.<br>    &quot;&quot;&quot;<br>    for i in tables_name:<br>        cur.execute(&#39;DROP TABLE IF EXISTS {}&#39;.format(i))<br>        conn.commit()<br><br>def create_tables(cur, conn):<br>    &quot;&quot;&quot;<br>    Creates each table using predefined queries.<br>    &quot;&quot;&quot;<br>    <br>    sales_table = &quot;&quot;&quot;CREATE TABLE IF NOT EXISTS sales(<br>    Sale_ID int,<br>    Product varchar(40),<br>    Quantity_Sold int,<br>    Each_Price float,<br>    Sales float,<br>    Date date,<br>    Day int,<br>    Month int,<br>    Year int)&quot;&quot;&quot;<br><br>    stock_table = &quot;&quot;&quot;<br>    CREATE TABLE IF NOT EXISTS stocks(<br>    Product VARCHAR(40),<br>    Stock_Quantity INT,<br>    Total_Quantity_Sold INT)&quot;&quot;&quot;<br><br>    tables = [sales_table, stock_table]<br><br>    for i in tables:<br>        cur.execute(i)<br>        conn.commit()<br><br>def sales_DB_Schema():<br>    &quot;&quot;&quot;<br>    - Creates the &#39;sales&#39; database if it doesn&#39;t exist.<br>    - Establishes connection with the &#39;sales&#39; database and gets<br>      a cursor to it.<br>    - Drops all the tables.<br>    - Creates all tables needed.<br>    - Finally, closes the connection.<br>    &quot;&quot;&quot;<br>    cur, conn = create_database()<br><br>    drop_tables(cur, conn)<br>    create_tables(cur, conn)<br><br>    conn.close()<br><br>if __name__ == &quot;__main__&quot;:<br>    sales_DB_Schema()</pre><p>This Python script automates the setup of a PostgreSQL database named ‘sales.’ It connects to the default database, creates ‘sales’ manages tables (‘sales’ and ‘stocks’), and establishes their schema. The script ensures a clean database state by dropping existing tables and creating new ones, providing a streamlined process for managing the database schema.</p><h4>2) kafka_stream_dag.py:</h4><pre>from datetime import datetime, timedelta<br>from airflow import DAG<br>from airflow.operators.python import PythonOperator<br>from airflow.providers.postgres.operators.postgres import PostgresOperator<br>from data_preparation import data_prepare<br>from generate_sales_data import Generate_Data<br><br># Default arguments for the DAG<br>DAG_DEFAULT_ARGS = {<br>    &#39;owner&#39;: &#39;Your_Owner&#39;,<br>    &#39;start_date&#39;: datetime(2023, 11, 11),<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(seconds=30)<br>}<br><br># Creating the DAG with its configuration<br>with DAG(<br>    &#39;begin_the_app&#39;,<br>    default_args=DAG_DEFAULT_ARGS,<br>    schedule_interval=&#39;0 1 * * *&#39;,<br>    catchup=False,<br>    description=&#39;Stream sales data into Kafka topic&#39;,<br>    max_active_runs=1<br>) as dag:<br><br>    # Defining the data streaming task using PythonOperator<br>    Data_Preparation_Task = PythonOperator(<br>        task_id=&#39;Preparing_The_Data&#39;, <br>        python_callable=data_prepare,<br>        dag=dag<br>    )<br><br>    # Defining the data streaming task using PythonOperator<br>    Begin_Kafka_Stream_Task = PythonOperator(<br>        task_id=&#39;begin_streaming_to_kafka&#39;, <br>        python_callable=Generate_Data,<br>        dag=dag<br>    )<br><br>Data_Preparation_Task &gt;&gt; Begin_Kafka_Stream_Task</pre><p>This file primarily defines an Airflow Directed Acyclic Graph (DAG) that handles the streaming of data to a Kafka topic.</p><p><strong>a. DAG Definition:</strong></p><p>That DAG is created with the name <strong>begin_the_app</strong>, configured to run daily at <strong>1 AM</strong>. It&#39;s designed not to run for any missed intervals (with<strong>catchup=False</strong>) and allows only one active run at a time.</p><p><strong>b. Tasks</strong></p><p><strong>Data_Preparation_Task</strong> prepares the sales data by performing tasks such as data cleaning, filtering, and transformation, after that <strong>Begin_Kafka_Stream_Task</strong>begins streaming the prepared sales data to a Kafka topic.</p><h4>3) generate_sales_data.py:</h4><pre>from kafka import KafkaProducer<br>from json import dumps<br>import pandas as pd<br>import time<br>from pathlib import Path<br><br># Define Kafka topic and server configuration<br>KAFKA_TOPIC_NAME = &#39;your_kafka_topic&#39;<br>KAFKA_BOOTSTRAP_SERVERS = &#39;your_kafka_bootstrap_servers&#39;<br><br>def generate_data():<br>    # Create a Kafka producer<br>    kafka_producer = KafkaProducer(<br>        bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS,<br>        value_serializer=lambda x: dumps(x).encode(&#39;utf-8&#39;)<br>    )<br>    <br>    # Path to the CSV file containing processed sales data<br>    file_path = Path(&#39;/your/path/to/Processed_Data.csv&#39;)<br><br>    # Read the sales data from the CSV file into a DataFrame<br>    sales_df = pd.read_csv(file_path)<br><br>    # Convert the DataFrame to a list of dictionaries (one dictionary per sale)<br>    sales_list = sales_df.to_dict(orient=&#39;records&#39;)<br><br>    for sale in sales_list:<br>        # Prepare the message to be sent<br>        message = sale<br>        print(f&quot;Message to be sent: {message}&quot;)<br><br>        # Send the message to the Kafka topic<br>        kafka_producer.send(KAFKA_TOPIC_NAME, message)<br><br>        time.sleep(1)<br><br>if __name__ == &#39;__main__&#39;:<br>    generate_data()</pre><p>This code defines a function called <strong>Generate_Data()</strong> that streams sales data from a CSV file to a Kafka topic called ‘sales’. The function first creates a Kafka producer and then reads the sales data from the CSV file into a DataFrame. The DataFrame is then converted to a list of dictionaries, and each dictionary is sent to the Kafka topic as a message. The function pauses for one second between sending messages.</p><h4>4) spark_processing.py:</h4><pre>import logging<br>from pyspark.sql import SparkSession<br>from pyspark.sql.types import *<br>from pyspark.sql.functions import *<br><br>def setup_logger():<br>    &quot;&quot;&quot;<br>    Set up the logger for the application.<br><br>    This function configures the logging format and level.<br><br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br><br>    logging.basicConfig(<br>        format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;,<br>        level=logging.INFO<br>    )<br><br>def init_spark_session():<br>    &quot;&quot;&quot;<br>    Initialize a Spark session.<br><br>    This function sets up a Spark session with specific configurations.<br><br>    Returns:<br>        SparkSession: The configured Spark session.<br>    &quot;&quot;&quot;<br><br>    logger = logging.getLogger(__name__)<br>    logger.info(&quot;Setting up Spark session...&quot;)<br>    spark = SparkSession.builder \<br>        .appName(&quot;YourAppName&quot;) \<br>        .config(&quot;spark.jars.packages&quot;, &quot;org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.2,&quot;) \<br>        .config(&#39;spark.jars&#39;, &#39;file:///your/path/to/mongo-spark-connector_2.12-3.0.2.jar,&#39;) \<br>        .config(&quot;spark.driver.extraClassPath&quot;, &quot;file:///your/path/to/postgresql-42.6.0.jar&quot;) \<br>        .config(&quot;spark.executor.extraClassPath&quot;, &quot;file:///your/path/to/postgresql-42.6.0.jar&quot;) \<br>        .getOrCreate()<br><br>    spark.sparkContext.setLogLevel(&#39;ERROR&#39;)<br>    return spark<br><br>def read_kafka_data(spark, kafka_topic, kafka_bootstrap_servers):<br>    &quot;&quot;&quot;<br>    Read data from Kafka.<br><br>    Args:<br>        spark (SparkSession): The Spark session.<br>        kafka_topic (str): The Kafka topic to subscribe to.<br>        kafka_bootstrap_servers (str): The Kafka bootstrap servers.<br><br>    Returns:<br>        DataFrame: The DataFrame containing Kafka data.<br>    &quot;&quot;&quot;<br><br>    logger = logging.getLogger(__name__)<br>    logger.info(&quot;Setting up Kafka source for Structured Streaming...&quot;)<br>    <br>    sales_df = spark.readStream \<br>        .format(&quot;kafka&quot;) \<br>        .option(&quot;kafka.bootstrap.servers&quot;, kafka_bootstrap_servers) \<br>        .option(&quot;subscribe&quot;, kafka_topic) \<br>        .option(&quot;startingOffsets&quot;, &quot;latest&quot;) \<br>        .load()<br><br>    sales_df1 = sales_df.selectExpr(&#39;CAST(value AS STRING)&#39;)<br>    return sales_df1<br><br>def process_data(spark, kafka_topic, kafka_bootstrap_servers, stock_filepath, hdfs_output_path, postgres_jdbc_url, postgres_config):<br>    &quot;&quot;&quot;<br>    Process and analyze data from Kafka and external files, and write results to various sinks.<br><br>    Args:<br>        spark (SparkSession): The Spark session.<br>        kafka_topic (str): The Kafka topic to subscribe to.<br>        kafka_bootstrap_servers (str): The Kafka bootstrap servers.<br>        stock_filepath (str): The file path for the external stock data.<br>        hdfs_output_path (str): The HDFS path for storing sales data.<br>        postgres_jdbc_url (str): The JDBC URL for PostgreSQL.<br>        postgres_config (dict): Configuration parameters for PostgreSQL.<br><br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br><br>    logger = logging.getLogger(__name__)<br><br>    # Read Kafka data<br>    sales_df = read_kafka_data(spark, kafka_topic, kafka_bootstrap_servers)<br><br>    # Parse JSON data<br>    sales_schema = StructType() \<br>        .add(&#39;Sale_ID&#39;, IntegerType()) \<br>        .add(&#39;Product&#39;, StringType()) \<br>        .add(&#39;Quantity_Sold&#39;, IntegerType()) \<br>        .add(&#39;Each_Price&#39;, FloatType()) \<br>        .add(&#39;Sale_Date&#39;, TimestampType()) \<br>        .add(&#39;Sales&#39;, FloatType())<br>    <br>    sales_df = sales_df.select(from_json(col(&#39;value&#39;), sales_schema).alias(&#39;sales_data&#39;))<br>    sales_df = sales_df.select(&#39;sales_data.*&#39;)<br><br>    # Process sales data<br>    sales_df = sales_df \<br>        .withColumn(&quot;Date&quot;, to_date(col(&quot;Sale_Date&quot;), &quot;yyyy-MM-dd&quot;)) \<br>        .withColumn(&quot;Day&quot;, split(col(&quot;Date&quot;), &quot;-&quot;).getItem(2)) \<br>        .withColumn(&quot;Month&quot;, split(col(&quot;Date&quot;), &quot;-&quot;).getItem(1)) \<br>        .withColumn(&quot;Year&quot;, split(col(&quot;Date&quot;), &quot;-&quot;).getItem(0)) \<br>        .drop(&quot;Sale_Date&quot;) \<br>        .withColumn(&quot;day&quot;, col(&quot;day&quot;).cast(IntegerType())) \<br>        .withColumn(&quot;month&quot;, col(&quot;month&quot;).cast(IntegerType())) \<br>        .withColumn(&quot;year&quot;, col(&quot;year&quot;).cast(IntegerType()))<br><br>    # Read stock data<br>    stocks_df = spark.read.csv(stock_filepath, header=True, inferSchema=True)<br><br>    # Join dataframes<br>    stocks_df = stocks_df \<br>        .withColumnRenamed(&quot;Quantity_Sold&quot;, &quot;Quantity_Sold_Stocks&quot;) \<br>        .join(sales_df<br>              .drop(&quot;Sale_ID&quot;)<br>              .drop(&quot;Each_Price&quot;)<br>              .drop(&quot;Sale_Date&quot;)<br>              .drop(&quot;Sales&quot;), on=&quot;Product&quot;, how=&quot;inner&quot;) \<br>        .withColumnRenamed(&quot;Quantity_Sold&quot;, &quot;Quantity_Sold_Sales&quot;)<br><br>    # Group and aggregate<br>    stocks_df = stocks_df \<br>        .groupBy(&quot;Product&quot;, &quot;Stock_Quantity&quot;) \<br>        .agg({&#39;Quantity_Sold_Sales&#39;: &#39;sum&#39;}) \<br>        .select(&#39;Product&#39;, &#39;Stock_Quantity&#39;, col(&#39;sum(Quantity_Sold_Sales)&#39;).alias(&#39;Total_Quantity_Sold&#39;))<br><br>    # Write to console<br>    query = sales_df.writeStream \<br>        .trigger(processingTime=&#39;5 seconds&#39;) \<br>        .outputMode(&#39;update&#39;) \<br>        .option(&#39;truncate&#39;, &#39;false&#39;) \<br>        .format(&#39;console&#39;) \<br>        .start()<br><br>    # Write to HDFS<br>    sales_df.writeStream \<br>        .outputMode(&#39;append&#39;) \<br>        .format(&#39;parquet&#39;) \<br>        .option(&#39;path&#39;, hdfs_output_path) \<br>        .option(&#39;checkpointLocation&#39;, &#39;/tmp/pyspark7_checkpoint&#39;) \<br>        .trigger(processingTime=&#39;5 seconds&#39;) \<br>        .start()<br><br>    # Write to PostgreSQL sales table<br>    sales_df.writeStream \<br>        .trigger(processingTime=&#39;5 seconds&#39;) \<br>        .outputMode(&#39;update&#39;) \<br>        .foreachBatch(lambda df, epoch_id: df.write.jdbc(url=postgres_jdbc_url, table=&#39;sales&#39;, mode=&#39;append&#39;, properties=postgres_config)) \<br>        .start()<br><br>    # Write to PostgreSQL stocks table<br>    stocks_df.writeStream \<br>        .trigger(processingTime=&#39;5 seconds&#39;) \<br>        .outputMode(&#39;complete&#39;) \<br>        .option(&#39;truncate&#39;, &#39;true&#39;) \<br>        .foreachBatch(lambda df, epoch_id: df.write.jdbc(url=postgres_jdbc_url, table=&#39;stocks&#39;, mode=&#39;overwrite&#39;, properties=postgres_config)) \<br>        .start()<br><br>    query.awaitTermination()<br><br>def main():<br>    &quot;&quot;&quot;<br>    Main function to orchestrate the execution of the Spark Structured Streaming application.<br><br>    This function sets up the logger, initializes the Spark session, defines configuration parameters,<br>    and calls the `process_data` function to execute the ETL process.<br><br>    Returns:<br>        None<br>    &quot;&quot;&quot;<br>    <br>    setup_logger()<br>    spark = init_spark_session()<br><br>    KAFKA_TOPIC_NAME = &#39;your_kafka_topic&#39;<br>    KAFKA_BOOTSTRAP_SERVERS = &#39;your_kafka_bootstrap_servers&#39;<br>    postgres_config = {<br>        &#39;user&#39;: &#39;your_postgres_user&#39;,<br>        &#39;password&#39;: &#39;your_postgres_password&#39;,<br>        &#39;driver&#39;: &#39;org.postgresql.Driver&#39;,<br>    }<br>    postgres_jdbc_url = &#39;jdbc:postgresql://your_postgres_host:your_postgres_port/your_database_name&#39;<br>    hdfs_output_path = &quot;hdfs://your_hdfs_host:your_hdfs_port/your_hdfs_directory&quot;<br>    stock_filepath = &quot;file:///your/local/path/to/Stock_Quantity.csv&quot;<br><br>    process_data(spark, KAFKA_TOPIC_NAME, KAFKA_BOOTSTRAP_SERVERS, stock_filepath, hdfs_output_path, postgres_jdbc_url, postgres_config)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p><strong>a. Imports &amp; Logging Initialization:</strong></p><p>The necessary libraries are imported, and a logging setup is created for better debugging and monitoring.</p><p><strong>b. Spark Session Initialization:</strong></p><p><strong>init_spark_session</strong>: Initializes a Spark session, the backbone of our analytics engine. This function includes specific configurations and settings tailored to the application’s requirements.</p><p><strong>c. Data Retrieval &amp; Transformation:</strong></p><ul><li><strong>read_kafka_data</strong>: Connects to a Kafka topic, retrieves sales data in real-time, and transforms it into a structured DataFrame.</li><li><strong>process_data</strong>: Orchestrates the ETL (Extract, Transform, Load) process, seamlessly integrating data from Kafka and external sources. This function governs the entire workflow, from data processing and analysis to the final destinations.</li></ul><p><strong>d. Main Execution</strong></p><p>The <strong>main</strong> function orchestrates the entire process: initializing the Spark session, fetching data from Kafka, transforming it, and streaming it to PostgreSQL and HDFS.</p><h3>Running the Project</h3><p>To successfully run the Real-Time Sales Data Analysis Application, follow the steps outlined below.</p><h4>Prerequisites</h4><p>Ensure that you have the following prerequisites installed on your system:</p><ul><li>Apache Spark</li><li>Apache Kafka</li><li>PostgreSQL</li><li>Apache Superset</li><li>Python (3.6 or higher)</li></ul><h4>Setup and Configuration</h4><ul><li>1- Make sure that the Java version is compatible with Pyspark.</li><li>2- Clone the repository</li></ul><pre>  git clone https://github.com/alaahgag/Real-Time-Sales-Data-Analysis-Application.git</pre><ul><li>3- Navigate to the project directory</li></ul><pre>  cd Real-Time-Sales-Data-Analysis-Application</pre><ul><li>4- install the needed packages and libraries</li></ul><pre>  pip install -r ./requirements.txt</pre><h4>Launch the project:</h4><ul><li>1- Start Kafka:</li></ul><pre>  sh confg/start-zookeeper.sh<br>  sh confg/start-kafka.sh</pre><ul><li>2- Start Apache Superset:</li></ul><pre>  superset run -p 8088</pre><ul><li>3- Start Apache Superset:</li></ul><pre>  airflow db init<br>  airflow webserver<br>  airflow scheduler</pre><ul><li>4- run spark_streaming.py file:</li></ul><pre>  spark-submit spark_streaming.py</pre><ul><li>4- Invoke kafka_stream_dag.py file</li></ul><h3>General Challenges and Troubleshooting</h3><h4>1- Configuration Challenges:</h4><p>Issue: Ensuring environment variables and configurations are correctly set can be tricky. An incorrect setting might prevent services from starting or communicating.</p><p>Troubleshooting:</p><ul><li>Double-check environment variables and configurations in all scripts.</li><li>Ensure paths and file locations are correctly specified.</li></ul><h4>2- Service Dependencies:</h4><p>Issue: Services like Kafka or Airflow have dependencies on other services (e.g., Zookeeper for Kafka). Ensuring the correct order of service initialization is crucial.</p><p>Troubleshooting:</p><ul><li>Review service dependencies and start services in the correct order.</li><li>Check logs for dependency-related errors.</li></ul><h4>3- Airflow DAG Errors:</h4><p>Issue: Syntax or logical errors in the DAG file (kafka_stream_dag.py) can prevent Airflow from recognizing or executing the DAG correctly.</p><p>Troubleshooting:</p><ul><li>Thoroughly review the DAG file for syntax errors or logical issues.</li><li>Use Airflow CLI commands for DAG validation.</li></ul><h4>4- Spark Dependencies:</h4><p>Issue: Ensuring all required JARs are available and compatible is essential for Spark’s streaming job. Missing or incompatible JARs can lead to job failures.</p><p>Troubleshooting:</p><ul><li>Verify the presence and compatibility of required JAR files.</li><li>Check Spark logs for dependency-related errors.</li></ul><h4>5- Kafka Topic Management:</h4><p>Issue: Creating topics with the correct configuration (like replication factor) is essential for data durability and fault tolerance.</p><p>Troubleshooting:</p><ul><li>Use Kafka command-line tools to inspect and manage topics.</li><li>Ensure topics are created with the desired configurations.</li></ul><h4>6- Deprecation Warnings:</h4><p>Issue: The provided logs show deprecation warnings, indicating that some methods or configurations used might become obsolete in future versions.</p><p>Troubleshooting:</p><ul><li>Refer to the official documentation for the deprecated features.</li><li>Update your scripts or configurations accordingly to use recommended alternatives.</li></ul><h3>Output Dashboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-k0wVz2vzjfSIEk9loDXw.png" /></figure><h3>Conclusion</h3><p>The Real-Time Sales Data Analysis Application is a robust solution designed to address the challenges faced by Mya Gon Yaung, a traditional men’s clothing retail shop. By leveraging the power of Spark Structured Streaming, Kafka, PostgreSQL, and Apache Superset, the application provides a seamless and efficient pipeline for processing, analyzing, and visualizing sales data in real-time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7db6a31823a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>