<?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 Rares Istoc on Medium]]></title>
        <description><![CDATA[Stories by Rares Istoc on Medium]]></description>
        <link>https://medium.com/@ristoc?source=rss-c0f99073ae3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LgkzVrhrf53i8F7Bh_QHyg.jpeg</url>
            <title>Stories by Rares Istoc on Medium</title>
            <link>https://medium.com/@ristoc?source=rss-c0f99073ae3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:58:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ristoc/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[Deploy Smarter, Not Harder: How Genezio simplifies fast, scalable deployment for ML teams]]></title>
            <link>https://medium.com/ml-vanguards/deploy-smarter-not-harder-how-genezio-simplifies-fast-scalable-deployment-for-ml-teams-e3c1e0a18ba4?source=rss-c0f99073ae3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c1e0a18ba4</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Rares Istoc]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 05:30:15 GMT</pubDate>
            <atom:updated>2025-02-03T09:55:19.825Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Genezio makes deployment easy, fast, and ready for the real world</h4><pre>                   [ START: TABLE OF CONTENTS ]<br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ 1. What is Genezio?                   │<br>         └────────────────────────────────────────┘<br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ 2. How client collaboration drives     |<br>         |     successful AI projects             │<br>         └────────────────────────────────────────┘<br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ 3. The Struggle with Infrastructure   │<br>         │    for ML Teams                       │<br>         └────────────────────────────────────────┘<br>               |-- (a) Common infrastructure challenges for ML teams<br>               └-- (b) How out-of-the-box platforms address these challenges<br><br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ 4. How to Deploy a RAG System with    │<br>         |   Genezio:: A Step-by-Step Guide      │<br>         └────────────────────────────────────────┘<br>               |-- (a) An advanced RAG architecture: Indexing, Retrieval,<br>                       Synthesizer<br>               |-- (b) Step-by-step guide to setting up RAG on Genezio<br>               <br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ 5. Real-World Scenario                │<br>         └────────────────────────────────────────┘<br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ 6. Conclusion: Focus on Building,     │<br>         │    Not Infrastructure                 │<br>         └────────────────────────────────────────┘</pre><h4>Article overview:</h4><blockquote>This article explores the challenges machine learning (ML) teams face when deploying client-facing proofs-of-concept (PoCs). It showcases how <a href="https://genezio.com/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a>, a function-as-a-service (FaaS) platform, provides a seamless solution.</blockquote><blockquote>Focusing on the specific needs of outsourcing and iterative client feedback, the article highlights the importance of reusable infrastructure to streamline deployment workflows and reduce inefficiencies.</blockquote><p>Key takeaways include:</p><ul><li><strong>The role of client collaboration:</strong> How small feedback loops and interactive PoCs foster better alignment between development teams and client expectations.</li><li><strong>Challenges with Infrastructure:</strong> Many ML teams struggle with infrastructure management due to a lack of in-house DevOps expertise, resulting in delays and inefficiencies.</li><li><a href="https://genezio.com/"><strong>Genezio</strong></a><strong>’s simplified deployment model:</strong> An introduction to <strong>Genezio</strong>’s core features and how it empowers teams to deploy ready-to-use RAG (Retrieval-Augmented Generation) infrastructure quickly and effortlessly.</li><li><strong>Step-by-step guidance for RAG deployment:</strong> A practical guide to setting up a RAG system with <a href="https://genezio.com/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a>, showcasing its speed, simplicity, and effectiveness.</li><li><strong>Real-world benefits:</strong> Examples of how <a href="https://genezio.com/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a> accelerates client feedback cycles, reduces costs, and allows teams to focus on building innovative products instead of managing infrastructure.</li></ul><p>Whether you’re an <strong>ML engineer</strong>, a <strong>DevOps professional</strong>, or a <strong>Project Manager</strong> looking to improve collaboration with clients, this article will provide insights and a clear understanding of how <strong>Genezio</strong> can transform your deployment workflow.</p><h3><strong>1. What is Genezio?</strong></h3><p><a href="https://genezio.com/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a> is a cutting-edge <strong>Function-as-a-Service (FaaS)</strong> platform designed to simplify and accelerate the deployment of applications and proof-of-concepts.</p><p>Similar to platforms like AWS Lambda, <a href="https://genezio.com/blog/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a> focuses on reducing the complexity associated with infrastructure management, allowing development teams to focus on building innovative solutions.</p><p>Unlike traditional deployment methods that often require extensive DevOps expertise, <a href="https://genezio.com/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a> enables teams to deploy code with minimal setup, ensuring faster turnaround times and seamless scalability.</p><p>It provides an intuitive interface for deploying functions and applications directly to the cloud, making it particularly valuable for machine learning teams and small development groups without dedicated cloud engineers.</p><blockquote>👇👇👇</blockquote><blockquote><strong>Check out </strong>🔗 <a href="https://genezio.com/blog/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio’s blog</strong></a><strong> for hands-on examples and implementation guides to dive deeper.</strong></blockquote><h3>2. How client collaboration drives successful AI projects</h3><p>In the dynamic world of AI outsourcing, <strong>small feedback loops are no longer optional — they’re essential.</strong></p><p>AI can often feel like a black box to clients. They’re investing significant resources, but uncertainty can grow without clear visibility into progress or outcomes.</p><p><strong>Regular, iterative updates</strong> keep clients informed and build trust by showing tangible results and alignment with their goals.</p><p>These feedback loops foster collaboration, enabling teams to:</p><ul><li>Address potential issues early before they snowball into more significant problems.</li><li>Ensure the deliverables align with client expectations every step of the way.</li><li>Demonstrate continuous progress, reinforcing the value of their investment.</li></ul><p>By involving clients in this way, you improve satisfaction and save time and effort by catching misalignments early — delivering a better product faster.</p><p>Establishing a reusable initial infrastructure for proofs-of-concept is invaluable to streamlining this process.</p><p>Clients increasingly expect to interact with proof-of-concepts, such as a functional version hosted under a URL.</p><p>This requirement can leave ML teams struggling with infrastructure configuration and deployment tasks outside their expertise.</p><p>After hours spent researching and setting up the necessary environment, they might still contact a friend or colleague experienced in this area for help. This inefficiency detracts from the team’s primary focus and delays project delivery.</p><p><a href="https://genezio.com/blog/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a> transforms the deployment process. As a cutting-edge function-as-a-service (FaaS) platform similar to AWS Lambda, it simplifies infrastructure management, allowing development teams to focus on innovation.</p><p>By eliminating technical complexities, <strong>Genezio</strong> enables seamless deployment of proofs-of-concept, letting clients interact with them in real time.</p><p>Moreover, <strong>Genezio</strong> lets you test your setup locally before cloud deployment, ensuring your infrastructure works as intended. This feature saves valuable time by catching potential issues early, streamlining the deployment process and reducing post-deployment debugging.</p><h3><strong>3. The Struggle with Infrastructure for ML Teams</strong></h3><p>Managing infrastructure is crucial for machine learning (ML) teams to showcase products to clients effectively. A well-configured setup allows clients to visualize progress. It ensures that development teams can focus on their primary work — building innovative products — rather than reinventing the wheel for every project.</p><p>However, many ML teams face significant challenges due to a lack of in-house cloud engineering or DevOps expertise. These challenges include:</p><h4>Common infrastructure challenges for ML teams</h4><ul><li><strong>Lack of expertise</strong>: Teams without dedicated cloud engineers struggle with configuring and maintaining infrastructure.</li><li><strong>Custom complexity</strong>: Complex, project-specific infrastructures require continuous updates and fine-tuning.</li><li><strong>Inefficient resource allocation</strong>: Time spent on infrastructure reduces focus on core ML development.</li></ul><h4>How out-of-the-box platforms address these challenges</h4><p>Many ML teams are adopting easy-to-use platforms like <strong>Genezio</strong> that simplify infrastructure management. These platforms offer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*6BvJumigjIg96xHmIiY0Ow.jpeg" /><figcaption>Benefits of Genezio</figcaption></figure><p>By eliminating the complexities of custom infrastructure management, these solutions allow ML teams to:</p><ul><li>Focus on refining models and delivering meaningful insights.</li><li>Present work in accessible, client-friendly formats.</li><li>Accelerate delivery timelines without compromising quality.</li></ul><p>This shift enhances productivity and ensures that ML teams can prioritize innovation over operational hurdles. Tools like <strong>Genezio</strong> empower teams to achieve more with less effort, transforming infrastructure management into a seamless and scalable process.</p><h3><strong>4. </strong>How to Deploy a RAG System with Genezio: A Step-by-Step Guide</h3><p>Deploying a Retrieval-Augmented Generation (RAG) system is no walk in the park. It often involves:</p><ul><li><strong>Dockerizing your application</strong> to ensure portability.</li><li><strong>Writing Infrastructure as Code (IaC)</strong> to manage cloud resources.</li><li><strong>Handling cloud configurations</strong>, from networking to storage, which can quickly become overwhelming.</li></ul><p>These complexities slow down iterations and stretch client feedback loops, making it hard to demonstrate progress and align with expectations.</p><p>This is where <strong>Genezio</strong> steps in. By simplifying deployment, <strong>Genezio</strong> eliminates these pain points, taking you from <strong>PoC to production-ready RAG infrastructure in record time</strong> — all without needing deep DevOps expertise.</p><p>In the next section, we’ll discuss an advanced RAG architecture and provide a step-by-step guide to setting up your RAG system with <strong>Genezio</strong> so you can experience the speed, simplicity, and effectiveness for yourself.</p><blockquote>🫵🫵🫵</blockquote><blockquote><strong>Explore the complete code and examples for deploying a RAG system on Genezio in </strong>🔗 <a href="https://github.com/mlrefinery/deploy-hybrid-rag-genezio"><strong>deploy-hybrid-rag-genezio</strong></a><strong> Github.</strong></blockquote><h4>4.1 An advanced RAG architecture: Indexing, Retrieval, Synthesizer</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15wuv291ccjapm9OCah09Q.jpeg" /><figcaption>Advanced Hybrid Rag Architecture</figcaption></figure><p>A well-designed Retrieval-Augmented Generation (RAG) architecture is the backbone of production-ready AI systems, ensuring efficient processing, accurate retrieval, and seamless information synthesis.</p><p>Let’s break down the key components of an advanced RAG pipeline:</p><h4>Indexing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fO2s7pD_VwFPjCCM1LRLpA.png" /></figure><p>The QdrantIndexer class is designed to index documents using various embedding models and store them in a Qdrant database.</p><p>Multiple embeddings are used in the indexing process:</p><h4>Dense Embeddings</h4><ul><li><strong>Purpose</strong>: Captures semantic similarity in a compact vector space.</li><li><strong>Use case</strong>: Ideal for queries focused on meaning rather than exact terms.</li><li><strong>Model</strong>: sentence-transformers/all-MiniLM-L6-v2</li></ul><h4>Sparse Embeddings</h4><ul><li><strong>Purpose</strong>: Encodes text with high weights for rare, significant terms.</li><li><strong>Use case</strong>: Effective for keyword-based retrieval or technical queries.</li><li><strong>Model</strong>: Qdrant/bm42-all-minilm-l6-v2-attentions</li></ul><h4>Matryoshka Embeddings</h4><ul><li><strong>Purpose</strong>: Provides multi-scale embeddings for varying levels of granularity.</li><li><strong>Use case</strong>: Enables precise or broad retrieval depending on context.</li><li><strong>Feature</strong>: Balances between specific and generalized search.</li></ul><h4>Late Interaction Embeddings (ColBERT)</h4><ul><li><strong>Purpose</strong>: Focuses on fine-grained token-level interactions during retrieval.</li><li><strong>Use case</strong>: Optimized for late-stage re-ranking, enhancing retrieval accuracy.</li><li><strong>Model</strong>: colbert-ir/colbertv2.0</li></ul><h4>Why Combine Them?</h4><p>Using dense, sparse, Matryoshka, and late interaction embeddings ensures:</p><ul><li><strong>Dense</strong> for semantic context.</li><li><strong>Sparse</strong> for keyword precision.</li><li><strong>Matryoshka</strong> for multi-scale relevance.</li><li><strong>ColBERT</strong> for fine-grained accuracy.</li></ul><p>This hybrid approach maximizes both precision and recall, making retrieval robust and effective for diverse query intents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eqke4_umJni-KDH-aH8MRA.png" /></figure><p>The first step in the process is preparing your data for efficient retrieval. Documents are:</p><p><strong>Transformed</strong> into nodes: Breaking documents into smaller, manageable pieces ensures better granularity and relevance during retrieval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8wfL4ah3k_Y8hx7a1ud9w.png" /></figure><h4>Retrieval</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqwjcvQxetBtbsgT7v03xA.png" /></figure><p>When a query is submitted, the system searches across multiple embedding types to ensure robust retrieval:</p><ul><li><strong>Dense embeddings</strong> capture nuanced semantic relationships, providing contextually rich results.</li><li><strong>Sparse embeddings</strong> handle high-dimensional search needs, ensuring broader coverage.</li></ul><p>The results from both embedding models are then <strong>fused</strong> using a <strong>Reciprocal Rank Fusion (RRF)</strong> strategy.</p><p>This approach combines the strengths of each embedding type, prioritizing relevance based on scores from both models. The fusion ensures that the system balances semantic understanding with exact keyword matching, providing a comprehensive and precise retrieval experience.</p><p>This hybrid search mechanism allows for robust query handling, enabling the system to return accurate and contextually relevant results to diverse user intents.</p><h4>Synthesizer</h4><p>The final stage of the pipeline is the synthesis of retrieved results into meaningful outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNavQiNwCXXALjGkTJwOVg.png" /></figure><p>The <strong>synthesizer</strong> transforms retrieved results into meaningful, query-specific outputs:</p><ol><li><strong>Context Creation</strong>: Combines retrieved documents into a structured context string.</li><li><strong>Prompt Generation</strong>: Uses a tailored template to guide the AI assistant in crafting a response, ensuring clarity and relevance.</li><li><strong>LLM Processing</strong>: Passes the prompt to a language model (e.g., GPT-4o-mini) to generate a detailed response.</li><li><strong>Refinement</strong>: A response synthesizer (e.g., TreeSummarize) ensures the output is coherent and concise.</li><li><strong>Delivery</strong>: Provides actionable, query-aligned insights based on the retrieved data.</li></ol><h4>4.2 Step-by-step guide to setting up RAG on Genezio</h4><p>And here comes <strong>Genezio</strong> onto the battlefield.</p><p>In this section, We’ll demonstrate how effortlessly you can fire up a 3-tier RAG (Retrieval-Augmented Generation) architecture in no time, using their seamless platform. Below, you’ll find a diagram of the architecture, which I’ll break down and explain in detail.</p><p>For this setup, we needed a vector database. Our natural choice, considered the de-facto standard in the industry, was <strong>QDrant</strong>. While <a href="https://genezio.com/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a> currently integrates with PostgreSQL and MongoDB — excellent options that meet the needs of most solutions — we opted to stick with QDrant to maintain consistency with the RAG systems we’ve developed in the past. However, it’s worth noting that you can seamlessly integrate an external managed database with <strong>Genezio</strong>, making it adaptable to a wide range of use cases without altering the core setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDWRaEwIHK8XRgsUKuY8fw.jpeg" /><figcaption>3-Tier RAG Architecture Diagram</figcaption></figure><h4><strong>Architecture Breakdown</strong></h4><p>1. <strong>Web Client</strong>: A chat interface built with React (specifically Next.js) that receives text input from the user. This interface acts as the user-facing entry point for our system, designed for intuitive interaction and responsiveness.</p><p>2. <strong>Service Layer</strong>: The generation, indexing, and retrieval functionalities are bundled into a single FastAPI service for simplicity in this demonstration. While this approach is sufficient for a proof of concept, in more complex systems, we recommend decoupling these components. Separation is critical in environments where continuous experimentation and iteration are the norm, as it provides flexibility to evolve individual modules independently.</p><p>3. <strong>Vector Database</strong>: The backbone of the system, storing the vectors produced during the indexing process. This component ensures efficient retrieval of relevant data to support accurate and context-aware generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2jcFE8ybLnG0z4kgYsEIw.png" /></figure><p>The <strong>genezio.yaml</strong> file is a critical component for deploying your project to the <strong>Genezio</strong> Cloud.</p><p>The genezio.yaml configuration file acts as a blueprint, simplifying the deployment process by instructing <strong>Genezio</strong> on how to provision and manage the necessary infrastructure for your project. This file defines key resources, including:\n</p><ul><li><strong>Databases</strong>: Configure PostgreSQL, MongoDB, or external vector databases like QDrant.</li><li><strong>Authentication services</strong>: Implement secure user management and access control.</li><li><strong>Deployed functions</strong>: Deploy backend services with minimal setup.</li><li><strong>Frontend hosting</strong>: Streamline deployment for client-facing applications.</li></ul><p>Key Benefits of Using the genezio.yaml File:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*mbgWHz091wm_7CU-3ib-bQ.jpeg" /><figcaption>Benefits of Using genezio.yaml File</figcaption></figure><p>By leveraging <strong>Genezio</strong>&#39;s modularity, each major component of your system is deployed as a single function on the platform. Combined with <strong>Genezio</strong>’s <strong>out-of-the-box elastic scaling</strong>, the system can seamlessly adapt to fluctuating user demands, whether you’re experiencing a surge in interactions or testing new features.</p><p>This robust, scalable architecture empowers teams to focus on building and innovating rather than being bogged down by infrastructure complexities. With <strong>Genezio</strong>, you can accelerate development from concept to production while maintaining a clean and maintainable system architecture.</p><p>Down below are all the steps required to spin up this infrastructure:</p><ol><li><strong>Install Genezion CLI</strong></li></ol><pre>npm install -g genezio</pre><p><strong>2. Test on local</strong></p><p>This will start an local development environment, similar to sam local, for those who played with AWS Lambda.</p><pre>genezio local</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imxbDsXOJ96_PZV3-EJGlw.png" /><figcaption>Local Deployment of Infrastructure</figcaption></figure><p><strong>3. Deploy on Cloud</strong></p><pre>genezio deploy</pre><p>And here you have it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smAf3D0ggpZ5F2Gm2fzKgw.jpeg" /><figcaption>RAG Retrieval Q&amp;A</figcaption></figure><p>Your application will be hosted on a custom subdomain, such as <a href="https://your-app-name.app.genez.io./">https://your-app-name.app.genez.io.</a> From the <strong>Genezio</strong> dashboard, you can seamlessly manage, test, update, and monitor your project, ensuring smooth operation and effortless maintenance.</p><p>As you can see, this is simplicity at its finest. With just a straightforward configuration and a few commands, you’re ready to deploy and use your application. Gone are the days of wrestling with complicated infrastructure setups — no need to manage intricate network configurations, security groups, CDNs, or lengthy and convoluted Infrastructure-as-Code (IaC) files.</p><p><strong>Genezio</strong>’s approach eliminates these hurdles, allowing you to focus entirely on building and refining your application. This streamlined process saves valuable development time and significantly reduces your team&#39;s cognitive load, letting you allocate resources to innovation rather than infrastructure headaches. It’s a game-changer for teams that value speed, simplicity, and scalability.</p><h3>5. Real-World Scenario</h3><p>One of the most exciting ways to use <strong>Genezio</strong>’s RAG deployment is by creating a <strong>Knowledge Intelligence Search Tool</strong> — a smart system that helps organizations turn piles of internal or public data into a powerful, easy-to-use knowledge base.</p><p>Companies generate a great amount of information every day — things like internal documents, training manuals, reports, customer support tickets, and emails. But all that data is usually spread across different systems, making it a headache for employees to find what they need, when they need it. And let’s be honest, traditional keyword searches often miss the mark because they can’t really “get” the context behind what you’re asking.</p><p>That’s where <a href="https://genezio.com/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai"><strong>Genezio</strong></a> comes in. It lets companies build a smart search tool powered by <strong>semantic search</strong>. The result? Employees can ask questions in plain, everyday language and get accurate, context-aware answers that actually make sense for what they’re looking for. No more wasted time digging through endless files.</p><h4><strong>Benefits</strong></h4><ul><li><strong>Efficiency</strong>: Saves employees hours by quickly surfacing the information they need, reducing manual search efforts.</li><li><strong>Improved decision-making</strong>: Provides decision-makers with timely and accurate insights to support strategic planning.</li><li><strong>Scalability</strong>: Easily scales with the organization as new data sources are added, ensuring long-term utility.</li></ul><h3><strong>6. Conclusion: Focus on Building, Not Infrastructure</strong></h3><p>If you’re looking to simplify deployments, accelerate your development process, and reduce the complexities of infrastructure management,</p><p><strong>Genezio</strong> is the ideal Function-as-a-Service (FaaS) platform for you. Designed with engineering teams, <strong>Genezio</strong> enables rapid deployment of proofs-of-concept, scalable applications, and advanced RAG (Retrieval-Augmented Generation) systems with ease.</p><blockquote>🫵🫵🫵</blockquote><blockquote><strong>Ready to get started?</strong><br>Explore the 🔗 <a href="https://github.com/mlrefinery/deploy-hybrid-rag-genezio">deploy-hybrid-rag-genezio</a> repository to access code samples, configuration files, and step-by-step guides to help you hit the ground running. Discover how <strong>Genezio</strong>’s features can transform your development workflow and simplify your deployments.</blockquote><p>↓↓↓</p><p><a href="https://genezio.com/?utm_source=substack&amp;utm_medium=newsletter&amp;utm_campaign=cube-python-ai">Genezio</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c1e0a18ba4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml-vanguards/deploy-smarter-not-harder-how-genezio-simplifies-fast-scalable-deployment-for-ml-teams-e3c1e0a18ba4">Deploy Smarter, Not Harder: How Genezio simplifies fast, scalable deployment for ML teams</a> was originally published in <a href="https://medium.com/ml-vanguards">Hyperplane</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Crawl your way into Market Dominance]]></title>
            <link>https://medium.com/ml-vanguards/how-to-crawl-your-way-into-market-dominance-f42d47399332?source=rss-c0f99073ae3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f42d47399332</guid>
            <dc:creator><![CDATA[Rares Istoc]]></dc:creator>
            <pubDate>Fri, 27 Dec 2024 18:24:11 GMT</pubDate>
            <atom:updated>2024-12-27T18:24:11.747Z</atom:updated>
            <content:encoded><![CDATA[<h4>A highly scalable Data Ingestion Pipeline for ML in Market Intelligence</h4><pre>                  [ START: TABLE OF CONTENTS ]<br>                               |<br>                               v <br>         ┌────────────────────────────────────────┐<br>         │ 1. Business Strategy Revolves Around  │<br>         │    Data                               │<br>         └────────────────────────────────────────┘<br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ 2. Gathering Relevant Data Points     │<br>         └────────────────────────────────────────┘<br>               |-- 2.1 Architecture Overview<br>               |-- 2.2 Scheduler<br>               └-- 2.3 Crawler<br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ 3. Challenges &amp; Pitfalls              │<br>         └────────────────────────────────────────┘<br>               |-- 3.1 Running Headless Browser Instance <br>                   with Selenium in Lambda Runtime Environment<br>               |-- 3.2 Aggregate Empty Pages<br>               └-- 3.3 Avoid Being Blocked by Social Media Platforms<br>                               |<br>                               v<br>         ┌────────────────────────────────────────┐<br>         │ Conclusion                             │<br>         └────────────────────────────────────────┘</pre><h4>Article overview:</h4><blockquote>This article outlines an end-to-end solution of a highly scalable data-ingestion pipeline tailored to a specific area: <strong>marketing intelligence</strong>. This architecture caters to various analytical processes: sales, competitor analysis, market analysis, and customer insights to name a few.</blockquote><blockquote>The use case explored in the article is focused around crawling major social media platforms and storing the posts for a later in-depth analysis with LLMs.</blockquote><p>Key takeaways include:</p><ul><li><strong>Scalable Data Ingestion</strong>: Event-driven architecture with AWS Lambda, EventBridge, and CloudWatch for high concurrency and monitoring.</li><li><strong>Optimized Crawling</strong>: Modular design using a dispatcher for dynamic crawler selection; integrates Selenium, Instaloader, and LangChain.</li><li><strong>Anti-Bot Solutions</strong>: Proxies mask IPs and bypass restrictions like rate limiting and IP blocking.</li><li><strong>Reliable Data</strong>: Prevents duplicates and aggregates posts for advanced LLM-based insights.</li><li><strong>Flexibility &amp; Scalability</strong>: Easily add new crawlers and domains; centralized logic ensures maintainability.</li><li><strong>Market Intelligence</strong>: End-to-end pipeline enables in-depth social media analysis for strategic insights.</li></ul><p>You can access the full solution code on 🔗 <a href="https://github.com/mlvanguards/data-ingestion-crawlers-pipeline"><strong>GitHub</strong></a>.</p><h4>Why do so many AI projects feel like déjà vu?</h4><p>You start with bold ambitions, tackle a proof of concept, and… it stalls. Again.</p><p>At <a href="https://mlvanguards.substack.com/"><strong>ML Vanguards</strong></a>, we know this story all too well. It’s the cycle we’ve broken countless times in our work at <a href="https://www.cube-digital.io/"><strong>Cube Digital</strong></a>.</p><p>The truth? Building production-grade AI isn’t about chasing buzzwords — it’s about combining <strong>engineering knowledge</strong> with <strong>practical AI </strong>to deliver <strong>systems</strong> that actually work, scale, and drive real-world impact.</p><h3>1. Business Strategy Revolves Around Data</h3><p>There is no surprise that data is power. The stock market is data, the consumers’ behavior is data, even clicks on buttons are relevant from a business perspective.</p><p>There is an awful need for automated solutions to streamline social media data collection and analysis. Knowing what your users want and actually use from your business is the key to decision making and strategy.</p><h3>2. Gathering Relevant Data Points</h3><h4>2.1 Architecture Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNK3BpZ02OOWIYxVmyahTw.png" /><figcaption>Event-Driven &amp; Highly Scalable Architecture for Data Ingestion Pipeline</figcaption></figure><h4>Components Overview</h4><p><strong>Scheduler: </strong>Plays multiple roles, despite its name, but the most important one is to trigger the crawler lambdas for each page link it has.</p><p><strong>Crawler: </strong>The name states its purpose. If you’re not familiar with the term crawling, pause this article and look it over before proceeding. This component takes the page link and starts crawling/extracting various posts and information about them. More details will come in the implementation part.</p><p><strong>Database: </strong>Most posts are unstructured textual data, but we can extract other useful information from them, and MongoDB shines at handling semi-structured data.</p><p>To mark the complete flow of the solution, the scheduler triggers a crawler lambda instance for each page, sending the page name and the link. The crawler starts extracting the posts from last week and stores the raw content, the post’s creation date, the link itself, and the name, but this doesn’t stop here. You can extract more information depending on what the platform offers you.</p><p>Then, the scheduler waits for all lambda instances to finish their execution, aggregates the extracted posts from the database, and, using some prompt templates, sends the posts along with these to ChatGPT to generate some reports.</p><h4>Tools &amp; Libraries</h4><ul><li><strong>Selenium</strong>: Web browser automation tool. This is used by one of the crawling libraries included in this solution.</li><li><strong>AWS Lambda</strong>: We profit from its huge fire-and-forget concurrency capabilities. The default quota is 1000 concurrent lambda functions, which can be increased to tens of thousands according to your needs.</li><li><strong>Eventbridge</strong>: Serverless EventBus helps you connect multiple applications in the AWS ecosystem; It’s used here to trigger the scheduler automatically through cron rules.</li><li><strong>CloudWatch:</strong> Log monitorization and alarm service.</li><li><strong>Instaloader: </strong>An open-source tool for extracting metadata from Instagram.</li><li><strong>Langchain:</strong> Powerful framework that allows building applications around Large Language Models.</li><li><strong>Pulumi:</strong> Infrastructure as Code (IaC) lets you write infrastructure as code in multiple languages. CDK with Terraform — but on steroids.</li></ul><h4>2.2 Scheduler</h4><p>The reporting part is not the focus, although you can find it <a href="https://github.com/mlvanguards/data-ingestion-crawlers-pipeline"><strong>here</strong></a><strong> </strong>along with all the code in this article. The leading actor here is the scheduling part itself, and this is the main entry point of the system where the whole flow is started and orchestrated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-cA42cAyHW5hJZLq_Xy3w.png" /><figcaption>Lambda Scheduler Function</figcaption></figure><p>Then, it stores the correlation ID of each lambda in a list and waits for all lambdas to finish their execution here. The awaited time defined here is 15 seconds; you can play with it according to the average time it takes for your crawler to complete its task, so Cloudwatch is not called that often.</p><p>Last, it finds all crawled posts from these pages and sends them to the report generation phase.</p><h4>2.3 Crawler</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HL6cdfGIwXMz7tjs1b4kjg.png" /><figcaption>Crawler Class Design</figcaption></figure><p>We’ve defined a main abstraction point for all types of crawlers. It defines a common interface that all derived crawlers must implement, and all subclasses must provide their implementation for the extract() method so wherever you need to build a new crawler. Besides the fact that this brings a lot of reusability and uniformity, another valuable advantage is represented down below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHcnXNHx2wYwt9jLr3MjVg.png" /><figcaption>Crawler Dispatcher Component</figcaption></figure><p>Each crawler is easily promoted and called automatically. In this case, we have a dispatcher whose job is to select and instantiate the correct crawler class based on the link you’ve provided to be processed. This essentially acts as a registry and a factory for the crawler and manages these under the unified interface and structure we’ve created for them. The advantages?</p><ul><li><strong>Flexibility &amp; Scalability: </strong>This component unlocks the possibility of easy addition without modifying the existing codebase. This makes the system easily expandable; you can include more domains and specialized crawlers — just plug and play them.</li><li><strong>Encapsulation &amp; Modularity: </strong>The dispatcher encapsulates the logic for determining which crawler to use based on the link. This makes the system more modular and allows each crawler to focus on its core business logic without worrying about pattern matching.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xf1PmUBBFhrX1gSc3Z9ciQ.png" /><figcaption>Lambda Crawler Function</figcaption></figure><p>This is the main entry point, where we get the link from the event body, select the correct crawler, and start the extraction jobs. Once finished, it checks if some posts have already been added to the database so we don’t add unnecessary duplicates and then adds the posts to it.</p><h3>3. Challenges &amp; Pitfalls</h3><h4>3.1 Running headless browser instance with Selenium in Lambda runtime environment.</h4><p>The Lambda execution environment is read-only, so anything you want to write on disk should be done into a temporary file. This will mostly ruin your dream of automatically installing the binary driver. So you would need to install this directly in the docker image and reference it manually in Selenium’s driver options. The only driver that worked for this setup was the Google binary driver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rvw6a3WgoeefyqIiAhlV0w.png" /><figcaption>Dockerfile</figcaption></figure><p>A crucial step in the Dockerfile is to manually download the Chrome driver and browser, then unpacked them in a location where they can be accessed by Selenium — which is usually done directly.</p><p>This is a <strong>mandatory step</strong> for the Lambda environment. Since everything is read-only, this is how to point Selenium to the correct driver and browser locations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGQEM8LmWcvtRSd4Z997gQ.png" /><figcaption>Selenium Driver Configuration</figcaption></figure><p>The driver and browser locations are hardcoded in the Dockerfile.</p><p>A few folders have been pointed to temporary directory locations, including user-data-dir, disk-cache-dir, and disk-cache-dir. These directories are automatically created by Selenium, but this has been prevented by manually setting them, as doing so could cause errors due to Lambda&#39;s disk limitations.</p><h4>3.2 Aggregate Empty Pages</h4><p>The initial monitoring algorithm was quite basic. It involved looping over the correlation IDs of each Lambda invocation and checking the database for any generated posts. However, a corner case we found where no new posts had been created for some pages within the searched time range, causing the algorithm to enter an infinite loop.</p><p>The solution devised incorporated CloudWatch logs into the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcrvxNcIT1um-vjoV0cLog.png" /><figcaption>CloudWatch Monitor Method</figcaption></figure><p>Here, all log streams for each Lambda generated on the current day are searched to locate the message, typically formatted as: REPORT RequestId: &lt;correlation_id&gt;. This message indicates that the Lambda has completed its execution, allowing the finished correlation IDs to be marked.</p><h4>3.3 Avoid Being Blocked by Social Media Platforms</h4><p>A common issue — one that could have consumed days of effort — required approaching it from a different perspective. Popular social media platforms employ numerous anti-bot protection mechanisms to prevent crawling, such as request header analysis, rate limiting, and IP blocking.</p><p>Since the browser is run in headless mode to simulate realistic user-browser interactions, and all crawlers send requests from the same IP address to multiple pages simultaneously and repeatedly, this behavior effectively signals, “Please block me.”</p><p>To mitigate this issue, we employ a proxy to mask the IP address and location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTxP0C0YVWhm1C_SBnRPJA.png" /><figcaption>Proxy Class Configuration</figcaption></figure><p>There are many good proxy solutions out there. However, we recommend you get a paid one like <a href="https://smartproxy.com/"><strong>SmartProxy</strong></a>, which offers you a pool of rotating proxy IPs to assign a different IP for each crawler.</p><p>This way, it will look just like any regular user trying to access a page from a different location.</p><p>But there’s a gotcha: many social media platforms restrict access even to public pages in many countries for users who are not logged in, so by using a proxy, you can find a country that does not implement this restriction and get IPs from it.</p><h3>Conclusion</h3><p>In this article, we’ve explored a complete end-to-end robust solution for building a Highly Scalable Data Ingestion pipeline that can leverage existing data from multiple crawlable sources for various processes like ML training, data analysis, etc.</p><p>We’ve gone through specific challenges you might face and how to overcome them in this process.</p><p>| 🔗 <em>Check out </em><a href="https://github.com/mlvanguards/data-ingestion-crawlers-pipeline"><strong><em>the code on GitHub</em></strong></a><em> and support us with a </em>⭐️</p><p>Have you <strong>enjoyed</strong> this <strong>article</strong>? Then…</p><p>If you’re ready to adopt a more practical, sustainable approach to AI — combining real-world engineering principles with effective AI strategies — subscribe to <a href="https://mlvanguards.substack.com/"><strong>ML Vanguards</strong></a> and join our community.</p><p>We’re dedicated to sharing hands-on guidance, battle-tested workflows, and insights that cut through the noise so you can build AI systems that endure.</p><p>↓↓↓</p><p><a href="https://mlvanguards.substack.com/embed">ML Vanguards | Cube Digital | Substack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f42d47399332" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml-vanguards/how-to-crawl-your-way-into-market-dominance-f42d47399332">How to Crawl your way into Market Dominance</a> was originally published in <a href="https://medium.com/ml-vanguards">Hyperplane</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Highly Scalable Data Ingestion Architecture for Machine Learning and Marketing…]]></title>
            <link>https://medium.com/decodingai/building-highly-scalable-data-ingestion-architecture-for-machine-learning-and-marketing-c65ad39f44fc?source=rss-c0f99073ae3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c65ad39f44fc</guid>
            <category><![CDATA[marketing-intelligence]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cloud-infrastructure]]></category>
            <dc:creator><![CDATA[Rares Istoc]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 06:10:37 GMT</pubDate>
            <atom:updated>2024-06-27T06:16:19.704Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Highly Scalable Data Ingestion Architecture for Machine Learning and Marketing Intelligence</h3><h4>Leveraging AWS Ecosystem and Data Crawling for Scalable and Adaptive Data Pipelines</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oATdWS65cqmhXJba" /><figcaption>Photo by <a href="https://unsplash.com/@sloppyperfectionist?utm_source=medium&amp;utm_medium=referral">Hans-Peter Gauster</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Machine learning without data is like a chef without ingredients — all the skills but nothing to cook.</p><p>These days, everything is circled around data, from the personalized ads we see online to the recommendations on our streaming services. Data drives decisions in businesses, healthcare, and even sports. Without data, our apps would be clueless, our smart devices would be dumb, and our predictions would be nothing more than guesses. In this digital age, data isn’t just the new oil; it’s the lifeblood of innovation and efficiency.</p><p><strong>Ok, but why another article about data ingestion?</strong></p><p>There are many ways to build data ingestion pipelines. With all the new toys created over the last decade, it&#39;s hard to select the best tools available to create a solution. Most of the time, the answer depends on your project&#39;s specific requirements.</p><p>In this article, you will explore an end-to-end solution tailored to a specific area: <strong>marketing intelligence</strong>. Using AWS’s integrated ecosystem of services, you can create a highly scalable data-ingestion pipeline that you can use to surf the web and crawl data, which you can plug into your various analytical processes: sales, competitor analysis, market analysis, and customer insights, you name it.</p><p>I also want to present a series of challenges I’ve encountered while building this solution. Most answers are scattered throughout the Internet, and it&#39;s hard to find a complete working solution… you can access <strong>the full solution code</strong> on <a href="https://github.com/decodingml/articles-code/tree/main/articles/ml_system_design/highly_scalable_data_ingestion_architecture_for_marketing_intelligence">GitHub</a></p><p><strong><em>IMPORTANT NOTE:</em></strong><em> Before diving into this solution, you must be aware of the legal implications of ingesting data from some data sources, like social media pages, so we can make sure nobody goes to jail. Please read the terms and conditions of each major platform; these will restrict you from crawling user profiles and private pages.</em></p><h3>Table of Contents</h3><ol><li>Architecture Overview</li><li>Implementation</li><li>Challenges &amp; Pitfalls</li><li>Local Testings</li><li>Deployment</li></ol><h3>1. Architecture Overview</h3><p>This is what we are about to build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GbvSk_XU3HAqMDidFeOcw.png" /><figcaption>[Image by the Author]</figcaption></figure><p>Here are some non-functional requirements that I’ve aimed to achieve with this architecture:</p><ul><li><strong>Scalability</strong>: I wanted this solution to simultaneously process as many pages as possible and add additional ones without care so the system can handle the amount of growth at any time.</li><li><strong>Maintainability &amp; Adaptability:</strong> I’ve designed each component of this system so that it can be easily changed and expanded without spending a lot of time on development.</li></ul><h4>Components Overview:</h4><p><strong>Scheduler: </strong>Plays multiple roles, despite its name, but the most important one is to trigger the crawler lambdas for each page link it has.</p><p><strong>Crawler: </strong>The name states its purpose. If you’re not familiar with the term crawling, pause this article and look it over before proceeding. This component takes the page link and starts crawling/extracting various posts and information about them. More details will come in the implementation part.</p><p><strong>Database: </strong>Our data lake storage instance will house these posts for later. For this, I’ve chosen MongoDB. Most posts are unstructured textual data, but we can extract other useful information from them, and Mongo shines at handling semi-structured data.</p><p>So, to mark the complete flow of our solution, the scheduler triggers a crawler lambda instance for each page, sending the page name and the link. The crawler starts extracting the posts from last week and stores the raw content, the post&#39;s creation date, the link itself, and the name, but this doesn’t stop here. You can extract more information depending on what the platform offers you.</p><p>Then, the scheduler waits for all lambda instances to finish their execution, aggregates the extracted posts from the database, and, using some prompt templates, sends the posts along with these to ChatGPT to generate some reports.</p><h4>Tools &amp; Libraries:</h4><ul><li><strong>Selenium</strong>: Web browser automation tool. I’ve not used this directly. This is used by one of the crawling libraries included in this solution.</li><li><strong>AWS Lambda</strong>: I’ll profit from its huge fire-and-forget concurrency capabilities. The default quota is 1000 concurrent lambda functions, which can be increased to tens of thousands according to your needs.</li><li><strong>Eventbridge</strong>: Serverless EventBus helps you connect multiple applications in the AWS ecosystem; I used it to trigger the scheduler automatically through cron rules.</li><li><strong>CloudWatch:</strong> Log monitorization and alarm service, we use this</li><li><strong>Instaloader: </strong>This is<strong> </strong>an open-source tool for extracting metadata from Instagram.</li><li><strong>Langchain:</strong> Powerful framework that lets you build applications around Large Language Models.</li><li><strong>Pulumi:</strong> Infrastructure as Code (IaC) lets you write infrastructure as code in multiple languages. It&#39;s basically CDK with Terraform but on steroids.</li></ul><h3>2. Implementation</h3><p>In this section, I’ll provide a detailed overview of the main components, breaking them down with code samples and explanations.</p><h4>2.1 Scheduler</h4><p>I’ll not focus so much on the reporting part, although you can find it <a href="https://github.com/decodingml/articles-code/tree/main/articles/ml_system_design/highly_scalable_data_ingestion_architecture_for_marketing_intelligence"><strong>here</strong></a> along with all the code I’ve shared in this article. The leading actor here is the scheduling part itself, and this is the main entry point of the system where the whole flow is started and orchestrated:</p><pre>import json<br>import os<br>import time<br>from datetime import datetime, timedelta<br><br>import boto3<br>from aws_lambda_powertools import Logger<br>from aws_lambda_powertools.utilities.typing import LambdaContext<br><br>from src.constants import PAGE_LINK<br>from src.db import database<br>from src.utils import monitor<br><br>logger = Logger(service=&quot;decodingml/scheduler&quot;)<br><br>_client = boto3.client(&quot;lambda&quot;)<br><br><br>def lambda_handler(event, context: LambdaContext):<br>    correlation_ids = []<br><br>    for link in PAGE_LINK:<br>        response = _client.invoke(<br>            FunctionName=&quot;lambda&quot;,<br>            InvocationType=&quot;Event&quot;,<br>            Payload=json.dumps({&quot;link&quot;: link}),<br>        )<br>        logger.info(f&quot;Triggered crawler for: {link}&quot;)<br><br>        correlation_ids.append(response[&quot;ResponseMetadata&quot;][&quot;RequestId&quot;])<br><br>    logger.info(f&quot;Monitoring: {len(correlation_ids)} crawler processes&quot;)<br><br>    while True:<br>        time.sleep(15)<br>        completed = monitor(correlation_ids)<br><br>        correlation_ids = [c for c in correlation_ids if c not in completed]<br><br>        if not correlation_ids:<br>            break<br><br>        logger.info(f&quot;Still waiting for {len(correlation_ids)} crawlers to complete&quot;)<br><br>    now = datetime.now()<br>    posts = list(<br>        database.profiles.find(<br>            {<br>                &quot;date&quot;: {&quot;$gte&quot;: (now - timedelta(days=7)), &quot;$lte&quot;: now},<br>            }<br>        )<br>    )<br><br>    logger.info(f&quot;Gathered {len(posts)} posts&quot;)<br><br>    if not posts:<br>        logger.info(&quot;Cannot generate report, no new posts available&quot;)<br>        return<br><br>    reports = generate_profiles_report(posts)<br><br>    logger.info(&quot;Generated new report!&quot;)</pre><p>As you can see, the scheduler acts as a scatterer. It iterates over a list of page links and invokes a crawler asynchronously by setting the <em>InvocationType</em> parameter to <strong>Event</strong>; this ensures that the scheduler won’t block the whole process to wait for a single page.</p><p>Then, it stores the correlation ID of each lambda in a list and waits for all lambdas to finish their execution here. I’ve defined an awaited time of 15 seconds; you can play with it according to the average time it takes for your crawler to complete its task, so you don’t call Cloudwatch that often.</p><p>Last, it finds all crawled posts from these pages and sends them to the report generation phase.</p><h4>2.2 Crawler</h4><p>Here I’ll break down the actual crawling process where you’ll see some good software practices applied so that you can easily [continue this]</p><pre>import abc<br>import os<br>from datetime import datetime, timedelta<br>from itertools import takewhile, dropwhile<br>from typing import List, Dict, Any<br><br>import instaloader<br><br>from src.crawlers.base import BaseAbstractCrawler<br><br>class BaseAbstractCrawler(abc.ABC):<br><br>    @abc.abstractmethod<br>    def extract(self, link: str, **kwargs) -&gt; None: ...<br><br><br>class InstagramCrawler(BaseAbstractCrawler):<br><br>    def __init__(self, link: str, proxy=None):<br>        self.link = link<br>        self.loader = instaloader.Instaloader()<br>        self._until = datetime.now()<br>        self._since = self._until - timedelta(days=7)<br>        self._proxy = proxy<br><br>    def extract(self, **kwargs) -&gt; List[Dict[str, str | Any]]:<br>        parsed_url = urlparse(self.link)<br><br>        if self._proxy:<br>            os.environ[&#39;https_proxy&#39;] = self._proxy.__dict__().get(&#39;http&#39;)<br>        profile = instaloader.Profile.from_username(self.loader.context, parsed_url.path.strip(&#39;/&#39;).split(&#39;/&#39;)[0])<br>        posts = takewhile(lambda p: p.date &gt; self._since, dropwhile(lambda p: p.date &gt; self._until, profile.get_posts()))<br><br>        return [<br>            {&#39;content&#39;: post.caption, &#39;date&#39;: post.date, &#39;link&#39;: self.link}<br>            for post in posts<br>        ]</pre><p>Here, I’ve defined a main abstraction point for all types of crawlers. It defines a common interface that all derived crawlers must implement, and all subclasses must provide their implementation for the extract() method so wherever you need to build a new crawler. Besides the fact that this brings me a lot of reusability and uniformity, another valuable advantage is represented down below:</p><pre>import re<br><br>from src.crawlers.base import BaseAbstractCrawler<br>from src.crawlers.instagram import InstagramCrawler<br><br><br>class CrawlerDispatcher:<br><br>    def __init__(self) -&gt; None:<br>        self._crawlers = {}<br><br>    def register(self, domain: str, crawler: type[BaseAbstractCrawler]) -&gt; None:<br>        self._crawlers[r&quot;https://(www\.)?{}.com/*&quot;.format(re.escape(domain))] = crawler<br><br>    def get_crawler(self, url: str) -&gt; BaseAbstractCrawler:<br>        for pattern, crawler in self._crawlers.items():<br>            if re.match(pattern, url):<br>                return crawler()<br>        else:<br>            raise ValueError(&quot;No crawler found for the provided link&quot;)<br><br><br>dispatcher = CrawlerDispatcher()<br>dispatcher.register(&#39;instagram&#39;, InstagramCrawler)</pre><p>I wanted to make each crawler easily promoted and called automatically. In this case, I’ve built a dispatcher whose job is to select and instantiate the correct crawler class based on the link you’ve provided to be processed. This essentially acts as a registry and a factory for my crawler and manages these under the unified interface and structure we’ve created for them. This has certain advantages, which I’ll present here:</p><ul><li><strong>Flexibility &amp; Scalability: </strong>This component unlocks the possibility for ease of addition without modifying the existing codebase. This makes the system to be easily expanded you can include more domains and specialized crawlers, just plug and play them.</li><li><strong>Encapsulation &amp; Modularity: </strong>The dispatcher encapsulates the logic for determining which crawler to use based on the link. This makes the system more modular and allows each crawler to focus on its core business logic without worrying about pattern matching.</li></ul><pre>from datetime import datetime, timedelta<br><br>from aws_lambda_powertools import Logger<br>from aws_lambda_powertools.utilities.typing import LambdaContext<br><br>from src.crawlers import dispatcher<br>from src.db import database<br><br>logger = Logger(service=&quot;decodingml/crawler&quot;)<br><br><br>def lambda_handler(event, context: LambdaContext):<br><br>    link = event.get(&#39;link&#39;)<br><br>    logger.info(f&quot;Start extracting posts for {link}&quot;)<br><br>    crawler = dispatcher.get_crawler(event.get(&#39;link&#39;))<br><br>    posts = [{**page, &#39;correlation_id&#39;: context.aws_request_id} for page in crawler.extract()]<br><br>    now = datetime.now()<br>    existing_posts = database.profiles.find({<br>        &quot;date&quot;: {&quot;$gte&quot;: (now - timedelta(days=7)), &quot;$lte&quot;: now},<br>        &quot;name&quot;: link<br>    }, projection={&#39;date&#39;: 1})<br><br>    existing_posts = [post.get(&#39;date&#39;) for post in list(existing_posts)]<br><br>    posts = [post for post in posts if post.get(&#39;date&#39;) not in existing_posts]<br><br>    if not posts:<br>        logger.info(&quot;No new posts on page&quot;)<br>        return<br><br>    logger.info(f&quot;Successfully extracted {len(posts)} posts&quot;)<br>    database.profiles.insert_many(posts)<br>    logger.info(f&quot;Successfully inserted data in db&quot;)</pre><p>Here, I’ve assembled the main entry point, where we get the link from the event body, select the correct crawler, and start the extraction jobs. Once I&#39;ve finished, I just check if some posts have already been added to the database so we don’t add unnecessary duplicates and then add the posts to it.</p><h3>3. Challenges &amp; Pitfalls</h3><h4>3.1 Running headless browser instance with selenium in lambda runtime environment.</h4><p>I think this caused me the most headaches and nightmares. The Lambda execution environment is read-only, so anything you want to write on disk should be done into a temporary file. This will mostly ruin your dream of automatically installing the binary driver. So you would need to install this directly in the docker image and reference it manually in Selenium’s driver options. The only driver I could use for this setup was the Google binary driver.</p><pre>FROM  public.ecr.aws/lambda/python:3.11 as build<br><br># Download chrome driver and browser and manually unpack them in their folders<br>RUN yum install -y unzip &amp;&amp; \<br>    curl -Lo &quot;/tmp/chromedriver-linux64.zip&quot; &quot;https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/119.0.6045.105/linux64/chromedriver-linux64.zip&quot; &amp;&amp; \<br>    curl -Lo &quot;/tmp/chrome-linux64.zip&quot; &quot;https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/119.0.6045.105/linux64/chrome-linux64.zip&quot; &amp;&amp; \<br>    unzip /tmp/chromedriver-linux64.zip -d /opt/ &amp;&amp; \<br>    unzip /tmp/chrome-linux64.zip -d /opt/<br><br><br>FROM  public.ecr.aws/lambda/python:3.11<br><br># Install the function&#39;s OS dependencies using yum<br>RUN yum install -y \<br>    atk \<br>    cups-libs \<br>    gtk3 \<br>    libXcomposite \<br>    alsa-lib \<br>    libXcursor \<br>    libXdamage \<br>    libXext \<br>    libXi \<br>    libXrandr \<br>    libXScrnSaver \<br>    libXtst \<br>    pango \<br>    at-spi2-atk \<br>    libXt \<br>    xorg-x11-server-Xvfb \<br>    xorg-x11-xauth \<br>    dbus-glib \<br>    dbus-glib-devel \<br>    nss \<br>    mesa-libgbm \<br>    ffmpeg \<br>    libxext6 \<br>    libssl-dev \<br>    libcurl4-openssl-dev \<br>    libpq-dev<br><br>COPY --from=build /opt/chrome-linux64 /opt/chrome<br>COPY --from=build /opt/chromedriver-linux64 /opt/<br><br>COPY ./pyproject.toml ./poetry.lock ./<br><br># Install Poetry, export dependencies to requirements.txt, and install dependencies<br># in the Lambda task directory, finally cleanup manifest files.<br>RUN python3 -m pip install --upgrade pip &amp;&amp; pip install poetry<br>RUN poetry export -f requirements.txt &gt; requirements.txt &amp;&amp; \<br>    pip3 install  --no-cache-dir -r requirements.txt --target &quot;${LAMBDA_TASK_ROOT}&quot; &amp;&amp; \<br>    rm requirements.txt pyproject.toml poetry.lock<br><br># Copy function code<br>COPY ./src ${LAMBDA_TASK_ROOT}/src</pre><p>The main idea in this Dockerfile is that I manually downloaded the Chrome driver and browser and unpacked them in a location where they can be accessed by Selenium, which usually would’ve done this directly.</p><p>This is a mandatory step for the Lambda environment. Since everything is read-only, in the next code sample I’ll show you how point Selenium to the correct driver and browser locations:</p><pre>from tempfile import mkdtemp<br><br>def init_driver(self):<br>    options = Options()<br>    # Setup drover binary location manually<br>    options.binary_location = &#39;/opt/chrome/chrome&#39;<br>    # Run browser in headless mode<br>    options.add_argument(&#39;--headless=new&#39;)<br>    options.add_argument(&#39;--no-sandbox&#39;)<br>    options.add_argument(&#39;--single-process&#39;)<br>    options.add_argument(&#39;--window-size=1420,1080&#39;)<br>    options.add_argument(&#39;--disable-dev-shm-usage&#39;)<br>    options.add_argument(&#39;--disable-gpu&#39;)<br>    options.add_argument(&#39;--disable-popup-blocking&#39;)<br>    options.add_argument(&#39;--disable-notifications&#39;)<br>    options.add_argument(&#39;--disable-dev-tools&#39;)<br>    options.add_argument(&#39;--log-level=3&#39;)<br>    options.add_argument(&#39;--ignore-certificate-errors&#39;)<br>    options.add_argument(&quot;--no-zygote&quot;)<br>    options.add_argument(f&quot;--user-data-dir={mkdtemp()}&quot;)<br>    options.add_argument(f&quot;--data-path={mkdtemp()}&quot;)<br>    options.add_argument(f&quot;--disk-cache-dir={mkdtemp()}&quot;)<br>    options.add_argument(&#39;--remote-debugging-port=9222&#39;)<br><br><br>    self._driver = webdriver.Chrome(<br>        service=Service(&quot;/opt/chromedriver&quot;),<br>        options=options,<br>    )</pre><p>Here I hardcode the driver and browser locations to the ones I’ve installed in Dockerfile.</p><p>You can see that I’ve also pointed a few fodlers to some temporary directory locations. I refer to user-data-dir, disk-cache-dir, and disk-cache-dir. Selenium will automatically create these directories, and I want to prevent that by manually setting them because doing so will cause errors due to Lambda&#39;s disk limitations.</p><h4>3.2 Aggregate Empty Pages</h4><p>My first monitorization algorithm was pretty basic. It looped over the correlation IDs of each lambda invocation and checked the database for generated posts, if there were any. Then, I hit a corner case where no new posts were created for some pages in the time range I searched, and the algorithm ended up in an infinite loop.</p><p>Then, I came up with an idea to bring CloudWatch logs into the game:</p><pre>import datetime<br>import re<br>from typing import List<br><br>import boto3<br><br>_client = boto3.client(&#39;logs&#39;)<br><br><br>def monitor(correlation_ids: List[str]):<br>    finished = []<br><br>    now = int((datetime.datetime.now() - datetime.timedelta(days=1)).timestamp() * 1000)<br><br>    response = _client.filter_log_events(<br>        logGroupName=&#39;/aws/lambda/crawler&#39;,<br>        startTime=now,<br>        filterPattern=&quot;REPORT RequestId&quot;<br>    )<br><br>    for event in response[&#39;events&#39;]:<br>        match = re.search(r&#39;REPORT RequestId: ([^\s]+)&#39;, event.get(&#39;message&#39;))<br>        if match:<br>            correlation_id = match.group(1)<br>            if correlation_id in correlation_ids:<br>                finished.append(correlation_id)<br><br>    return finished</pre><p>Here, I search through all log streams for each lambda generated in that current day and look for the message, which usually has this format: <strong><em>REPORT RequestId:</em></strong> &lt;correlation_id&gt;. This indicates that the lambda has reached the end of its execution, and I can mark which correlation IDs have finished.</p><h4>3.3 Avoid being blocked by social media platforms</h4><p>This was a pity error—the kind you would’ve spent days on—and the solution was to watch it from a different perspective. Popular social media platforms implement many anti-bot protection mechanisms to prevent crawling, from request header analysis to rate limiting to IP blocking.</p><p>And because we run our browser in headless mode to mimic realistic user-browser interaction, and all our crawlers send requests under the same IP address to multiple pages at the same time repeatedly, this screams, please block me.</p><p>To address this, I’ve used a proxy to mask my IP address and location:</p><pre>import os<br><br><br>class ProxyConnection:<br><br>    def __init__(<br>        self,<br>        host: str = None,<br>        port: str = None,<br>        username: str = None,<br>        password: str = None,<br>        verify_ssl: bool = False<br>    ):<br>        self.host = host or os.getenv(&#39;PROXY_HOST&#39;)<br>        self.port = port or os.getenv(&#39;PROXY_PORT&#39;)<br>        self.username = username or os.getenv(&#39;PROXY_USERNAME&#39;)<br>        self.password = password or os.getenv(&#39;PROXY_PASSWORD&#39;)<br>        self.verify_ssl = verify_ssl<br>        self._url = f&quot;{self.username}:{self.password}@{self.host}:{self.port}&quot;<br><br>    def __dict__(self):<br>        return {<br>            &#39;https&#39;: &#39;https://{}&#39;.format(self._url.replace(&quot; &quot;, &quot;&quot;)),<br>            &#39;http&#39;: &#39;http://{}&#39;.format(self._url.replace(&quot; &quot;, &quot;&quot;)),<br>            &#39;no_proxy&#39;: &#39;localhost, 127.0.0.1&#39;,<br>            &#39;verify_ssl&#39;: self.verify_ssl<br>        }</pre><p>There are many good proxy solutions out there. However, I’ll recommend you get a paid one like <a href="https://smartproxy.com/"><strong>SmartProxy</strong></a>, which offers you a pool of rotating proxy IPs to assign a different IP for each crawler.</p><p>This way, it will look just like any regular user trying to access a page from a different location.</p><p>Also, there’s a gotcha here: many social media platforms restrict access even to public pages in many countries for users who are not logged in, so by using a proxy, you can find a country that does not implement this restriction and get IPs from it.</p><h3>4. Local Testings</h3><p>To prove this works, I wrote a makefile containing some simple commands for crawler and lambda. The problem is that I’ve only managed to test the crawler locally. Since the scheduler spins up crawlers, they should be already deployed on AWS.</p><pre>local-test-crawler: # Send test command on local to test  the lambda<br> curl -X POST &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; \<br>  -d &#39;{&quot;link&quot;: &quot;https://www.instagram.com/mcdonalds&quot;}&#39;<br><br>local-test-scheduler: # Send test command on local to test  the lambda<br> curl -X POST &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; -d &#39;{}&#39;</pre><p>Now, most people, when testing lambda functions on a local environment, use AWS Lambda <strong>RIE (Runtime Interface Emulator)</strong>, which allows you to test your lambda function packages in a container. Basically, this emulates a lambda execution environment on your local machine. As you can see, I’ve managed to do this without using the emulator, which slightly simplified my environment.</p><p>You can use these commands to test each component. For example, if you would like to test the crawler, go into your terminal and use this command:</p><pre>&gt; make local-test-crawler</pre><p>As you can see, the crawling process has started, and for this page, we’ve found three new posts in the last seven days:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gc8DisemzgYuK0AbaA8yPg.png" /></figure><h3>5. Deployment</h3><p>The deployment process is defined in <a href="https://github.com/decodingml/articles-code/tree/main/articles/ml_system_design/highly_scalable_data_ingestion_architecture_for_marketing_intelligence"><strong>our GitHub</strong></a> repository under the <strong>ops</strong> folder, where you can explore the whole solution written in Pulumi.</p><p>You can play with the Makefile. It contains all the necessary commands to make your infrastructure up and running.</p><h3>Conclusion</h3><p>In this article, we’ve explored a complete end-to-end robust solution for building a Highly Scalable Data Ingestion pipeline that can leverage existing data from multiple crawlable sources for various processes like ML training, data analysis, etc.</p><p>We’ve gone through specific challenges you might face and how to overcome them in this process.</p><p>| <em>🔗 </em><strong><em>Check out</em></strong><em> </em><a href="https://github.com/decodingml/articles-code/tree/main/articles/ml_system_design/highly_scalable_data_ingestion_architecture_for_marketing_intelligence"><em>the code on GitHub</em></a><em> and support us with a </em>⭐️</p><p>I hope you’ve enjoyed this article as much as I’ve enjoyed writing it. If you did, then…</p><p>↓↓↓</p><p>Join 7.5k+ engineers in the 𝗗𝗲𝗰𝗼𝗱𝗶𝗻𝗴 𝗠𝗟 𝗡𝗲𝘄𝘀𝗹𝗲𝘁𝘁𝗲𝗿 for battle-tested content on production-grade ML. 𝗘𝘃𝗲𝗿𝘆 𝘄𝗲𝗲𝗸:</p><p><a href="https://decodingml.substack.com/">Decoding ML | Paul Iusztin | Substack</a></p><h3>References</h3><p>[1] <a href="https://www.zenrows.com/blog/stealth-web-scraping-in-python-avoid-blocking-like-a-ninja">Web Scraping in Python: Avoid Detection Like a Ninja</a></p><h3>Images</h3><p>If not otherwise stated, all images are created by the author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c65ad39f44fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decodingai/building-highly-scalable-data-ingestion-architecture-for-machine-learning-and-marketing-c65ad39f44fc">Building Highly Scalable Data Ingestion Architecture for Machine Learning and Marketing…</a> was originally published in <a href="https://medium.com/decodingai">Decoding AI Magazine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>