<?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 Jiuyuanx on Medium]]></title>
        <description><![CDATA[Stories by Jiuyuanx on Medium]]></description>
        <link>https://medium.com/@jiuyuanx?source=rss-c2154cc974b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OzTQhCmCGGHnF-gTAG8-FQ.png</url>
            <title>Stories by Jiuyuanx on Medium</title>
            <link>https://medium.com/@jiuyuanx?source=rss-c2154cc974b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:42:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jiuyuanx/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[Building an AWS-Based Recommendation System: A Complete Pipeline]]></title>
            <link>https://medium.com/@jiuyuanx/building-an-aws-based-recommendation-system-a-complete-pipeline-3b0aecd05f54?source=rss-c2154cc974b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b0aecd05f54</guid>
            <category><![CDATA[aws-sagemaker]]></category>
            <category><![CDATA[aws-rds]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[aws-cloudwatch]]></category>
            <category><![CDATA[aws-mwaa]]></category>
            <dc:creator><![CDATA[Jiuyuanx]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 23:37:21 GMT</pubDate>
            <atom:updated>2024-03-27T02:38:53.933Z</atom:updated>
            <content:encoded><![CDATA[<p>In the era of personalized content and on-demand entertainment, the power of recommendation systems cannot be overstated. These intricate pieces of technology are what make platforms like Netflix, Tiktok, Amazon, and Spotify so engaging and user-friendly. Today, I will take you through the process of building a robust recommendation system using a variety of AWS services, including <strong>Kafka Streams</strong> for data ingestion, <strong>AWS RDS </strong>for data storage, <strong>SageMaker </strong>for machine learning model training and deployment, <strong>Apache Airflow </strong>for orchestration and more. This system is designed to recommend movies from 28k+ movie pool for 1M+ users based on user preferences and interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51jPExNq-dX65bQAqjXy7Q.png" /></figure><h3><strong>Data Ingestion and Storage: The Beginning</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWm2rfBMb2hGOj_idMnDhw.png" /></figure><p>The data, streaming in real-time through Kafka Streams, encompasses an overwhelming volume of 1 billion user watch behaviors, continuously recorded every two minutes during viewing sessions, alongside rating records that capture users’ evaluations of movies. The task at hand involves diligently reading each Kafka consumer message to parse and comprehend the GET request, aiming to extract pivotal information such as the user ID, movie ID, rating, and the watch length for each movie.</p><p>Here is a code for Kafka consumer reading in a target period of time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/487ee7d76eb5daf136f782ccc4a4c4cb/href">https://medium.com/media/487ee7d76eb5daf136f782ccc4a4c4cb/href</a></iframe><p>Additionally, the pipeline is designed to periodically enrich this dataset by retrieving users’ demographic information and movies’ metadata from APIs like IMDB and TMDB. This enriching process ensures that our recommendation system is not just based on user interactions but is also informed by detailed contextual data about the users and the movies themselves. Once the data is ingested, the next step is to clean and transform it to fit our needs. This involves filtering out noise, extracting features, and transforming the data into a panel format that is suitable for analysis and machine learning models.</p><p>Then the systematically organized data is stored in corresponding tables within AWS RDS — user, movie, watch, and rating tables. Here is a snippet of code to store rating data in RDS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/807e68b4a36127517a911492ff069c04/href">https://medium.com/media/807e68b4a36127517a911492ff069c04/href</a></iframe><h3><strong>Training Data Preparation: The Crucial Step</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGSltgqyghEFdFapuCnHdw.png" /></figure><p>Then let’s prepare our training dataset. Using SQL queries with AWS Relational Database Service (RDS), we can retrieve the latest 1000,000 rows from the ratings table. This dataset, representing the most recent user interactions, is vital for training a model that is both relevant and responsive to current trends. Subsequently, this data is stored as a CSV file in AWS S3, which ready to be used by SageMaker for model training.</p><p>Writing SQL to retrieve training data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8328667ba928a35a6d5921799c910e01/href">https://medium.com/media/8328667ba928a35a6d5921799c910e01/href</a></iframe><p>To augment our system’s capability and ensure it scales effectively to accommodate growing data and complexity, we compare the strengths of AWS RDS, AWS Redshift, and AWS DynamoDB. Each of these services brings unique advantages to the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GScCNi88hf4Zkif99G1naQ.png" /></figure><h4>Advantages of Using AWS RDS:</h4><ul><li><strong>Managed Service:</strong> AWS RDS automates time-consuming administrative tasks such as hardware provisioning, database setup, patching, and backups, allowing teams to focus on application development.</li><li><strong>Structured Data Integrity:</strong> Relational databases excel in maintaining structured data, ensuring that the relationships between user data, movie data, and their interactions are meticulously preserved. This integrity is crucial for accurately reflecting the dynamic nature of user preferences and movie attributes over time.</li><li><strong>Ease of Updates:</strong> The relational database model facilitates straightforward updates to user and movie information. Changes to attributes like user demographics or movie metadata can be implemented efficiently without disrupting the overall data structure, ensuring that the system remains up-to-date with minimal effort.</li></ul><h4>Advantages of Using AWS Redshift:</h4><ul><li><strong>Massive Parallel Processing (MPP)</strong>: AWS Redshift is designed for high performance on large datasets, utilizing columnar storage, data compression, and parallel query execution.</li><li><strong>Scalability:</strong> Seamlessly scales data warehouse capacity to petabytes of data, allowing for efficient data analysis and reporting.</li><li><strong>Cost-effectiveness: </strong>Offers a cost-effective solution for analyzing vast amounts of data with the option to choose between on-demand pricing or reserved instances.</li></ul><h4>Advantages of Using AWS DynamoDB:</h4><ul><li><strong>Fully Managed NoSQL Database: </strong>Offers seamless management without the overhead of operation management, such as server maintenance, setup, configuration, or replication.</li><li><strong>Performance at Scale: </strong>DynamoDB supports key-value and document data structures and is designed to deliver consistent, single-digit millisecond response times at any scale.</li><li><strong>Automatic Scaling:</strong> Features automatic scaling of throughput capacity, adapting to varying loads while maintaining performance.</li></ul><p>In evaluating AWS RDS, Redshift, and DynamoDB, we prioritize simplicity and cost by initially selecting AWS RDS for its ease of management and affordability. RDS’s managed services and scalable resources suit our project’s early stages well. However, as our needs evolve — particularly towards handling larger datasets or incorporating unstructured data — we are prepared to transition to AWS Redshift for its superior data analysis capabilities or AWS DynamoDB for its flexibility with unstructured data and scalability. This strategy allows us to start efficiently and cost-effectively while keeping our options open for scaling up and diversifying functionalities in the future.</p><p>Here is a quick view of the movie and rating tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gvAoR4fYzjv328Pu" /><figcaption>Movie Table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*70Ymufezm4zZtv3d" /><figcaption>Rating Table</figcaption></figure><h3>Model Training: The Heart of the System</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6VmNBZYox6uHNqchy72fg.png" /></figure><p>SageMaker enhances the model-building experience by offering a broad array of prebuilt machine learning models directly on its platform, such as K-NN, K-Means, PCA, Random Forest, XGBoost and various neural networks… For our recommendation system, we use specifically a collaborative filtering model — Singular Value Decomposition (SVD), which learns for movie and users feature embeddings in the same latent space through SVD Factorization of rating matrix implemented in Scikit-Surprise, a Python library designed for building and analyzing recommender systems. However SageMaker does not a have this prebuilt collaborative filtering model, so we containerize the Scikit-Surprise SVD using Docker, allowing it to be easily deployed and run in any environment that supports Docker containers. This Docker image is then stored in AWS Elastic Container Registry (ECR), trainable by SageMaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jT5o9TVdhmeG6dxR" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6110e4657121fabaccd34fb1ffb459ab/href">https://medium.com/media/6110e4657121fabaccd34fb1ffb459ab/href</a></iframe><p>Here is CLI for docker containerizing and ECR uploading:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceb9725250bc29d37b84c1e65c82a834/href">https://medium.com/media/ceb9725250bc29d37b84c1e65c82a834/href</a></iframe><p>Training the model is where AWS SageMaker shines. By creating a SageMaker training job, we utilize the previously prepared data in S3 and the Docker image in ECR to train our recommendation model. SageMaker’s robust and scalable environment is ideal for handling the complexities of machine learning model training. Upon completion, the trained model is outputted back to S3, where it can be easily accessed for deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YhsWXii4WP-oCD0e" /></figure><p>Here is a sample script for training job creation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8a90a15d136f2864d89568846a108c0/href">https://medium.com/media/b8a90a15d136f2864d89568846a108c0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOg_Aa3pSwXbkwmruSxu-A.png" /></figure><h3><strong>Orchestration and Automation: The Backbone</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J0mVMv-yS6uThFaw" /></figure><p>Apache Airflow is an open-source platform used for orchestrating complex computational workflows and data processing pipelines. Designed with the principle of “configuration as code,” it allows users to author, schedule, and monitor workflows through easy-to-read Python scripts. Airflow’s versatile design enables it to integrate seamlessly with a variety of third-party services, databases, and infrastructure components, making it a preferred choice for managing the execution of tasks that form part of a larger data-driven application.</p><p>Building on the capabilities of Apache Airflow, Amazon Web Services (AWS) offers Managed Workflow for Apache Airflow (MWAA), a managed service that simplifies the process of running Airflow on AWS. MWAA automates the provisioning, configuration, and scaling of Airflow environments, allowing users to focus on their workflows rather than the underlying infrastructure. This service integrates deeply with other AWS services, making it particularly effective for orchestrating data pipelines that leverage AWS’s storage, database, analytics, and machine learning capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ocAgKe8kfRMJTYqg" /></figure><p>To ensure our system is up-to-date and responsive to new data, we employ Managed Workflow for Apache Airflow (MWAA) to orchestrate the entire pipeline. This involves setting up a schedule to run every 6 hours (customizable based on needs), automating the process of reading data from Kafka, storing it in RDS, creating training data, and training the model with SageMaker. Additionally, metrics related to the pipeline’s performance and the model’s accuracy are logged in AWS CloudWatch, providing valuable insights for monitoring and optimization.</p><p>Here is a sample Airflow DAG code for orchestrating ETL pipeline of three python scripts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3456c17ed7fc8fd5de43e1784b4f1cb4/href">https://medium.com/media/3456c17ed7fc8fd5de43e1784b4f1cb4/href</a></iframe><p>One of the standout features of Apache Airflow is its intuitive user interface (UI), which provides a comprehensive visualization of workflows. This UI is instrumental for users to efficiently manage and monitor their data pipelines. It color-codes tasks to indicate their status: whether they have succeeded, failed, are in progress, or have yet to be executed. This immediate visual feedback is invaluable for troubleshooting, as it allows users to quickly pinpoint which parts of the pipeline are failing and require attention. Moreover, the UI provides detailed logs for each task, offering insights into the execution process and facilitating debugging.</p><p>Additionally, the Airflow UI supports manual triggers for workflows, the ability to pause and resume tasks, and the modification of schedules directly from the interface, enhancing the user’s control over their data processing activities. The combination of these features not only aids in the effective management of workflows but also significantly reduces the time and effort required to diagnose and resolve issues, ensuring smoother and more reliable pipeline operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9VqqBRzdv-c4LA_qEPTMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-R1yLYI7jmsvz1q7KrZJ8Q.png" /></figure><p>And we can monitor all the metrics in Amazon CloudWatch, especially the model performance using the query language:</p><pre>fields @timestamp, @message<br>| filter @message like /rmse=/ or @message like /mae=/<br>| parse @message &quot;rmse=*;&quot; as rmse<br>| parse @message &quot;mae=*;&quot; as mae<br>| sort @timestamp desc<br>| stats min(rmse) as RMSE, min(mae) as MAE by bin(2h)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwrrv4BMjRI5xug1xY8hbw.png" /></figure><pre>fields @timestamp, @message<br>| filter @message like /rmse=/ or @message like /mae=/<br>| parse @message &quot;rmse=*;&quot; as rmse<br>| parse @message &quot;mae=*;&quot; as mae<br>| sort @timestamp desc<br>| stats min(rmse) as RMSE, min(mae) as MAE by bin(2h)</pre><h3>Conclusion</h3><p>Building a recommendation system on AWS involves a series of intricately connected steps, from data ingestion to model training and serving recommendations. By leveraging a range of AWS services, this pipeline not only ensures scalability and reliability but also offers flexibility to adapt to different use cases and data types. Whether you’re a seasoned data scientist or an aspiring one, the journey of creating such a system offers invaluable insights into the world of machine learning and cloud computing. Through continuous optimization and learning, the potential to enhance user experiences and drive engagement is limitless.</p><h4>Strengths of the Pipeline</h4><ol><li><strong>Comprehensive Data Handling:</strong> The pipeline adeptly manages a vast quantity of data streamed in real-time, demonstrating robust capabilities in data ingestion, cleaning, and transformation. This ensures a high-quality dataset for model training and inference.</li><li><strong>Automation and Orchestration</strong>: Utilizing Managed Workflow for Apache Airflow (MWAA) for orchestration automates critical steps such as data processing, model training, and deployment. This reduces manual intervention and streamlines operations.</li></ol><h4>Limitations of the Pipeline</h4><ol><li><strong>Complexity in Management: </strong>While AWS services offer scalability and robustness, managing multiple interconnected services can become complex, especially for smaller teams or projects with limited AWS expertise.</li><li><strong>Cost Considerations:</strong> The cost of operating a sophisticated pipeline across multiple AWS services can escalate quickly. Effective cost management and optimization strategies are essential to ensure the pipeline remains economically viable.</li></ol><h4>Future Directions</h4><ol><li><strong>Incorporating Advanced ML and AI Techniques</strong>: Exploring and integrating more advanced machine learning and AI techniques, such as deep learning models for more nuanced recommendation systems, could enhance the system’s performance and personalization capabilities.</li><li><strong>Enhancing Data Privacy and Security: </strong>As data volumes and user bases grow, enhancing data privacy and security measures will become increasingly important. Future iterations could focus on implementing more robust encryption methods and privacy-preserving machine learning techniques.</li></ol><p>By addressing these limitations and exploring these future directions, the pipeline can continue to evolve, offering more sophisticated, efficient, and cost-effective solutions for real-time recommendation systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b0aecd05f54" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>