<?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 Zupee TechLab on Medium]]></title>
        <description><![CDATA[Stories by Zupee TechLab on Medium]]></description>
        <link>https://medium.com/@techlab_53748?source=rss-3bb4617bbf22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*At_FG25qADy9B7CV7lSStg.png</url>
            <title>Stories by Zupee TechLab on Medium</title>
            <link>https://medium.com/@techlab_53748?source=rss-3bb4617bbf22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:12:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@techlab_53748/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[Mastering the Art of Mocking]]></title>
            <link>https://medium.com/@techlab_53748/mastering-the-art-of-mocking-83eb913aa5df?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/83eb913aa5df</guid>
            <category><![CDATA[collaborative-development]]></category>
            <category><![CDATA[mocking-framework]]></category>
            <category><![CDATA[buildbetterfaster]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[quality-engineering]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 06:18:54 GMT</pubDate>
            <atom:updated>2025-07-15T06:18:54.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqp5XLkW3XQ2V01fwcrLTQ.png" /></figure><h4>How Zupee built Pretendo to accelerate development,Speed &amp; Collaboration</h4><p>In fast-paced development cycles, one thing slows teams down more than anything else: <strong>Dependencies</strong> <strong>!!</strong></p><p>Waiting on external APIs, half-built internal services, or flaky staging environments blocks progress across the board from feature implementation to test execution.</p><p>At Zupee, where we ship multiple feature releases every week, we knew this wasn’t sustainable. Delays caused by unavailable services were no longer an inconvenience — they were an engineering bottleneck.</p><p><strong>While mocking itself is a well-known practice, most teams use it in a limited or ad hoc fashion. At Zupee, we saw an opportunity to take it much further.</strong> We didn’t just use mocking to bypass unavailable services, we elevated it into a deliberate, platform-level strategy to decouple teams, unblock development, and scale test reliability.</p><p>This is the story of how mocking evolved from a scattered utility into a foundational pillar of our engineering culture — culminating in <strong>Pretendo</strong>, <strong><em>our in-house smart mocking platform</em></strong> built for speed, transparency, and collaboration.</p><h3>Agenda</h3><p>Here’s what this post will cover:</p><ol><li><strong>The Real Problem We’re Solving<br></strong>Understand the core challenge of external dependencies in modern development and how they slow down delivery across frontend &amp; backend development, and testing cycles.</li><li><strong>WireMock: Our First Step<br></strong>The tool that helped us scale test automation — and what it couldn’t solve as we grew.</li><li><strong>Mocking in Action: Our Multi-Layered Framework<br></strong>How Zupee uses mocking across client and backend workflows with real examples, stateful scenarios, and negative testing.</li><li><strong>From Tooling to Platform: Why We Built Pretendo<br></strong>What gaps WireMock couldn’t solve and how Pretendo emerged as a smarter, scalable mocking platform.</li><li><strong>Pretendo in Action: Collaboration, Speed &amp; Confidence<br></strong>How Pretendo helps Zupee teams ship faster by enabling shared contracts, proactive integration testing, and transparent mock management.</li><li><strong>Pretendo’s Impact<br></strong>The measurable improvements we’ve seen — in speed, reliability, and teamwork</li></ol><h3>The Real Problem</h3><p>When you’re part of a fast-moving engineering environment like Zupee, building UIs or APIs, you quickly realize this, you’re only as fast as your slowest dependency. Solving that makes all the difference.</p><blockquote>You can’t build reliably when your dependencies aren’t ready or stable.</blockquote><p>As our systems scaled, this problem became more visible across the board:</p><ul><li><strong>Flaky third-party integrations</strong> — whether it’s payment gateways, OTP services, or KYC providers — caused test failures, inconsistent behavior, and wasted engineering hours.</li><li><strong>Backend developers were blocked</strong> waiting on other services or upstream APIs that hadn’t been implemented yet.</li><li><strong>Frontend teams couldn’t move forward</strong> without mocks that matched real backend contracts.</li><li><strong>CI pipelines slowed down</strong>, test feedback loops broke, and trust in automation eroded.</li><li><strong>Integration bugs surfaced late</strong>, increasing the cost of debugging and recovery.</li></ul><p>These challenges weren’t theoretical, they showed up in our release cycles, blocked QA, delayed features, and created cross-team friction.</p><p><strong>So we had to ask:</strong></p><p><em>How can we simulate real-world interactions and system behaviour, across teams — without relying on fragile staging setups or partially built services?</em></p><p><strong>And more importantly:</strong></p><p><em>How do we ensure </em><strong><em>speed</em></strong><em>, </em><strong><em>alignment</em></strong><em>, and </em><strong><em>repeatability</em></strong><em> in Zupee’s development and test workflows?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlLwsmKu30vkvsR_LHcKQA.png" /></figure><h3>WireMock:The Engine Behind Zupee’s Early Mocking Strategy</h3><p><a href="https://wiremock.org/">WireMock</a> is an open-source HTTP service simulator used to mock and stub web APIs. It allows developers and testers to simulate real API behaviour by setting up predefined request-response mappings.</p><p>WireMock can run as a standalone server or be embedded in test suites, making it ideal for testing, debugging, and development without relying on live services.</p><p>It supports dynamic responses, request matching, delays, and stateful scenarios, helping teams build reliable and isolated tests for complex systems.</p><h3>Why WireMock Worked for Us: Zupee’s Go-To Mocking Engine (Before Pretendo)</h3><p>In the early stages of building our automation and development workflows at Zupee, we needed a dependable mocking tool to keep teams moving — not just when external APIs were down, but even when internal services were still under development or undergoing changes. That’s where <strong>WireMock</strong> came in.</p><p>While WireMock was great for testing, it had <strong>two key limitations</strong> as we scaled:</p><ol><li>It lacked a centralized user interface for cross-team visibility.</li><li>It didn’t support real-time collaboration on API contracts between frontend, backend, and QA.</li></ol><h3>Understanding Mocking: Zupee’s Perspective</h3><p>At Zupee, where rapid development meets complex, real-world integrations, our systems routinely interact with a variety of external services — from payment gateways and SMS providers to KYC and identity verification APIs.</p><p>But depending on these systems during development or testing isn’t just slow — it introduces flakiness, unpredictability, and unnecessary costs.</p><p>That’s why <strong>mocking isn’t just a convenience at Zupee — it’s a core part of how we build</strong>.</p><p>By decoupling our test and development environments from real dependencies, mocking gives our teams the control, speed, and confidence they need to ship fast and ship smart.</p><p>Here are just a few critical workflows where mocking makes a tangible difference:</p><ul><li>Test payment workflows without real money movement</li><li>Validate OTP logins without actual SMS delivery</li><li>Simulate KYC flows without hitting partner APIs</li><li>Guarantee consistency in tests, even when the real systems are down</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bVMuToN2mGInHibHJ6m4g.png" /></figure><h3>Our Approach to Mocking: A Multi-Layered Strategy</h3><p>Mocking at Zupee isn’t a one-size-fits-all solution. It’s a multi-layered architecture that spans across frontend and backend, built with flexibility and scalability in mind.</p><h4>Mocking in Client Automation (Appium/Selenium + WireMock)</h4><p>Our FE test cases rely heavily on mocking to simulate backend APIs and ensure stable end-to-end validations.</p><ol><li><strong>HTTP API Mocking with WireMock</strong></li></ol><p>We use WireMock to intercept and return stubbed responses for backend services — everything from user balances to tournament details.</p><p><strong><em>Mocking API responses allows us to simulate 200s, 400s, and even 500s without breaking a sweat and test the app’s UI behaviour.</em></strong></p><p>Rather than relying on flaky staging environments, these mocks allow frontend tests to be consistent, fast, and independent of backend readiness — improving coverage, confidence, and feedback loops.</p><p>2. <strong>Handling Negative Scenario</strong></p><p>Testing failure scenarios is critical to ensure our application behaves predictably under adverse conditions. This includes validating how the system responds to payment failures, network issues, and authentication errors.</p><p>At Zupee, we simulate such scenarios using our mocking framework based on WireMock. Below is an example where we mock a payment failure case for a specific order</p><p>One such example is <strong>payment failure testing</strong>. Using mocks, we replicate failed transaction responses — helping us validate how our system handles edge cases like insufficient balance, server errors from payment gateways, or retries after a failed attempt.</p><p>By mocking these conditions, we ensure:</p><ul><li>Consistent and repeatable failure tests</li><li>No dependency on unstable or expensive third-party sandboxes</li><li>Early discovery of handling gaps in business-critical flows</li></ul><p>By decoupling from real systems, we <strong>uncover edge cases</strong> <strong>early and</strong> <strong>prevent surprises in production.</strong></p><h3>Mocking in Backend Automation (Node.js/TypeScript + WireMock)</h3><p>Our backend test automation framework leverages WireMock to simulate third-party integrations, enabling comprehensive testing of payment flows, KYC verifications, and service interactions. At Zupee, we’ve built a robust mocking layer that powers over 1000+ test cases across our payment</p><h3>Core Infrastructure</h3><p>At Zupee, we’ve built a robust mocking framework using WireMock as our primary mocking tool. Here’s how we’ve structured it:</p><ol><li><strong>Centralized Mocking Service</strong></li></ol><pre>class WiremockHelper extends BaseHelpers {<br>      contructor(testId?: string) {<br>          super(getConfig(&quot;service&quot;).wiremockServiceUrl, testId)<br>      }<br>}</pre><p><strong>2. Mapping Configuration</strong></p><p>We maintain structured mapping files for different services:</p><ul><li>Payment Gateways (Deposit, Withdraw)</li><li>KYC Services (PAN, Aadhaar)</li><li>Communication Services (OTP, SMS)</li></ul><h3>Real-World Example: Payment Flow Testing</h3><p>Let’s look at how we test a payment deposit flow at Zupee:</p><p><strong>1. Setup Phase</strong></p><pre>// Define mock responses for payment gateway<br>await paymentHelper.defineRazorpayCreateOrderWiremock(<br>  createOrderCondition,<br>  fetchOrderCondition,<br>  fetchPaymentsCondition,<br>  serviceName.toLowerCase(),<br>  checkoutBodyData,<br>  userCheckoutData,<br>  paymentMethod.toLowerCase()<br>)</pre><p><strong>2. Transaction Flow</strong></p><pre>// Mock initial order status<br>await paymentHelper.assertInitialOrderStatus(<br>  &quot;OrderNotCreated&quot;,<br>  initialZupeeTxnStatus,<br>  initialPgTxnStatus,<br>  checkoutBodyData,<br>  userId,<br>  dbDataPayment<br>)<br><br>// Mock intermediate states<br>await paymentHelper.assertIntermediateOrderStatus(<br>  intermediateStatus,<br>  intermediateZupeeTxnStatus,<br>  intermediatePgTxnStatus.toLowerCase(),<br>  checkoutBodyData,<br>  userId,<br>  checkoutBodyData.constraintId<br>)<br><br>// Mock final success/failure<br>await paymentHelper.assertFinalOrderStatus(<br>  finalOrderStatus,<br>  finalZupeeTxnStatus,<br>  finalPgTxnStatus,<br>  checkoutBodyData,<br>  userId,<br>  checkoutBodyData.constraintId<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h0H2DLBD5ibPscDS" /></figure><h3>Pretendo: Zupee’s Leap from Tooling to Platform</h3><p>At Zupee, WireMock continues to serve as our go-to engine for backend and frontend test automation — powering robust, isolated testing across our automation suites. But as we scaled, we realized test automation was only part of the equation.</p><p>We didn’t just need mocking for tests. We needed a <strong>smart</strong> <strong>mocking platform for development</strong>.</p><p>What if…</p><ul><li>Developers could define their own mocks before the real APIs existed?</li><li>Teams shared ownership of contracts and worked off a single source of truth?</li></ul><p>That’s when we built <strong>Pretendo</strong>.</p><p><strong>Pretendo</strong> (<em>Zupee’s Internal Mocking Platform)</em> is a smart mocking layer built on top of WireMock, purpose-built to support <strong>scalable, collaborative development</strong> across teams. It turns contract mocks into a shared language between frontend, backend, and QA — enabling smoother workflows, faster iteration, and earlier validation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G1-8nQAlpdLF3Xmi" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D5Cd92rhRW797Ghb" /></figure><h3>Why Pretendo?</h3><p>Pretendo was born out of a simple need: <strong>eliminate blockers caused by API dependencies</strong> in parallel development.</p><p>Instead of waiting for downstream services or working off assumptions, teams can now mock <strong>exact request-response pairs</strong>, bringing clarity and consistency across the board.</p><p>But more importantly, <strong>Pretendo makes mocking DIY</strong> — putting the power directly in the hands of every developer, not just QA engineers or those familiar with WireMock.</p><p>With a simple UI and intuitive flow, anyone can create, manage, and share mocks without writing a single line of code — turning what used to be a backend-heavy task into an everyday developer tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c0sFOT-qUZJ01Aow" /></figure><h3>How Pretendo Accelerates Zupee Engineering</h3><p>⚡ <strong>Faster Development</strong></p><p>At Zupee, teams can start developing features without waiting for downstream APIs to be ready.</p><p>🤝 <strong>Better Collaboration</strong></p><p>Frontend, backend, and QA work off the same mock contracts, removing ambiguity and increasing confidence.</p><p>🧪 <strong>Proactive Integration Testing</strong></p><p>Mocks help teams test integrations before the real APIs go live — helping us catch bugs earlier.</p><h3>The Transformation: From Blockers to Builders</h3><p>What began as a workaround to unblock development has now become a pillar of Zupee’s engineering culture.</p><p>From using WireMock in our automation pipelines to building <strong>Pretendo</strong> for scale, our journey reflects a core belief:</p><blockquote><strong>Build for collaboration, move fast, and test with confidence.</strong></blockquote><p><strong>The Numbers Tell the Story:</strong></p><ul><li>🚀 <strong>Development Speed:</strong> No more waiting on downstream APIs.</li><li>🔄 <strong>Test Automation Reliability:</strong> From 50% to 99% test success rate</li><li>💰 <strong>Cost Efficiency:</strong> Zero charges for testing third-party integrations</li><li>👥 <strong>Team Collaboration:</strong> 10+ pods building in parallel, on shared contracts.</li></ul><h3>Final Thoughts</h3><p>At Zupee, <strong>mocking isn’t just a test strategy — it’s an engineering mindset</strong>.</p><p>What started with WireMock matured into Pretendo — a tool that reflects how we want to build: collaboratively, rapidly, and with full control.</p><p>We’re no longer asking: <em>“Is the API ready?”</em></p><p>We’re asking:<em>“What contract do we need to move forward?”</em></p><blockquote><strong><em>“If mocking was the foundation, Pretendo is the blueprint for the future of collaborative development at Zupee.”</em></strong></blockquote><p>Passionate about building fast, smart, and scalable systems? Come join the team at Zupee!</p><h3>About Author</h3><p>Payal is a Senior Lead Quality Engineer dedicated to crafting quality engineering practices that scale seamlessly with speed and confidence. With a strong passion for test strategy and building developer-friendly automation frameworks, she helps teams deliver reliable software faster.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83eb913aa5df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Releasing at the Speed of Thought: Inside Zupee’s App Release Engine]]></title>
            <link>https://tech.zupee.com/releasing-at-the-speed-of-thought-inside-zupees-app-release-engine-f100de7b4833?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/f100de7b4833</guid>
            <category><![CDATA[continuous-deployment]]></category>
            <category><![CDATA[release-velocity]]></category>
            <category><![CDATA[release-automation]]></category>
            <category><![CDATA[app-release-management]]></category>
            <category><![CDATA[release-engineering]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 07:21:05 GMT</pubDate>
            <atom:updated>2025-06-24T08:59:57.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ew7X2LQzjlzWLaLzwL0YVQ.jpeg" /></figure><p>In the world of mobile app development, there’s a persistent myth: you can have reliability OR speed, but not both. Most companies spend days or weeks on release cycles, believing that thoroughness requires time.</p><blockquote><strong>At Zupee, we’ve shattered this false choice.</strong></blockquote><p>Our rapid app release cycle delivers both lightning-fast deployment AND bulletproof reliability through our automation-supercharged Release Engine.</p><p>This isn’t just about being fast — it’s about <strong><em>solving automation at scale</em></strong> and <strong><em>continuously evolving</em></strong> our capabilities to stay ahead of complexity. Here’s how we’ve cracked the code on reliable, high-velocity releases:</p><ul><li><strong>Integrated Platform Thinking:</strong> How a unified vision across QA, Dev, and Operations, supercharged by our own in-house platforms like ‘Zenith’, ‘Catalyst’, and ‘Elixir’, creates an unshakeable backbone for efficiency.</li><li><strong>Automation That Thinks (and Scales): </strong>Dive into the sheer depth of our automation — from in-sprint functional tests(frontend, backend) that catch issues early, to AI-driven visual checks — all ensuring quality without sacrificing speed.</li><li><strong>Quality That’s All About Our Users: </strong>Discover how we weave 360-degree feedback from our users and hard data into a continuous loop, constantly refining our releases and the gaming experience itself.</li><li><strong>The Bottom Line — Real Impact: </strong>We’ll connect the dots between our rapid app release cycle and the tangible business wins: faster feature delivery, sharper market responsiveness, and solid, sustainable growth.</li><li><strong>Ready for Tomorrow with AI:</strong> See how we’re not just using AI, but actively embedding it deeper into our DNA to keep pushing the boundaries of release velocity and quality.</li></ul><h3>The Core Challenge: Quality at the Speed of Development</h3><p>Here’s the fundamental problem that most companies struggle with: <strong><em>When development moves fast, how do you ensure testing and quality assurance keep pace without becoming bottlenecks?</em></strong></p><p>Most organisations face this dilemma:</p><ul><li><strong>Fast Development + Slow Testing = Release Bottlenecks</strong></li><li><strong>Fast Development + Fast Testing = Quality Compromises</strong></li><li><strong>Comprehensive Testing + Quality Focus = Slow Releases</strong></li></ul><blockquote><strong>The Zupee Solution:</strong> We’ve engineered a fourth option that breaks this false trilemma entirely.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nOqMT7jgIINBGmyt2v3oA.png" /><figcaption><strong>Quality vs Speed Quadrant</strong></figcaption></figure><h4>What Makes This Different</h4><p>We’re not talking about quick deployments of 1–2 isolated features that any company can push in a few hours. We’re talking about <strong><em>comprehensive, full-scale app releases</em></strong> that include:</p><ul><li>Multiple feature updates</li><li>Backend service changes</li><li>UI/UX improvements</li><li>Performance optimisations</li></ul><h4>Our Achievement</h4><p>Delivering these complete app releases with both speed AND un-compromised quality through intelligent automation.</p><h3>The Engine Room: How We Solved Quality With Rapid Development</h3><h4>1. The Automation Powerhouse: Quality Assurance That Scales with Development</h4><p>Our comprehensive automation is <strong>intelligently architected to match development velocity with quality</strong>. We’ve engineered a multi-layered approach that ensures <strong>full app releases</strong> maintain quality while moving at record speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1epnXYbNj-kFZ4Q1r2UHQ.png" /><figcaption><strong>Zupee’s Multi-Layered Automation Strategy: Comprehensive testing across four critical layers</strong></figcaption></figure><h4>a. In-Sprint Automation: Integrating Automation from the Start</h4><p>Our QA engineers work in perfect synchronization with development teams, crafting automated tests within the same sprint as feature development. This approach doesn’t just build quality — it <strong><em>continuously expands our automation fortress</em></strong> as our platform evolves.</p><h4>b. Our Quality-at-Speed Arsenal: Engineered for Comprehensive App Releases</h4><p>Rather than adapting generic tools, we’ve <strong><em>engineered in-house frameworks</em></strong> that ensure every aspect of our full app releases maintains quality while moving at development speed:</p><p><strong>i. Catalyst (Our Frontend Automation Powerhouse)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIzxJqCAtYnk6KIp5jstwg.png" /><figcaption><strong>Client Automation Architecture</strong></figcaption></figure><ul><li><strong>Tech Stack</strong>: Java, Appium, Cucumber, TestNG, Maven, Jenkins, Spring Boot, Mocking, JDBC, Allure, Log4J, Git, Kafka client, MongoDB Driver Sync, Jedis.</li><li><strong>Quality-Speed Impact:</strong> Over 500 critical user scenarios execute automatically with every build, ensuring <strong><em>complete frontend validation</em></strong> for full app releases without slowing development velocity.</li></ul><p><strong>ii. Elixir (The Guardian of Our Backend)</strong></p><ul><li><strong>Tech Stack</strong>: JestJS, Typescript, Axios, MongoDB, MySql, Eslint, Faker, Husky, Lodash, SNS, SQS, S3 Bucket, Aerospike/Segmentation, Wiremock, Redis, K8s, Socket.io, Ajv for schema validation.</li><li><strong>Quality-Speed Impact</strong>: Around 4,500 automated test cases validate all backend services continuously, enabling <strong><em>multiple Release Engineering cycles per day</em></strong> while maintaining comprehensive quality coverage.</li></ul><p><strong>iii. Safeguarding the Gaming Experience</strong></p><p>We’ve developed comprehensive automation specifically focused on ensuring the integrity and quality of our core gaming experiences, covering both frontend and backend gameplay scenarios as new features are rapidly integrated.</p><p><strong>Frontend User-to-User Gameplay Testing</strong></p><ul><li><strong>Tech Stack: </strong>TypeScript, Mocha, Chai, WDIO, LambdaTest</li><li><strong>Quality-Speed Impact:</strong> Around 150 frontend gameplay scenarios validate user interface interactions and multiplayer connectivity features in real-time with development, ensuring authentic user-to-user gaming experiences.</li></ul><p><strong>Backend Real User Multiplayer Testing</strong></p><ul><li><strong>Tech Stack: </strong>Jest, OpenAI, Socket.IO, Kafka, SQS, Redis, Aerospike, Allure Reports, Docker</li><li><strong>Quality-Speed Impact:</strong> Zupee games have 450 backend gameplay scenarios to <strong>safeguard game logic</strong>, real-time communications, and data integrity, ensuring seamless user-to-user gameplay despite rapid feature deployments.</li></ul><p><strong>iv. The AI-Powered Eagle Eye for Visuals</strong></p><p>We harness tools like LambdaTest Smart UI for AI-driven visual automation. This helps us catch those sneaky visual regressions that functional tests might overlook, ensuring our UIs are always pixel-perfect.</p><p><strong>v. Peak Performance, Always</strong></p><p>Automated API latency testing and app throttling tests (which cleverly simulate user experiences on 2G, 3G, 4G, and Wi-Fi) allow us to proactively sniff out and squash performance bottlenecks and ensure our app shines even in challenging real-world conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiSbh2F7g8ClaaPsxGZ83Q.png" /><figcaption><strong>Front end automations for each application release</strong></figcaption></figure><h4>2. Strategic Quality Orchestration: Ensuring Quality Never Slows Down Development</h4><p><strong>a. Structuring for Growth (People, Process Evolution &amp; Stakeholder Alignment)</strong></p><p>Achieving our current app release capability and sophisticated quality orchestration was a deliberate, phased evolution. This involved establishing formal test management practices, initiating Release Engineering cycles, and securing stakeholder buy-in for a transformed release process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fo-u9BH5r5RHPaCpHAyT3g.png" /><figcaption><strong>App Release Calendar</strong></figcaption></figure><p><strong>c. Zenith — Our Nerve Center</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6cxVmIfRliNQIf_oocBAQ.png" /><figcaption><strong>Zenith — a single ecosystem for test case, test runs, test plans and reporting tool</strong></figcaption></figure><p>Building on our integrated platform thinking, we created <strong><em>Zenith — our in-house developed test management and execution nerve center.</em></strong> Zenith is where we craft and manage test cases, strategize our plans, run executions, orchestrate full-scale app releases, automatically pipe reports into Slack, and get a crystal-clear, unified dashboard view of all our automation suites (backend, frontend, and gameplay) in real-time. (A detailed Medium article on Zenith’s development and capabilities will be coming soon.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnv1GdWGL6Udy_lZTab9sw.png" /><figcaption><strong>Zenith as app release management tool</strong></figcaption></figure><p><strong>d. Defining &amp; Delivering True Quality (Collaboration &amp; 360° User Insights)</strong></p><p>We fostered a culture where QA, Development, and Operations collaborate intensely, driven by a shared platform mindset. We actively sought and integrated <strong>real user experience feedback</strong> from various touchpoints, including our CRM team, app store reviews, and direct player comments. This valuable real-world intel informed our testing and automation strategies, ensuring we deliver a <strong>360-degree, user-centric quality</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Y4wPMG6HbgOqJo6_dNOJQ.png" /><figcaption><strong>Zupee’s Quality-Speed Achievement Dashboard</strong></figcaption></figure><h3>Impact Unleashed: How Our App Release Engine Supercharges Zupee’s Success</h3><p>Our ability to deliver <strong><em>comprehensive, high-quality app releases</em></strong> at lightning speed isn’t just impressive engineering — it’s a fundamental business advantage that drives measurable growth.</p><h4>1. Innovating at Full Throttle &amp; Winning the Market</h4><p>We can dream up, build, and deploy new features, react to shifting market trends, and act on player feedback with unprecedented speed.</p><h4>2. Boosting Business Velocity &amp; Rock-Solid Stability</h4><p>The ripple effects on our operations and overall growth are crystal clear:</p><p><strong>a. Lightning-Fast Rollouts</strong></p><p>New versions reach 100% of our player base in a matter of days, not the weeks it used to take. Value delivered, instantly.</p><p><strong>b. Enhanced Product Stability &amp; Reduced Disruptions</strong></p><p>The superior quality baked in at speed means drastically fewer disruptive hotfix releases. This translates to more stable products, happier players, and a development team that can focus on building the future, not just fixing the past.</p><h4><strong>3. Skyrocketing Confidence &amp; Strategic Freedom</strong></h4><p>The sheer reliability of our Release Engine gives us enormous confidence. We can experiment boldly, iterate rapidly, and pursue ambitious product strategies, knowing we have the horsepower and the stability to deliver, time and time again.</p><h3>Future Forward: Engineering the Next Generation of Automation</h3><h4>1. Embracing the AI Revolution</h4><p>We see immense potential for Artificial Intelligence to further enhance our QA processes, from <strong>smarter test case generation</strong> and prioritization to predictive defect analysis. Our company culture supports and encourages the full <strong>potential</strong> <strong>of AI</strong>, and our QA team is excited to be at the forefront of this innovative wave.</p><p><strong>2. Introducing ‘Trace’: Codeless UI Automation, Zupee Style</strong></p><p>We’re developing Trace as our <strong><em>next-generation UI automation solution</em></strong>, engineered with AI at its core to eliminate manual testing bottlenecks and enable natural language test creation. (A detailed Medium article on Trace’s development and capabilities will be coming soon.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f0kL-k8QDy3rdPHOTieVw.png" /><figcaption><strong>Trace — Codeless UI Automation Tool</strong></figcaption></figure><p><strong>3. Crafting ‘Essence’: Tailor-Made API Testing</strong></p><p>Complementing Trace, Essence represents our <strong><em>intelligent API testing architecture</em></strong> designed to automatically adapt testing strategies based on system behavior and risk patterns.(A detailed Medium article on Essence’s development and capabilities will be coming soon.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*of5-r0eHVIw11WokYevk8Q.png" /><figcaption><strong>Essence — API Tool</strong></figcaption></figure><h3>Conclusion: Setting the Pace, Defining the Future of Gaming Innovation</h3><ul><li><strong>Shattered the false choice</strong> between reliability and speed through automation excellence</li><li><strong>Engineered advanced, multi-layered automation</strong> that operates with surgical precision</li><li><strong>Built continuously-evolving platforms</strong> that scale with our growth and complexity</li><li><strong>Created a release engine</strong> that delivers both bulletproof reliability AND lightning-fast deployment</li></ul><h3>About Author</h3><p><strong>Vishal Agarwal </strong>is a <strong>QA Technical Manager </strong>at Zupee with a strong expertise in leading teams, creating automation frameworks and testing. Vishal brings both technical depth and leadership excellence to drive innovation in quality engineering and automation at scale.</p><p>Thanks for being part of our story!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f100de7b4833" width="1" height="1" alt=""><hr><p><a href="https://tech.zupee.com/releasing-at-the-speed-of-thought-inside-zupees-app-release-engine-f100de7b4833">Releasing at the Speed of Thought: Inside Zupee’s App Release Engine</a> was originally published in <a href="https://tech.zupee.com/">Zupee TechLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Driving User-Level Personalisation at scale with Real-Time Feature Stores]]></title>
            <link>https://tech.zupee.com/driving-user-level-personalisation-at-scale-with-real-time-feature-stores-829e2e9be20c?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/829e2e9be20c</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[personalization]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Fri, 03 May 2024 05:30:33 GMT</pubDate>
            <atom:updated>2024-05-03T05:30:33.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*c4-IRYKP_JqzgMRY3EwcFQ.jpeg" /></figure><h3>Introduction</h3><p>In today’s data-centric world, businesses rely on data-driven decision-making now more than ever. Whether it’s personalizing user experiences, optimizing operations or predicting market trends, data plays a pivotal role. To harness the full potential of data, organizations are turning to real-time feature stores. In this blog, we’ll explore what real-time feature stores are, why they matter and how we at <strong>Zupee</strong> have leveraged real-time feature stores for various use cases.</p><p><strong>Zupee</strong> is a rapidly growing skill based real money gaming platform that caters to a growing user base of more than 80 million registered users. We have been building data powered models to enhance the overall user experience and improve the integrity solutions on our app. These include multiple ML models to improve user recommendations, system integrity solutions etc. The full potential of these models can be leveraged when deployed on real-time data. Serving features on a reliable, real-time and centralized basis would be necessary for these to work. This calls for a <strong>Real Time Feature store</strong> to be built.</p><h3>What is a Real-Time Feature Store?</h3><p>A real-time feature store is a critical component of a modern data architecture. It’s a centralized repository that stores, manages and serves feature data for machine learning (ML) and data analytics applications. Features, in this context, refer to the attributes or characteristics extracted from raw data that serve as inputs for ML models and analytical queries.</p><h3>Key components of a real-time feature store include:</h3><p>1. <strong>Data Ingestion:</strong> Real-time feature stores ingest data from various sources, including databases, data streams and external APIs.</p><p>2. <strong>Feature Engineering:</strong> They provide tools and pipelines for feature engineering, allowing data scientists and engineers to create and transform features as needed.</p><p>3. <strong>Feature Storage:</strong> The feature store stores these engineered features, making them easily accessible for model training and inferencing.</p><p>4. <strong>Real-Time Serving:</strong> It enables low-latency, real-time feature retrieval, a crucial requirement for online applications and ML models that need up-to-the-moment data.</p><h3>Why Real-Time Feature Stores Matter:</h3><p>1. <strong>Enhanced Decision-Making</strong>: Real-time feature stores empower organizations to make decisions based on the most current data available. This is especially critical in fast-paced industries like gaming, e-commerce, finance and healthcare.</p><p>2. <strong>Efficient Model Training</strong>: Machine learning models require up-to-date features for training. Real-time feature stores ensure that data scientists can build models on fresh, relevant data.</p><p>3. <strong>Consistency and Reproducibility</strong>: Centralizing feature storage ensures feature consistency across the organization, reducing the risk of discrepancies in different parts of the pipeline.</p><p>4. <strong>Scalability</strong>: They support high-throughput, low-latency access, even as data volumes grow, making them suitable for large-scale, real-time applications.</p><p>5. <strong>Versioning and Governance</strong>: Feature stores often come with versioning and governance capabilities, allowing organizations to track changes and comply with regulations.</p><h3>Architecture Overview:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rap14vmEn4I2c-6u" /><figcaption>Architecture diagram for real time feature store</figcaption></figure><h3>Data Ingestion:</h3><p>For the data ingestion part we are using messages coming in through various kafka topics.</p><h4>Apache Kafka</h4><p><strong>Apache Kafka</strong> is an open-source distributed event streaming platform used by thousands of companies for high-performance data pipelines, streaming analytics, data integration, and mission-critical applications. <a href="https://kafka.apache.org/">Link</a></p><p>These events are being published by the backend. An example event will be a WINNER_DECLARED event being published by the backend whenever the game is complete and the winner for the table is declared by the system. This event comprises data related to the user such as score, winning amount, game name etc., and also of the table such as prize amount, game’s entry fee, number of players on the table etc.</p><h3>Feature Storage:</h3><p>We are using Aerospike as a storage layer in our Real Time Feature Store.</p><h4>Aerospike</h4><p><strong>Aerospike Database</strong> is a flash memory and<a href="https://en.wikipedia.org/wiki/In-memory_database"> </a>In-memory open source distributed key value NoSQL database management system <a href="https://en.wikipedia.org/wiki/Aerospike_(database)">Link</a></p><p>The multi-model, NoSQL Aerospike Database enables organizations to cost-effectively process gigabytes-to-petabytes of data to make real-time decisions with unlimited scale.</p><p>The <strong>Aerospike</strong> DB has features logically divided into different feature groups. Features on the Aerospike DB are exposed via a server layer which acts as an interface between the DB and downstream applications.</p><p>We are storing features at a unique user level currently and plan to extend to other levels of aggregation going forward. At this level, we have logically segregated the features into sets(similar to a table in a relational database). We want to store aggregate features like aggregate lifetime <strong>GMV</strong> of a particular user and also features like last ’N’ games info. We have come up with a Data structure which would support backfills in case of any issues and also regular recalibration with our Offline DBs without any downtime.</p><p>We have broken the aggregate features like lifetime GMV into <strong>Live</strong> and <strong>TLSTS</strong> sub-features. We also have defined a <strong>LSTS</strong> feature. <strong>LSTS</strong> stands for Last Updated TimeStamp which denotes the time till which the aggregated value is calculated by the backfill Job. It acts as a breakpoint in time between the <strong>Live</strong> and <strong>TLSTS</strong> parts of the features.</p><p><strong>TLSTS</strong> stands for Till Last Updated TimeStamp and this sub-feature has aggregated value till the <strong>LSTS</strong> timestamp.</p><p><strong>Live</strong> sub-feature will have the values aggregated at a date level.</p><h4>Data Structure example — TOTAL GMV of a user:</h4><p>Total <strong>GMV</strong> which is an lifetime aggregate is stored as two sub-features:</p><ul><li><strong>GMV_TLSTS</strong></li><li><strong>GMV_LIVE</strong></li></ul><p>Assuming the Aerospike record for a user has following values as of 20th September, 2023:</p><ul><li><strong>LSTS</strong> of the record: 1694736000000 — which is the start of day of 15th September, 2023 in Millis.</li><li><strong>GMV_TLSTS</strong>: 12000</li><li><strong>GMV_LIVE</strong>:-</li></ul><p>{‘2023–09–15’: 100,</p><p>‘2023–09–16’: 110,</p><p>‘2023–09–17’: 200,</p><p>‘2023–09–18’: 150,</p><p>‘2023–09–19’: 168,</p><p>‘2023–09–20’: 92}</p><p><strong>Total GMV</strong> of the user is calculated as 12000 + 100 + 110 + 200 + 150 + 168 + 92 which is: 12820. This calculation is done on the real-time serving layer and the storage is responsible for keeping these individual sub-features.</p><p>The live part has aggregates at daily level and will be updated by the Flink app whenever there is an update. The <strong>TLSTS</strong> part will have aggregate value as of a particular point of time. This way:</p><ul><li>The backfills in case of any issue can be done easily, without any downtime.</li><li>Synchronisations with offline DBs can be done easily, without any downtime.</li><li>Features like aggregations over the last n days can also be supported.</li><li>Storage can be saved by frequently updating the <strong>TLSTS</strong> fields and removing the corresponding <strong>LIVE</strong> fields.</li></ul><h4>Recalibration Logic:</h4><p>The growing number of keys in the <strong>LIVE </strong>sub-features would be a valid concern here. To tackle this and to maintain a regular sync between the feature store and the offline DBs, we have created a recalibration Job which updates the values based on the logic explained below:</p><ul><li>Delete the <strong>LIVE</strong> keys of dates older than the <strong>LIVE_KEY_WINDOW</strong> threshold</li><li>Update the <strong>LIVE</strong> keys of dates within the threshold by values from offline DBs</li><li>Update the <strong>TLSTS</strong> key with <strong>TLSTS</strong> + values of <strong>deleted</strong> <strong>LIVE</strong> keys</li><li>Also update the <strong>LSTS</strong> value of the record accordingly</li></ul><p>Building on the above example, assuming that:</p><ul><li>We want to keep the last ‘5’ days(N=5) data for the date level aggregation use cases as well i.e., <strong>LIVE_KEY_WINDOW = 5</strong></li><li>Recalibration Job running on 20th Sep, 2023 EOD</li><li>GMV of the user from offline DB for:</li></ul><p>15th September, 2023 is 100</p><p>16th September, 2023 is 110</p><p>17th September, 2023 is 200</p><p>18th September, 2023 is 160</p><p>19th September, 2023 is 168</p><p>20th September, 2023 is 92</p><p>Recalibration Job will update the <strong>LSTS</strong> to: <strong>1694822400000</strong> — which is the start of day of 16th September, 2023 in Millis</p><p><strong>GMV_TLSTS</strong> will be updated to:</p><p><strong>GMV_TLSTS</strong>(old) + sum(<strong>GMV_LIVE</strong>[&lt;<strong>ANY_DATE_LESS_THAN_LIVE_KEY_WINDOW</strong>&gt;])</p><p>12000 + 100 = <strong>12100</strong></p><p>GMV_LIVE keys will be updated as follows:-</p><ul><li>Delete(GMV_LIVE[&lt;<strong>ANY_DATE_LESS_THAN_LIVE_KEY_WINDOW</strong>&gt;])</li><li>GMV_LIVE[&lt;<strong>ANY_DATE_GREATER_THAN_LIVE_KEY_WINDOW</strong>&gt;] = GMV value of that date from offline DB. i.e.,</li></ul><p><strong>GMV_LIVE</strong>:-</p><p>{‘2023–09–16’: 110,</p><p>‘2023–09–17’: 200,</p><p>‘2023–09–18’: 160,</p><p>‘2023–09–19’: 168,</p><p>‘2023–09–20’: 92}</p><p><strong>Total GMV</strong> of the user after recalibration is calculated as 12100 + 110 + 200 + 160 + 168 + 92 which is: 12920.</p><p>The last ’N’ games type of features are kept as a bounded list and update logic depends on the use case.</p><p>The combination of these two data structures is able to cater for most of our use cases.</p><h3>Feature Engineering:</h3><p>We are using Apache Flink for stream processing the incoming Kafka events, feature engineering and publishing these features into the storage layer.</p><h4>Apache Flink</h4><ul><li>Apache Flink is a framework and distributed processing engine for stateful computations over <em>unbounded and bounded</em> data streams. <a href="https://flink.apache.org/what-is-flink/flink-architecture/">Link</a></li></ul><p>We have the aggregated feature store in various sets in Aerospike. The Flink app consumes incoming kafka events, fetches the aggregated old data from aerospike and aggregates and upserts the records to the corresponding set. We have built a Flink app for one logical segregation of features.</p><p>We are using a Job based backfill/recalibration of features. Whenever a new set of features are added, this job is triggered for those features. This job also takes care of the feature recalibration with Offline DBs.</p><h3>Real-Time Serving:</h3><p>We have created a server layer which abstracts the aggregation logic for the user. Most of the calls come from either an ML model deployed on <strong>Flink</strong> or an API call. The client layer takes care of the aggregation of sub-features and any other preprocessing to be done before serving the feature. The client layer is completely decoupled from the storage layer in the Aerospike. This has helped in keeping the client layer lightweight and also this client layer can be imported by an user and can directly call the required features without worrying about the implementation at the storage layer.</p><p>This layer is now created in both Python and node Js which serve our Data Science &amp; Backend use cases respectively. Since we have decoupled the client layer from the storage layer we were able to create clients in multiple languages depending on the use case. We would be moving the definitions to a centralized registry to maintain the consistency of definitions among the clients.</p><h3>Logging:</h3><p>We are publishing the updates in the records to a kafka topic which is then published to s3 via a kafka-s3-connector. We are using this for logging and analytics purposes.</p><h4>AWS s3</h4><p>Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance.</p><p>The downstream kafka events are logged to AWS s3.</p><h3>Conclusion:</h3><p>By leveraging the real-time feature store, we are able to activate multiple ML models such as credit card fraud detection, Collusion Detection on a real-time basis and also serve these centralized features for backend use cases such as segmentation.</p><p>The features and feature groups in the aerospike DB will be extended and polished based on the future requirements of the downstream applications. Features to multiple real time ML models to be built will be served by this feature store. We are also building real-time feature stores on different aggregation levels such as Tournament and Table levels. This will reduce the duplication of features across teams and centralize the definitions of features.</p><h3>About the author</h3><p>Arun Rajaram is a Senior Data Engineer at Zupee, where he has spent over three years designing and developing advanced data architectures. His primary focus has been on building real-time feature stores and precomputed tables that enhance our operational capabilities. At Zupee, he has engineered multiple data pipelines and jobs that are pivotal in supporting our data-driven decision-making processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=829e2e9be20c" width="1" height="1" alt=""><hr><p><a href="https://tech.zupee.com/driving-user-level-personalisation-at-scale-with-real-time-feature-stores-829e2e9be20c">Driving User-Level Personalisation at scale with Real-Time Feature Stores</a> was originally published in <a href="https://tech.zupee.com/">Zupee TechLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Storm: The Art of Managing Third-Party API Disruptions]]></title>
            <link>https://tech.zupee.com/navigating-the-storm-the-art-of-managing-third-party-api-disruptions-3c17ec2ad585?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c17ec2ad585</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[payments-technology]]></category>
            <category><![CDATA[real-money-games]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[fintech]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 10:34:15 GMT</pubDate>
            <atom:updated>2024-02-09T10:34:15.264Z</atom:updated>
            <content:encoded><![CDATA[<p>How to create a dynamic switch between different merchants to bring seamless experience to customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*lm_iYuX-2vnRuxlVl9T3gQ.png" /></figure><h4>Introduction</h4><p>Imagine this scenario: In this totally interconnected world where every business is dependent on tons of third party applications, imagine a scenario where sudden third party API malfunction triggers a chain reaction of issues, leading to service interruptions, frustrated users, and an urgent scramble by developers to rectify the situation. The result? Unplanned downtime that not only affects the end-user experience, but also demands valuable time and resources to manually intervene in situations that could be better managed.</p><p>In this blog post, we embark on a journey, exploring the critical need for effective handling of third-party API downtime. We delve into the challenges posed by manual interventions during API outages and the widespread consequences for businesses and their customers. In this blog, we unravel the secrets of handling API downtime effectively and discover how to ensure uninterrupted service in an ever-evolving digital landscape.</p><h4>Table of Contents:</h4><ul><li>The Problem</li><li>Our Approach</li><li>Implementation details</li><li>Challenges faced</li><li>Lessons learned</li><li>Conclusion</li></ul><h4>The Problem</h4><p>Like any other online business, Zupee also relies on third-party services. Some such requirements include sending OTP, KYC verification, most important is processing PAYMENT for deposits/withdrawals, finding location of the user via GPS, VPA or Bank validation and so on.</p><p>Third-party API downtime can strike unexpectedly, disrupting the flow of critical data, services, and user experiences. The odds increase significantly higher with public third-party APIs or databases in the picture.</p><p>Dealing with external APIs is always tricky. Service degradation, downtimes are quite frequent. Dealing with it manually is not an easy job. On-call person is always on the toes because third-party APIs can degrade anytime.</p><p>For any use case like payouts, we have multiple third-parties integrated(Payment Gateways) in which we have distributed the traffic percentage. So whenever we see an error on one of the payment gateways we manually adjust the traffic so that we get a higher success rate. Once we change the traffic then we have to monitor the other PG who performed badly. Is it performing well? If yes then route the traffic based on the need. As this is an inefficient and manual approach, this leads to a lower success rate in payments. To add to that, a smooth payment process improves customer retention and satisfaction.</p><p>In the above we gave the example for payouts but the same happens with other use cases like deposit, VPA/Bank validations, OTP, KYC verification, etc.</p><p>This leads to a lot of inefficiency in developer productivity and operational challenges in day to day work. We had to find a smart solution to tackle this with absolutely ZERO manual intervention and give the best experience to our customers.</p><h4>Our Approach</h4><p>We solved this problem by breaking down the problem into multiple sub problems and solving at each level independently. This allows us to modify any piece of the system independently with minimal dev changes and we call this system — <strong>Dynamic Switcher</strong>.</p><p><strong>Dynamic Switcher: </strong>It is a real time automated dynamic routing system, which rearranges/routes the traffic by analyzing the feature set or data models.</p><p>The Dynamic switcher algorithm uses a <strong>non-deterministic mathematical model</strong> to rank all applicable merchants for the given transaction, using a lot of information such as merchant performance for a similar transaction recently and historical performance.</p><p><strong>Terminologies</strong></p><ul><li><strong>Bucket: </strong>Small unit of time(say 10 minutes), for which we start the analysis of data and predict traffic allocation for the next bucket(10 minutes).</li><li><strong>Feature Set: </strong>It is an individual measurable property or characteristic of the phenomenon.It refers to a defined collection of attributes or specifications that are used to measure and evaluate the performance of external merchants in a specific context</li><li><strong>Weight</strong>: It defines each feature Set and tells which feature set is more important than the other. If featureSet_1 have more weight than featureSet_2 then the featureSet_1 is more imp than other.</li></ul><p>Dynamic Switcher works on 3 major pillars:</p><ul><li><strong>Aggregation Logic</strong>: consume merchant data continually and find the feature Set result in a bucket.</li><li><strong>Decision Logic</strong>: It ranks the merchants based on the featureSet results.</li><li><strong>Routing Logic</strong>: Based on the featureSet rank, it decides how much absolute traffic will route to particular merchants.</li></ul><h4>Implementation Details:</h4><h4>Aggregation Logic</h4><p>In this, we first have to define the feature sets for which we want to store/aggregate the current/previous buckets or historical data.</p><p>Feature Set are of two types:</p><ul><li><strong>Pre</strong>: FeatureSet that works on previous bucket data or historical data.</li><li><strong>Post</strong>: FeatureSet that works on current bucket data.</li></ul><p>Here the List of feature sets:</p><ul><li><strong>Success Rate(pre)</strong>: It means that if we hit merchant API x times in y minutes and how many API gave us the expected result. Example if we hit that API 100 times in 10 minutes and 80 get success then the success rate is 80% in that time frame.</li><li><strong>Failure Rate(pre)</strong>: It means that if we hit merchant API x times in y minutes and how many API fails. Example if we hit that API 100 times in 10 minutes and 20 fail then the success rate is 20% in that time frame.</li><li><strong>Pendency(pre)</strong>: This is applicable for some use cases like in payments where payment gets stuck on the bank side and payment status is pending for a long time.</li><li><strong>Failure Streak(post)</strong>: If in the previous window one merchant performs good and we give it the majority of traffic in the current window. If it starts performing poorly in the current window, we do not want failure in these cases. Here this feature set helps us in such scenarios. It will check if we encounter continuous errors that breaches a defined error count threshold. This implies that there is some issue with the merchant resulting in errors. In such scenarios, the system should be able to switch the traffic to the stable merchant automatically and avoid giving traffic to the erroneous merchant for some time.</li><li><strong>Allow Minimum Traffic(pre)</strong>: This is one of the most important and beautiful feature sets. This featureSet is required in two cases.</li></ul><p>Case 1: Let’s suppose we have 3 merchants. In the previous window merchant _3 performed quite poorly so we gave zero traffic to that merchant in the current window. In the next window, what we do is we will give 1% of traffic to that merchant. If it performs well then in the next window we give the respected traffic to that merchant.</p><p>Case 2: If we want to add the new merchant, this feature set helps in first giving minimum traffic and then gradually increasing the traffic for the merchant.</p><ul><li><strong>Low Balance(pre)</strong>: what if one merchant usage plan is exhausted, all the requests to that merchant would fail till the time you get it recharged. So we solved this problem as well, and introduced one more feature set where we were able to distribute the traffic according to the usage plan available to make sure we don’t exhaust it.</li><li><strong>Latency(pre)</strong>: If we see high latency on one merchant compared to other then this feature set helps us in traffic distribution.</li><li><strong>Cost Routing(pre): </strong>If one merchant provides service at a lower price as compared to other merchants(Cost charged per unit of requests hit), we can distribute traffic accordingly.</li></ul><p>We start capturing the data for the current API hits to particular merchants in the mongoDB with TTL set. We can also use redis here for capturing the data and it depends on the use-case. Below is the diagram, to demonstrate a similar sample flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GUj1ZGUIO4wWjoIn" /><figcaption>Flow diagram for dynamic switcher in action</figcaption></figure><p>In the above diagram, Whenever we call the third party API we push the event to kafka which is consumed by recon Service. After validating the data, it then pushes to the mongo collections.</p><p>We have defined the bucket size for 10 minutes, it represents a small unit of time(10 minutes), for which we start the analysis of data and predict traffic allocation for the next bucket(10 minutes). With the help of the event bridge(cron), we call recon.service to start analysis for the feature set for the current bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N5t_3BAgdPPIWedD" /></figure><p>Now, we start analyzing the feature Set results on the data store and after analysis we push the results to redis. This result represents the previous window, which helps in taking decisions for traffic allocation for the next bucket window.</p><h3>Decision Logic</h3><p>While data is being captured and aggregated continuously, Decision logic takes care of ranking the merchants based on it. Each feature set has weights assigned to them that represent how much they contribute to rank the merchants relative to each other.</p><p>For every feature set, a merchant score is calculated and then a final score is calculated based on which merchants are finally ranked.</p><p>Let’ say, marchant A and merchant B both have served</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_iY7k863PPl8HtFsAi5NQ.png" /></figure><p>We define the consolidate value that rank each PG by analysis of feature sets, below is a sample formula considering Success Rate(SR) and Latency:</p><p>Result_A = (SR + (pending Rate * SR / 100 * 0.5)) * W_A1 + latency Value * W_A2</p><p>(W_A1, W_A2 are the weightages assigned to the feature sets)</p><p>Lets calculate the score keeping latency weightage as zero and assigning the whole weight to other featureSets.</p><p>MerchantA = success Rate + (pending Rate * success Rate / 100 * 0.5) = 92.25</p><p>MerchantB = success Rate + (pending Rate * success Rate / 100 * 0.5) = 82</p><p>Now, we run the traffic distribution algorithm(explained in next section) based upon the ranks assigned to the particular merchants.</p><p><strong>Low Balance feature set: </strong>This feature set checks how much traffic each PG can support till next refill time or recharge time. This feature set is dependent on use case to use case.</p><p>Why we need this feature set: In payouts we have a use case where we can only refill the payout bank account at 12 pm and on non-bank holiday. So, suppose if we have two payment gateways and one performs good and other poor. In this what happen is that we gave most of the traffic to one PG and other PG zero traffic, this can come to the case that we get zero balance in PG 1 and now we have one PG which perform good but with zero balance and other is already performing bad and now all user base traffic routed to that poorly performing PG and all user based get affected by that. We use a greedy algorithm approach here which is spread over refill time. It helps in optimizing the SR to the best possible value.</p><h3>Routing Logic</h3><p>Considering above example scores,below is a dry run of how the traffic distribution algorithm works:</p><p>Let suppose we have 3 merchants, we treat all merchants equally and route equal traffic allocation to them which is 100 / 3 = 33.333%. Now from the 3 merchants, we find the lowest rank merchant, let suppose that is merchant_3. if merchant_1 has a score 90, merchant_2 has a score 80 and merchant_3 has 75 assigned. Now we compare merchant_3 with all other merchants. As merchant_3 compares with merchant_2 they have a score difference of 5%.</p><p>Here, each rank window example 90–100, 80–90, 70–80 etc, have multiple factors for traffic deductions. If the rank difference lies in the 80–90 window. Like one merchant has 81 and another has 86. Here the difference is 5. But the traffic deduction happen of 5 * window factor = 10%.</p><p>That means merchant_2 will get 5% more traffic compared to merchant_3. Then we deduct the (5 * windowFactor) 15% from merchant_3 originally assigned traffic and assigned that extra traffic to merchant_2 and the same we compared that with merchant_1. Recursively, then we again start with a low rank merchant that is merchant_2 then re-run the same logic.</p><p>After calculating the absolute traffic logic, we push the result to the redis hash.</p><p>When we get the final absolute traffic distribution value, we then use the gaussian probability distribution algorithm. We take the window length number = 256</p><p>If we have 2 merchants with traffic let’s say 50 / 50. Then we create the range like this: Merchant_1 (0, 127) and merchant_2 (128, 255). Then when users do any transaction, we create the random number % 256, if it falls in range (0, 127) then it is Merchant_1 or else Merchant_2. This is the basic idea of traffic distribution and adjusted accordingly depending upon no of merchants and the traffic percentage.</p><p><strong>Failure Streak Feature Set: </strong>When we predict the traffic allocation for the next bucket, it may happen that the best performing merchant is performing bad in the current bucket. We do not want our customers to face bad experiences. To tackle this problem, we came up with a streak feature set solution.</p><p>This checks the merchant performance in real time maintaining the streak of the failed transactions. If it reaches more than threshold value then we take that merchant of the traffic and route the traffic to other active merchants.</p><p>If all merchants perform badly, then the traffic allocation is routed as such and no changes in the routed logic happens.</p><p><strong>Allow minimum traffic Feature Set: </strong>Now allow the minimum feature set to come into picture. If we have 2 or more merchants, if one of the PG performs poorly and gets 0% traffic then this merchant will not get picked up in the next bucket allocation. We have to give at least a minimum amount of traffic, so that it get picked automatically. Example we gave 1% of traffic.</p><p><strong>Cool Off Period</strong>: If a merchant performs badly and gets a minimum amount of traffic(1%) and it again performs badly in the next bucket, then we do not give minimum traffic to that merchant, we wait for the next x buckets to assign the minimum traffic to that PG again.</p><h3>Challenges faced</h3><ul><li>Merchant full or partial downtime</li></ul><p>Let’s suppose as per the previous bucket analysis, you decide merchant 1 as the best third-party. As soon as the next window bucket starts, you start routing traffic to this merchant. What if this merchant faces downtime? All of your requests in this bucket window time frame are going to fail. Certainly, we can’t afford that. The very idea of the Dynamic Switcher is to predict the best merchants ranking for the next window. That prediction will hold true, but it is not guaranteed. So we have to incorporate these scenarios as well. We call it failure streak. This is a kind of circuit breaker, where if a merchant breaches a certain threshold for failure or pendency or any feature set, you can kick out that merchant from the merchants’ list for the current window.</p><ul><li>Insufficient Balance or Rate limiting</li></ul><p>What if one merchant usage plan is exhausted, all the requests to that merchant would fail till the time you get it recharged. So we solved this problem as well, and introduced one more feature set where we were able to distribute the traffic according to the usage plan available to make sure we don’t exhaust it.</p><ul><li>Biasness to a merchant</li></ul><p>Such systems have a tendency to become biased towards one merchant in one or multiple edge cases, so we need to be very cautious about this. We adapted the following two protocols to remove the biases from the system.</p><ul><li>Reviving the kicked out merchant</li></ul><p>We used the Allow Minimum Traffic policy to revive the kicked out merchant. So far, we have discussed how we can remove one merchant based on its performance. But what happens after that, how to bring back that merchant into the system automatically. So for that in every bucket, we keep sending a very minimal traffic till we start getting the successful response. Once done, we start increasing the traffic in a steady manner to make sure the merchant downtime has been fully resolved.</p><ul><li>Adaptive(Non-Linear) distribution instead of Static(Linear) distribution</li></ul><p>This is the most beautiful piece of the whole system. Let’s suppose there are 2 merchants who are performing neck to neck with the same performance score. Let’s say the score is 95 for both, then the system should distribute equal traffic to both the merchants. But what if the score is 95 for one and 90 for another. This 5% difference in the performance score would lead to a slightly higher distribution to merchant 1 and slightly lesser to merchant 2. Let’s say the distribution is 52% and 48%. But the same 5% difference with a performance score of 85% and 80% would lead to higher delta in distribution, let’s say, 60% to merchant 1 and 40% to merchant 2. So it is both, the absolute and the relative performance score, that matters in the traffic distribution.</p><h3>Lessons learned</h3><p>Building this system was a continuous iterative process along with a lot of learning. While we had a north star vision for this system, we did not rush to that. We started with only one flow. That was the most critical one for us to solve. We started with a very basic version of the system to validate our POC. Precision of that system was lower but still we were able to switch automatically to the next best merchant with a lag equivalent to bucket window. Then we improved our system to switch with a lag of the streak window and finally with the real time.</p><p>Then we went ahead and made a common library to be used by other services. It is a very simple plug-in and play model where individual services have the ability to define their own feature sets, rules, decision layer logic and everything.</p><h3>Conclusion</h3><p>This project was an ambitious one. We knew at the very first day what we would be able to achieve with this. Solving a very specific use case is one thing but extending it to enable others is altogether a different milestone. With continuous learning and iterative mindset, we were able to achieve what we envisioned. This project has a very high ROI and now we are reaping it to the full. Developer productivity, cost savings with the merchants usage plan are the highlights apart from system robustness and resilience.</p><h3>About Author</h3><p>Executing this massive project cannot be accomplished by a single individual. Kudos to the team working on this:</p><ul><li><strong>Aman Gupta:</strong> Engineering Leader at Zupee, dedicated to streamlining payments and ensuring compliance through Tech</li><li><strong>Nikhil Kaplas: </strong>The mastermind behind the active solution, serving as the technology leader at Zupee. Nikhil focuses on devising innovative solutions to all payment and compliance technology challenges.</li><li><strong>Kamal Kishore Sharma: </strong>An integral engineer who collaborated closely with Nikhil to bring the project to fruition. Kamal holds the position of senior engineer, working closely with Nikhil and Aman.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c17ec2ad585" width="1" height="1" alt=""><hr><p><a href="https://tech.zupee.com/navigating-the-storm-the-art-of-managing-third-party-api-disruptions-3c17ec2ad585">Navigating the Storm: The Art of Managing Third-Party API Disruptions</a> was originally published in <a href="https://tech.zupee.com/">Zupee TechLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you really really know nodejs?]]></title>
            <link>https://tech.zupee.com/do-you-really-really-know-nodejs-cbcb430c3908?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbcb430c3908</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 09:25:19 GMT</pubDate>
            <atom:updated>2024-01-05T09:25:19.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*wT0tqAUhWNYGdH0VI5nO9g.jpeg" /></figure><h3>Introduction/Motivation</h3><p>I read tons of documents regarding Node.js but every time it seemed to me I had a somewhat partial understanding and at times even incorrect understanding. This was happening because I was trying to visualize what the system was doing through the words in documents but didn’t have the code to back my imagination. Also the documents were designed to present a generic understanding rather than an in depth explanation and for this reason often glossed over important details and also over simplified it in the process. For example there was one time I was debugging the max tick time and wanted to know the exit condition of the io_poll phase of the event loop but no documentation could give me the exact answer with all the conditions (only 48 max iterations are allowed in the io_poll phase and this number is hardcoded in the code).</p><p>Then I asked myself why do we have a very good understanding of the code that we have worked on or debugged or contributed to in any way? And many times don’t even need to rely on any documentation. It is because we are able to read the code which is the absolute truth and not just some simplified generic documentation. So how do we develop a similar understanding of Node.js? Go through the code of course. Also I recommend not blindly trust anything written in this document, verify everything through the code and which is why I have provided the code and its source for almost everything we touch here.</p><h3>Table of Contents : What’s in store for you :</h3><p>Section 1: Starting Point</p><p>Section 2: Libuv and the Event Loop</p><p>Section 3: Node runtime setup</p><p>Section 4: Http Server</p><h3>Starting Point</h3><p>When we are trying to read any piece of code and understand the flow of it, we must begin from the starting point. In our case it is when a user starts running a Node.js program — let’s call it myCode.js — user runs a command on terminal $ <em>node myCode.js </em>.</p><p>Node.js is simply a c++ program and just like any c++ program starts with a main function. Also it has two very important dependencies <em>‘libuv’ and ‘v8’</em>. But that’s all these two are <em>— just c++ dependencies</em> to be imported and used by the main code. And these two dependencies are all there is to understanding Node.js. Libuv contains the heart of Node.js which is the event loop and its execution (method name — uv_run). And v8 is the library which reads the .js files and converts it into machine code which gets executed in Node.js runtime environment.<br>Below is the main function which is where it all starts.</p><p><a href="https://github.com/nodejs/node/blob/main/src/node_main.cc#L96"><em>https://github.com/Node.js/node/blob/main/src/node_main.cc#L96</em></a><em> </em>(this ref may change in future)</p><pre>// src/node_main.cc<br>// https://github.com/Node.js/node/blob/main/src/node_main.cc#L96<br>#include &quot;node.h&quot;<br>...<br><br>int main(int argc, char* argv[]) {<br>  return node::Start(argc, argv); <br>}<br>// implemention of Start is in node.cc (code below) <br><br>...</pre><pre>// src/node.cc<br><br>static ExitCode StartInternal(int argc, char** argv) {<br>  <br>  ...<br><br>  uv_loop_configure(uv_default_loop(), UV_METRICS_IDLE_TIME);<br><br><br>  ...<br><br>  NodeMainInstance main_instance(snapshot_data,<br>                                 uv_default_loop(),<br>                                 per_process::v8_platform.Platform(),<br>                                 result-&gt;args(),<br>                                 result-&gt;exec_args());<br>  return main_instance.Run();<br>}<br><br><br>int Start(int argc, char** argv) {<br>#ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION<br>  std::tie(argc, argv) = sea::FixupArgsForSEA(argc, argv);<br>#endif<br>  return static_cast&lt;int&gt;(StartInternal(argc, argv));<br>}</pre><p>Main() function calls node.cc#Start() function (code above) which calls the StartInternal() function.</p><p>Two things happen here :-</p><ol><li>Event loop initializes — uv_default_loop() and event loop starts — uv_run(). StartInternal function initializes the main_intance object -</li></ol><pre>main_instance(  snapshot_data,<br>                uv_default_loop(),<br>                per_process::v8_platform.Platform(),<br>                result-&gt;args(),<br>                result-&gt;exec_args()); // code highlighted above as well<br><br>return main_instance.Run();</pre><p>This sets up the event loop using uv_default_loop() and then main_instance.Run() is executed which starts the event loop by invoking the uv_run() function of libuv</p><p>2. The V8 instance for our particular platform is initialized using v8_platform.Platform(). And all the javascript code needed gets initialized. How we use the v8 engine is later explained in the article under — ‘Node runtime setup’ section</p><h3>Libuv and The Event loop</h3><p>Continuing on the method we have adopted so far, i.e reading directly from the ultimate source of truth — the Code</p><h4>Event loop initialisation</h4><p>uv_default_loop</p><pre>// deps/uv/src/uv-commons.c<br><br>uv_loop_t* uv_default_loop(void) {<br>  if (default_loop_ptr != NULL)<br>    return default_loop_ptr;<br><br>  if (uv_loop_init(&amp;default_loop_struct))<br>    return NULL;<br><br>  default_loop_ptr = &amp;default_loop_struct;<br>  return default_loop_ptr;<br>}<br></pre><pre>// deps/uv/src/unix/loop.c<br><br><br><br>int uv_loop_init(uv_loop_t* loop) {<br> <br>...<br><br>//* the timer_heap contains the callbacks added using setTimeout() and setInterval() and it used in the event loop to execute these callbacks */<br>  heap_init((struct heap*) &amp;loop-&gt;timer_heap);<br><br><br>  uv__queue_init(&amp;loop-&gt;wq);<br><br>//* Used for callbacks scheduled to run when the event loop is idle. These are typically tasks that should be executed when there are no other pressing operations to handle */<br>  uv__queue_init(&amp;loop-&gt;idle_handles);<br>  uv__queue_init(&amp;loop-&gt;async_handles);<br><br>//* The check_handles queue is used for setImmediate callbacks. These are functions that are scheduled to run after the current poll phase of the event loop */<br>  uv__queue_init(&amp;loop-&gt;check_handles);<br><br>//* This queue is for callbacks that need to run before the event loop begins its poll phase. In Node.js, this could be used for setup operations prior to executing I/O-related tasks */<br>  uv__queue_init(&amp;loop-&gt;prepare_handles);<br>  uv__queue_init(&amp;loop-&gt;handle_queue);<br><br> ...<br><br>// The pending_queue mostly takes care of the tasks which could not be handled immediately.<br>  uv__queue_init(&amp;loop-&gt;pending_queue);<br><br>// watcher queue is the most important queue as this is where we add watchers with file descriptors. These file descriptors are polled during the uv__io_poll phase of the event loop run (uv_run) for data */<br>  uv__queue_init(&amp;loop-&gt;watcher_queue);<br>  ....<br>}</pre><h4>Event loop execution</h4><p>We have seen the initialisation so now let’s get to the execution stage</p><p>So continuing where we left from in the section — Starting Point, i.e main_instance.Run()</p><pre>// node_main_instance.cc<br>// https://github.com/Node.js/node/blob/main/src/node_main_instance.cc#L33<br><br><br>// This Run method is invoked from node.cc StartInternal method<br>ExitCode NodeMainInstance::Run() {<br>  <br>  ...<br><br>  Run(&amp;exit_code, env.get()); // implementation of this method is just below<br>  return exit_code;<br>}<br><br>void NodeMainInstance::Run(ExitCode* exit_code, Environment* env) {<br> ...<br><br>// this will start the event loop by invoking uv_run method from it<br>// this implementation of this method is in the code block below<br>    *exit_code =<br>        SpinEventLoopInternal(env).FromMaybe(ExitCode::kGenericUserError);<br>  }<br><br>  ...<br>}<br><br><br><br>// src/api/embed_helpers.cc - https://github.com/Node.js/node/blob/main/src/api/embed_helpers.cc#L22C1-L22C1<br><br><br>Maybe&lt;ExitCode&gt; SpinEventLoopInternal(Environment* env) {<br>  <br>   ...<br><br>      uv_run(env-&gt;event_loop(), UV_RUN_DEFAULT); // event loop starts running<br>     <br>   ...<br>}<br></pre><p>Event loop function implementation</p><p>The important components of event loop execution (uv_run):</p><ul><li>uv__io_poll(loop, timeout) — uv_io_poll is the phase where sockets are polled for incoming data using epoll_pwait (in case of linux)</li><li>uv__run_check(loop) — this is the phase where callbacks which were attached with setImmediate are executed</li><li>uv__run_closing_handles(loop) — as the name suggests — close the handles marked for closing. What is a handle is explained in the section — Node runtime setup</li><li>uv__run_timers(loop) — this is the phase where the callbacks which were attached with setTimeouts and setIntervals are executed</li></ul><pre>//https://github.com/Node.js/node/blob/main/deps/uv/src/unix/core.c#L414<br>// This function - uv_run is the event loop executing<br><br>int uv_run(uv_loop_t* loop, uv_run_mode mode) {<br>  int timeout;<br>  int r;<br>  int can_sleep;<br><br>  r = uv__loop_alive(loop);<br>  if (!r)<br>    uv__update_time(loop);<br><br>  /* Maintain backwards compatibility by processing timers before entering the<br>   * while loop for UV_RUN_DEFAULT. Otherwise timers only need to be executed<br>   * once, which should be done after polling in order to maintain proper<br>   * execution order of the conceptual event loop. */<br>  if (mode == UV_RUN_DEFAULT &amp;&amp; r != 0 &amp;&amp; loop-&gt;stop_flag == 0) {<br>    uv__update_time(loop);<br>    uv__run_timers(loop);<br>  }<br><br>  while (r != 0 &amp;&amp; loop-&gt;stop_flag == 0) {<br>    can_sleep =<br>        uv__queue_empty(&amp;loop-&gt;pending_queue) &amp;&amp;<br>        uv__queue_empty(&amp;loop-&gt;idle_handles);<br><br>    uv__run_pending(loop);<br>    uv__run_idle(loop);<br>    uv__run_prepare(loop);<br><br>    timeout = 0;<br>    if ((mode == UV_RUN_ONCE &amp;&amp; can_sleep) || mode == UV_RUN_DEFAULT)<br>// uv__next_timeout calculates how long the event loop should wait for I/O events (which happens in the uv__io_poll phase) based on the timing of the nearest scheduled timer (INT_MAX incase no timer is scheduled). It ensures the event loop blocks for an appropriate amount of time, waking up either when I/O events are ready or when it&#39;s time to handle the next scheduled timer event. This calculation is crucial for the efficient and timely execution of asynchronous tasks within the event loop.<br>      timeout = uv__backend_timeout(loop);<br><br>    uv__metrics_inc_loop_count(loop);<br><br>//  uv_io_poll is the phase where sockets are polled for incoming data using epoll_pwait (in case of linux)<br>    uv__io_poll(loop, timeout);<br><br>    /* Process immediate callbacks (e.g. write_cb) a small fixed number of<br>     * times to avoid loop starvation.*/<br>    for (r = 0; r &lt; 8 &amp;&amp; !uv__queue_empty(&amp;loop-&gt;pending_queue); r++)<br>      uv__run_pending(loop);<br><br>    /* Run one final update on the provider_idle_time in case uv__io_poll<br>     * returned because the timeout expired, but no events were received. This<br>     * call will be ignored if the provider_entry_time was either never set (if<br>     * the timeout == 0) or was already updated b/c an event was received.<br>     */<br>    uv__metrics_update_idle_time(loop);<br><br>// this is the phase where callbacks which were attached with setImmediate are executed<br>    uv__run_check(loop);<br><br>// as the name suggests - close the handles marked for closing<br>    uv__run_closing_handles(loop);<br><br>//  this is the phase where the callbacks which were attached with setTimeouts and setIntervals are executed <br>    uv__update_time(loop);<br>    uv__run_timers(loop);<br><br>    r = uv__loop_alive(loop);<br>    if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)<br>      break;<br>  }<br><br>  /* The if statement lets gcc compile it to a conditional store. Avoids<br>   * dirtying a cache line.<br>   */<br>  if (loop-&gt;stop_flag != 0)<br>    loop-&gt;stop_flag = 0;<br><br>  return r;<br>}</pre><p>Reader can go through all the functions highlighted in the uv_run method. I’ll provide below the explanation for the uv__io_poll(loop, timeout) method which is the soul of the event loop</p><p>Again, as we have decided, we would go through the code. So let’s dive in.</p><pre>// deps/uv/src/unix/linux.c<br><br><br>void uv__io_poll(uv_loop_t* loop, int timeout) {<br>  ...<br><br>// base stores time at the start of the polling loop<br>  base = loop-&gt;time;<br>// max length of the io poll loop<br>  count = 48; /* Benchmarks suggest this gives the best throughput. */<br>  real_timeout = timeout;<br><br>  if (lfields-&gt;flags &amp; UV_METRICS_IDLE_TIME) {<br>    reset_timeout = 1;<br>    user_timeout = timeout;<br>    timeout = 0;<br>  } else {<br>    reset_timeout = 0;<br>    user_timeout = 0;<br>  }<br><br>  epollfd = loop-&gt;backend_fd;<br><br>  memset(&amp;e, 0, sizeof(e));<br>// Empty the watchers queue which contains file descriptors to watch for data and add it to the prep array. Later in the article you&#39;ll get a very clear understanding of how the watcher queue is populated in the first place. But for now proceed with the understanding that it has data regarding file descriptors on which network is going to write data<br>  while (!uv__queue_empty(&amp;loop-&gt;watcher_queue)) {<br>    q = uv__queue_head(&amp;loop-&gt;watcher_queue);<br>    w = uv__queue_data(q, uv__io_t, watcher_queue);<br>    uv__queue_remove(q);<br>    uv__queue_init(q);<br><br>    op = EPOLL_CTL_MOD;<br>    if (w-&gt;events == 0)<br>      op = EPOLL_CTL_ADD;<br><br>    w-&gt;events = w-&gt;pevents;<br>    e.events = w-&gt;pevents;<br>    e.data.fd = w-&gt;fd;<br><br>    uv__epoll_ctl_prep(epollfd, ctl, &amp;prep, op, w-&gt;fd, &amp;e);<br>  }<br><br>  inv.events = events;<br>  inv.prep = &amp;prep;<br>  inv.nfds = -1;<br><br>  for (;;) {<br>// no file descriptors to watch and so exit<br><br>    if (loop-&gt;nfds == 0)<br>      if (iou-&gt;in_flight == 0)<br>        break;<br><br>    /* All event mask mutations should be visible to the kernel before<br>     * we enter epoll_pwait().<br>     */<br>    if (ctl-&gt;ringfd != -1)<br>      while (*ctl-&gt;sqhead != *ctl-&gt;sqtail)<br>        uv__epoll_ctl_flush(epollfd, ctl, &amp;prep);<br><br>    /* Only need to set the provider_entry_time if timeout != 0. The function<br>     * will return early if the loop isn&#39;t configured with UV_METRICS_IDLE_TIME.<br>     */<br>    if (timeout != 0)<br>      uv__metrics_set_provider_entry_time(loop);<br><br>    /* Store the current timeout in a location that&#39;s globally accessible so<br>     * other locations like uv__work_done() can determine whether the queue<br>     * of events in the callback were waiting when the poll was called.<br>     */<br>    lfields-&gt;current_timeout = timeout;<br><br>// nfds variable has the number of file descriptors on which data is available to be read and events variable has information of such fds. <br>// epoll_pwait is a linux system call which blocks the loop till at least 1 socket it is waiting on is readable or timeout has reached. Notice I am deliberately using the word &#39;blocks&#39;. But because it can efficiently wait on multiple sockets at the same time and returns data even if one of them has data to read, the wait time is minimal<br>    nfds = epoll_pwait(epollfd, events, ARRAY_SIZE(events), timeout, sigmask);<br><br>    /* Update loop-&gt;time unconditionally. It&#39;s tempting to skip the update when<br>     * timeout == 0 (i.e. non-blocking poll) but there is no guarantee that the<br>     * the operating system didn&#39;t reschedule our process while in the syscall.<br>     */<br>    SAVE_ERRNO(uv__update_time(loop));<br><br>// if no file descriptors have data and timeout has happened then break loop<br>    if (nfds == 0) {<br>      assert(timeout != -1);<br><br>      if (reset_timeout != 0) {<br>        timeout = user_timeout;<br>        reset_timeout = 0;<br>      }<br><br>      if (timeout == -1)<br>        continue;<br><br>      if (timeout == 0)<br>        break;<br><br>      /* We may have been inside the system call for longer than |timeout|<br>       * milliseconds so we need to update the timestamp to avoid drift.<br>       */<br>      goto update_timeout;<br>    }<br><br>// if error break the loop<br>    if (nfds == -1) {<br>      if (errno != EINTR)<br>        abort();<br><br>      if (reset_timeout != 0) {<br>        timeout = user_timeout;<br>        reset_timeout = 0;<br>      }<br><br>      if (timeout == -1)<br>        continue;<br><br>      if (timeout == 0)<br>        break;<br><br>      /* Interrupted by a signal. Update timeout and poll again. */<br>      goto update_timeout;<br>    }<br><br>    have_iou_events = 0;<br>    have_signals = 0;<br>    nevents = 0;<br><br>    inv.nfds = nfds;<br>    lfields-&gt;inv = &amp;inv;<br><br>    for (i = 0; i &lt; nfds; i++) {<br>      pe = events + i;<br>      fd = pe-&gt;data.fd;<br><br>      /* Skip invalidated events, see uv__platform_invalidate_fd */<br>      if (fd == -1)<br>        continue;<br><br>      if (fd == iou-&gt;ringfd) {<br>        uv__poll_io_uring(loop, iou);<br>        have_iou_events = 1;<br>        continue;<br>      }<br><br>      assert(fd &gt;= 0);<br>      assert((unsigned) fd &lt; loop-&gt;nwatchers);<br><br>      w = loop-&gt;watchers[fd];<br><br>      if (w == NULL) {<br>        /* File descriptor that we&#39;ve stopped watching, disarm it.<br>         *<br>         * Ignore all errors because we may be racing with another thread<br>         * when the file descriptor is closed.<br>         */<br>        uv__epoll_ctl_prep(epollfd, ctl, &amp;prep, EPOLL_CTL_DEL, fd, pe);<br>        continue;<br>      }<br><br>      /* Give users only events they&#39;re interested in. Prevents spurious<br>       * callbacks when previous callback invocation in this loop has stopped<br>       * the current watcher. Also, filters out events that users has not<br>       * requested us to watch.<br>       */<br>      pe-&gt;events &amp;= w-&gt;pevents | POLLERR | POLLHUP;<br><br>      /* Work around an epoll quirk where it sometimes reports just the<br>       * EPOLLERR or EPOLLHUP event.  In order to force the event loop to<br>       * move forward, we merge in the read/write events that the watcher<br>       * is interested in; uv__read() and uv__write() will then deal with<br>       * the error or hangup in the usual fashion.<br>       *<br>       * Note to self: happens when epoll reports EPOLLIN|EPOLLHUP, the user<br>       * reads the available data, calls uv_read_stop(), then sometime later<br>       * calls uv_read_start() again.  By then, libuv has forgotten about the<br>       * hangup and the kernel won&#39;t report EPOLLIN again because there&#39;s<br>       * nothing left to read.  If anything, libuv is to blame here.  The<br>       * current hack is just a quick bandaid; to properly fix it, libuv<br>       * needs to remember the error/hangup event.  We should get that for<br>       * free when we switch over to edge-triggered I/O.<br>       */<br>      if (pe-&gt;events == POLLERR || pe-&gt;events == POLLHUP)<br>        pe-&gt;events |=<br>          w-&gt;pevents &amp; (POLLIN | POLLOUT | UV__POLLRDHUP | UV__POLLPRI);<br><br>      if (pe-&gt;events != 0) {<br>        /* Run signal watchers last.  This also affects child process watchers<br>         * because those are implemented in terms of signal watchers.<br>         */<br>        if (w == &amp;loop-&gt;signal_io_watcher) {<br>          have_signals = 1;<br>        } else {<br>          uv__metrics_update_idle_time(loop);<br>          w-&gt;cb(loop, w, pe-&gt;events);<br>        }<br><br>        nevents++;<br>      }<br>    }<br><br>    uv__metrics_inc_events(loop, nevents);<br>    if (reset_timeout != 0) {<br>      timeout = user_timeout;<br>      reset_timeout = 0;<br>      uv__metrics_inc_events_waiting(loop, nevents);<br>    }<br><br>    if (have_signals != 0) {<br>      uv__metrics_update_idle_time(loop);<br>      loop-&gt;signal_io_watcher.cb(loop, &amp;loop-&gt;signal_io_watcher, POLLIN);<br>    }<br><br>    lfields-&gt;inv = NULL;<br><br>    if (have_iou_events != 0)<br>      break;  /* Event loop should cycle now so don&#39;t poll again. */<br><br>// if received operating system signal like SIG_INT etc then break<br>    if (have_signals != 0)<br>      break;  /* Event loop should cycle now so don&#39;t poll again. */<br>// if there were some sockets on which we had data <br>    if (nevents != 0) {<br>// if the count of event processed has reached then should exit so as to not block the process further <br>// if count has not reached but the events array is full then try one more time because there might be few more sockets with data but could be read due to events array being full <br>      if (nfds == ARRAY_SIZE(events) &amp;&amp; --count != 0) {<br>        /* Poll for more events but don&#39;t block this time. */<br>        timeout = 0;<br>        continue;<br>      }<br>// Returning immediately after processing available events so that the function doesn&#39;t spend extra time polling when there are no more events to process.<br>      return;<br>    }<br><br><br>    if (timeout == 0)<br>      break;<br><br>    if (timeout == -1)<br>      continue;<br><br>update_timeout:<br>    assert(timeout &gt; 0);<br><br>    real_timeout -= (loop-&gt;time - base);<br>    if (real_timeout &lt;= 0)<br>      break;<br><br>    timeout = real_timeout;<br>  } // for loop ends here<br><br>  if (ctl-&gt;ringfd != -1)<br>    while (*ctl-&gt;sqhead != *ctl-&gt;sqtail)<br>      uv__epoll_ctl_flush(epollfd, ctl, &amp;prep);<br>}<br></pre><h4>Microtasks and nextTick</h4><p>Callbacks enqueued in the microtask queue and nextTick queue are executed during the event loop itself. But wait, we have the event loop above but it doesn’t have anything related to microtasks execution or nextTick execution? Well it does, it is there during the execution of the timer callbacks and the immediate callbacks. So let’s look at the code.</p><pre>// https://github.com/nodejs/node/blob/main/lib/internal/bootstrap/node.js#L305<br><br>{<br>  const { nextTick, runNextTicks } = setupTaskQueue();<br>  process.nextTick = nextTick;<br>  // Used to emulate a tick manually in the JS land.<br>  // A better name for this function would be `runNextTicks` but<br>  // it has been exposed to the process object so we keep this legacy name<br>  // TODO(joyeecheung): either remove it or make it public<br>  process._tickCallback = runNextTicks;<br><br>  const { setupTimers } = internalBinding(&#39;timers&#39;);<br>  const {<br>    processImmediate,<br>    processTimers,<br>  } = internalTimers.getTimerCallbacks(runNextTicks);<br>  // Sets two per-Environment callbacks that will be run from libuv:<br>  // - processImmediate will be run in the callback of the per-Environment<br>  //   check handle.<br>  // - processTimers will be run in the callback of the per-Environment timer.<br>  setupTimers(processImmediate, processTimers);<br> // this setupTimers method actually passes these two methods - processImmediate and processTimers to libuv through a binding interface function which I have provided below<br>  // Note: only after this point are the timers effective<br>}<br>// implementation of processImmediate and processTimers is in the next code block and them getting passed to libuv is in the code block below<br><br>// lib/internals/timers.js<br><br>function getTimerCallbacks(runNextTicks) {<br>  // If an uncaught exception was thrown during execution of immediateQueue,<br>  // this queue will store all remaining Immediates that need to run upon<br>  // resolution of all error handling (if the process is still alive).<br>  const outstandingQueue = new ImmediateList();<br><br>  function processImmediate() {<br>    const queue = outstandingQueue.head !== null ?<br>      outstandingQueue : immediateQueue;<br>    let immediate = queue.head;<br><br>    // Clear the linked list early in case new `setImmediate()`<br>    // calls occur while immediate callbacks are executed<br>    if (queue !== outstandingQueue) {<br>      queue.head = queue.tail = null;<br>      immediateInfo[kHasOutstanding] = 1;<br>    }<br><br>    let prevImmediate;<br>    let ranAtLeastOneImmediate = false;<br>    while (immediate !== null) { // iterate till list is empty<br>      if (ranAtLeastOneImmediate)<br>        runNextTicks();<br>      else<br>        ranAtLeastOneImmediate = true;<br><br>      // It&#39;s possible for this current Immediate to be cleared while executing<br>      // the next tick queue above, which means we need to use the previous<br>      // Immediate&#39;s _idleNext which is guaranteed to not have been cleared.<br>      if (immediate._destroyed) {<br>        outstandingQueue.head = immediate = prevImmediate._idleNext;<br>        continue;<br>      }<br><br>      // TODO(RaisinTen): Destroy and unref the Immediate after _onImmediate()<br>      // gets executed, just like how Timeouts work.<br>      immediate._destroyed = true;<br><br>      immediateInfo[kCount]--;<br>      if (immediate[kRefed])<br>        immediateInfo[kRefCount]--;<br>      immediate[kRefed] = null;<br><br>      prevImmediate = immediate;<br><br>      const asyncId = immediate[async_id_symbol];<br>      emitBefore(asyncId, immediate[trigger_async_id_symbol], immediate);<br><br>      try {<br>        const argv = immediate._argv;<br>        if (!argv)<br>          immediate._onImmediate();<br>        else<br>          immediate._onImmediate(...argv);<br>      } finally {<br>        immediate._onImmediate = null;<br><br>        if (destroyHooksExist())<br>          emitDestroy(asyncId);<br><br>        outstandingQueue.head = immediate = immediate._idleNext;<br>      }<br><br>      emitAfter(asyncId);<br>    }<br><br>    if (queue === outstandingQueue)<br>      outstandingQueue.head = null;<br>    immediateInfo[kHasOutstanding] = 0;<br>  }<br><br><br>  function processTimers(now) {<br>    debug(&#39;process timer lists %d&#39;, now);<br>    nextExpiry = Infinity;<br><br>    let list;<br>    let ranAtLeastOneList = false;<br>    while ((list = timerListQueue.peek()) != null) {<br>      if (list.expiry &gt; now) {<br>        nextExpiry = list.expiry;<br>        return timeoutInfo[0] &gt; 0 ? nextExpiry : -nextExpiry;<br>      }<br>      if (ranAtLeastOneList)<br>        runNextTicks();<br>      else<br>        ranAtLeastOneList = true;<br>      listOnTimeout(list, now);<br>    }<br>    return 0;<br>  }<br><br>  function listOnTimeout(list, now) {<br>    const msecs = list.msecs;<br><br>    debug(&#39;timeout callback %d&#39;, msecs);<br><br>    let ranAtLeastOneTimer = false;<br>    let timer;<br>    while ((timer = L.peek(list)) != null) {<br>      const diff = now - timer._idleStart;<br><br>      // Check if this loop iteration is too early for the next timer.<br>      // This happens if there are more timers scheduled for later in the list.<br>      if (diff &lt; msecs) {<br>        list.expiry = MathMax(timer._idleStart + msecs, now + 1);<br>        list.id = timerListId++;<br>        timerListQueue.percolateDown(1);<br>        debug(&#39;%d list wait because diff is %d&#39;, msecs, diff);<br>        return;<br>      }<br><br>      if (ranAtLeastOneTimer)<br>        runNextTicks();<br>      else<br>        ranAtLeastOneTimer = true;<br><br>      // The actual logic for when a timeout happens.<br>      L.remove(timer);<br><br>      const asyncId = timer[async_id_symbol];<br><br>      if (!timer._onTimeout) {<br>        if (!timer._destroyed) {<br>          timer._destroyed = true;<br><br>          if (timer[kRefed])<br>            timeoutInfo[0]--;<br><br>          if (destroyHooksExist())<br>            emitDestroy(asyncId);<br>        }<br>        continue;<br>      }<br><br>      emitBefore(asyncId, timer[trigger_async_id_symbol], timer);<br><br>      let start;<br>      if (timer._repeat) {<br>        // We need to use the binding as the receiver for fast API calls.<br>        start = binding.getLibuvNow();<br>      }<br><br>      try {<br>        const args = timer._timerArgs;<br>        if (args === undefined)<br>          timer._onTimeout();<br>        else<br>          ReflectApply(timer._onTimeout, timer, args);<br>      } finally {<br>        if (timer._repeat &amp;&amp; timer._idleTimeout !== -1) {<br>          timer._idleTimeout = timer._repeat;<br>          insert(timer, timer._idleTimeout, start);<br>        } else if (!timer._idleNext &amp;&amp; !timer._idlePrev &amp;&amp; !timer._destroyed) {<br>          timer._destroyed = true;<br><br>          if (timer[kRefed])<br>            timeoutInfo[0]--;<br><br>          if (destroyHooksExist())<br>            emitDestroy(asyncId);<br>        }<br>      }<br><br>      emitAfter(asyncId);<br>    }<br><br>    // If `L.peek(list)` returned nothing, the list was either empty or we have<br>    // called all of the timer timeouts.<br>    // As such, we can remove the list from the object map and<br>    // the PriorityQueue.<br>    debug(&#39;%d list empty&#39;, msecs);<br><br>    // The current list may have been removed and recreated since the reference<br>    // to `list` was created. Make sure they&#39;re the same instance of the list<br>    // before destroying.<br>    if (list === timerListMap[msecs]) {<br>      delete timerListMap[msecs];<br>      timerListQueue.shift();<br>    }<br>  }<br><br>  return {<br>    processImmediate,<br>    processTimers,<br>  };<br>}<br><br><br>// https://github.com/nodejs/node/blob/main/src/timers.cc#L22<br><br><br>void BindingData::SetupTimers(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {<br><br>...<br><br>// The javascript function above - processImmediate and processTimers are passed to libuv through this binding interface. (Bindings are discussed briefly below)<br>  env-&gt;set_immediate_callback_function(args[0].As&lt;Function&gt;());<br>  env-&gt;set_timers_callback_function(args[1].As&lt;Function&gt;());<br>}</pre><p>As it has become already evident from the code above while setting up the libuv queues to process immediate callbacks and timer callbacks, we have attached to these callbacks processing of microtasks and nextTicks. Readers might find in some documents floating on the internet which will tell you that microtasks and nextTicks execute after every phase of the event loop. But, in fact they get executed after every callback of every phase of the event loop (except the io_poll phase) because the callbacks of timers and immediate phase are wrapped with invocation of nextTick and microtask callbacks. Also the whole queue storing microtasks and nextTicks gets processed all at once.</p><h3>Node runtime setup</h3><p>Continuing from where we concluded in the Starting Point section</p><pre>// src/node_main_instance.cc<br>// This Run method is invoked from node.cc StartInternal method<br>ExitCode NodeMainInstance::Run() {<br>  Locker locker(isolate_);<br>  Isolate::Scope isolate_scope(isolate_);<br>  HandleScope handle_scope(isolate_);<br><br>  ExitCode exit_code = ExitCode::kNoFailure;<br>  DeleteFnPtr&lt;Environment, FreeEnvironment&gt; env =<br>      CreateMainEnvironment(&amp;exit_code);<br>  CHECK_NOT_NULL(env);<br><br>  Context::Scope context_scope(env-&gt;context());<br>  Run(&amp;exit_code, env.get()); // implementation of this method is just below<br>  return exit_code;<br>}<br><br>void NodeMainInstance::Run(ExitCode* exit_code, Environment* env) {<br>  if (*exit_code == ExitCode::kNoFailure) {<br>    bool runs_sea_code = false;<br>#ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION<br>    if (sea::IsSingleExecutable()) {<br>      sea::SeaResource sea = sea::FindSingleExecutableResource();<br>      if (!sea.use_snapshot()) {<br>        runs_sea_code = true;<br>        std::string_view code = sea.main_code_or_snapshot;<br>        LoadEnvironment(env, code);<br>      }<br>    }<br>#endif<br>    // Either there is already a snapshot main function from SEA, or it&#39;s not<br>    // a SEA at all.<br>    if (!runs_sea_code) {<br>      LoadEnvironment(env, StartExecutionCallback{});<br>    }<br><br>// this will start the event loop by invoking uv_run method from it<br>// this implementation of this method is in the code block below<br>    *exit_code =<br>        SpinEventLoopInternal(env).FromMaybe(ExitCode::kGenericUserError);<br>  }<br><br>#if defined(LEAK_SANITIZER)<br>  __lsan_do_leak_check();<br>#endif<br>}</pre><pre>//src/api/environment.cc<br><br><br>MaybeLocal&lt;Value&gt; LoadEnvironment(<br>    Environment* env,<br>    StartExecutionCallback cb) {<br>  env-&gt;InitializeLibuv();<br>  env-&gt;InitializeDiagnostics();<br><br>  return StartExecution(env, cb);<br>}<br><br></pre><pre>// src/node.cc<br><br>MaybeLocal&lt;Value&gt; StartExecution(Environment* env, const char* main_script_id) {<br> ...<br><br>  return scope.EscapeMaybe(realm-&gt;ExecuteBootstrapper(main_script_id));<br>}<br><br>MaybeLocal&lt;Value&gt; StartExecution(Environment* env, StartExecutionCallback cb) {<br> ...<br><br>  if (env-&gt;worker_context() != nullptr) {<br>    return StartExecution(env, &quot;internal/main/worker_thread&quot;);<br>  }<br><br>  std::string first_argv;<br>  if (env-&gt;argv().size() &gt; 1) {<br>    first_argv = env-&gt;argv()[1];<br>  }<br><br>  if (first_argv == &quot;inspect&quot;) {<br>    return StartExecution(env, &quot;internal/main/inspect&quot;);<br>  }<br><br>  if (per_process::cli_options-&gt;print_help) {<br>    return StartExecution(env, &quot;internal/main/print_help&quot;);<br>  }<br><br>  if (env-&gt;options()-&gt;prof_process) {<br>    return StartExecution(env, &quot;internal/main/prof_process&quot;);<br>  }<br><br>  // -e/--eval without -i/--interactive<br>  if (env-&gt;options()-&gt;has_eval_string &amp;&amp; !env-&gt;options()-&gt;force_repl) {<br>    return StartExecution(env, &quot;internal/main/eval_string&quot;);<br>  }<br><br>  if (env-&gt;options()-&gt;syntax_check_only) {<br>    return StartExecution(env, &quot;internal/main/check_syntax&quot;);<br>  }<br><br>  if (env-&gt;options()-&gt;test_runner) {<br>    return StartExecution(env, &quot;internal/main/test_runner&quot;);<br>  }<br><br>  if (env-&gt;options()-&gt;watch_mode) {<br>    return StartExecution(env, &quot;internal/main/watch_mode&quot;);<br>  }<br>// this StartExecution below is what runs the myCode.js file<br>  if (!first_argv.empty() &amp;&amp; first_argv != &quot;-&quot;) {<br>    return StartExecution(env, &quot;internal/main/run_main_module&quot;);<br>  }<br><br>  if (env-&gt;options()-&gt;force_repl || uv_guess_handle(STDIN_FILENO) == UV_TTY) {<br>    return StartExecution(env, &quot;internal/main/repl&quot;);<br>  }<br><br>  return StartExecution(env, &quot;internal/main/eval_stdin&quot;);<br>}</pre><p>So we have figured out the bootstrapping process above where the input file — myCode.js as well as other important javascript files are executed. But you must be still wondering how is a c++ program (node.js) able to execute these .js files. The code below will give you some idea.</p><h4>Javascript Code Bootstrapping</h4><p>[</p><p>Things to look for in the code below which are highlighted as well</p><ol><li>CompileAndCall(context, id, arguments.size(), arguments.data(), realm)</li><li>MaybeLocal&lt;Function&gt; maybe_fn = LookupAndCompile(context, id, optional_realm)</li><li>LoadBuiltinSource(isolate, id).ToLocal(&amp;source))</li><li>MaybeLocal&lt;Function&gt; maybe_fun = ScriptCompiler::CompileFunction(context, &amp;script_source, parameters-&gt;size(), parameters-&gt;data(), 0, nullptr, options);</li><li>fn-&gt;Call(context, undefined, argc, argv)</li></ol><p>]</p><pre>//src/node_realm.cc<br><br>MaybeLocal&lt;Value&gt; Realm::ExecuteBootstrapper(const char* id) {<br>  EscapableHandleScope scope(isolate());<br>  Local&lt;Context&gt; ctx = context();<br>  MaybeLocal&lt;Value&gt; result =<br>      env()-&gt;builtin_loader()-&gt;CompileAndCall(ctx, id, this);<br><br>  // If there was an error during bootstrap, it must be unrecoverable<br>  // (e.g. max call stack exceeded). Clear the stack so that the<br>  // AsyncCallbackScope destructor doesn&#39;t fail on the id check.<br>  // There are only two ways to have a stack size &gt; 1: 1) the user manually<br>  // called MakeCallback or 2) user awaited during bootstrap, which triggered<br>  // _tickCallback().<br>  if (result.IsEmpty()) {<br>    env()-&gt;async_hooks()-&gt;clear_async_id_stack();<br>  }<br><br>  return scope.EscapeMaybe(result);<br>}</pre><pre>// src/node_builtins.cc<br><br><br><br>MaybeLocal&lt;Value&gt; BuiltinLoader::CompileAndCall(Local&lt;Context&gt; context,<br>                                                const char* id,<br>                                                Realm* realm) {<br><br>...<br><br>  return CompileAndCall(context, id, arguments.size(), arguments.data(), realm);<br>}<br><br>MaybeLocal&lt;Value&gt; BuiltinLoader::CompileAndCall(Local&lt;Context&gt; context,<br>                                                const char* id,<br>                                                int argc,<br>                                                Local&lt;Value&gt; argv[],<br>                                                Realm* optional_realm) {<br>  // Arguments must match the parameters specified in<br>  // BuiltinLoader::LookupAndCompile().<br>  MaybeLocal&lt;Function&gt; maybe_fn = LookupAndCompile(context, id, optional_realm);<br>  Local&lt;Function&gt; fn;<br>  if (!maybe_fn.ToLocal(&amp;fn)) {<br>    return MaybeLocal&lt;Value&gt;();<br>  }<br>  Local&lt;Value&gt; undefined = Undefined(context-&gt;GetIsolate());<br><br>// this is where the compiled code by v8 library (I deliberately don&#39;t use the word engine because at a basic level it&#39;s c++ library and using terms like engine makes it complicated to understand) gets executed using fn-&gt;Call(). Internally the bytecode of the javascript function is executed instruction by instruction by ignition (just a c++ code which is part of v8 library)<br>  return fn-&gt;Call(context, undefined, argc, argv);<br>}<br><br><br>MaybeLocal&lt;Function&gt; BuiltinLoader::LookupAndCompile(Local&lt;Context&gt; context,<br>                                                     const char* id,<br>                                                     Realm* optional_realm) {<br>  std::vector&lt;Local&lt;String&gt;&gt; parameters;<br>  Isolate* isolate = context-&gt;GetIsolate();<br>  // Detects parameters of the scripts based on module ids.<br>  // internal/bootstrap/realm: process, getLinkedBinding,<br>  //                           getInternalBinding, primordials<br>  if (strcmp(id, &quot;internal/bootstrap/realm&quot;) == 0) {<br>    parameters = {<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;process&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;getLinkedBinding&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;getInternalBinding&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;primordials&quot;),<br>    };<br>  } else if (strncmp(id,<br>                     &quot;internal/per_context/&quot;,<br>                     strlen(&quot;internal/per_context/&quot;)) == 0) {<br>    // internal/per_context/*: global, exports, primordials<br>    parameters = {<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;exports&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;primordials&quot;),<br>    };<br>  } else if (strncmp(id, &quot;internal/main/&quot;, strlen(&quot;internal/main/&quot;)) == 0 ||<br>             strncmp(id,<br>                     &quot;internal/bootstrap/&quot;,<br>                     strlen(&quot;internal/bootstrap/&quot;)) == 0) {<br>    // internal/main/*, internal/bootstrap/*: process, require,<br>    //                                        internalBinding, primordials<br>    parameters = {<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;process&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;require&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;internalBinding&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;primordials&quot;),<br>    };<br>  } else {<br>    // others: exports, require, module, process, internalBinding, primordials<br>    parameters = {<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;exports&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;require&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;module&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;process&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;internalBinding&quot;),<br>        FIXED_ONE_BYTE_STRING(isolate, &quot;primordials&quot;),<br>    };<br>  }<br><br>  MaybeLocal&lt;Function&gt; maybe =<br>      LookupAndCompileInternal(context, id, &amp;parameters, optional_realm);<br>  return maybe;<br>}<br><br><br><br>MaybeLocal&lt;Function&gt; BuiltinLoader::LookupAndCompileInternal(<br>    Local&lt;Context&gt; context,<br>    const char* id,<br>    std::vector&lt;Local&lt;String&gt;&gt;* parameters,<br>    Realm* optional_realm) {<br>  Isolate* isolate = context-&gt;GetIsolate();<br>  EscapableHandleScope scope(isolate);<br><br>// the LoadBuiltinSource(isolate, id) method is where the file is read from the // disk and stored in the source string<br>  Local&lt;String&gt; source;<br>  if (!LoadBuiltinSource(isolate, id).ToLocal(&amp;source)) {<br>    return {};<br>  }<br><br>...<br><br>// This &quot;ScriptCompiler::CompileFunction&quot; is the V8 method which will compile the javascript code and create a byte-code (similar to assembly but platform independent) code from it<br>  MaybeLocal&lt;Function&gt; maybe_fun =<br>      ScriptCompiler::CompileFunction(context,<br>                                      &amp;script_source,<br>                                      parameters-&gt;size(),<br>                                      parameters-&gt;data(),<br>                                      0,<br>                                      nullptr,<br>                                      options);<br><br>  // This could fail when there are early errors in the built-in modules,<br>  // e.g. the syntax errors<br>  Local&lt;Function&gt; fun;<br>  if (!maybe_fun.ToLocal(&amp;fun)) {<br>    // In the case of early errors, v8 is already capable of<br>    // decorating the stack for us - note that we use CompileFunction<br>    // so there is no need to worry about wrappers.<br>    return MaybeLocal&lt;Function&gt;();<br>  }<br><br>  // XXX(joyeecheung): this bookkeeping is not exactly accurate because<br>  // it only starts after the Environment is created, so the per_context.js<br>  // will never be in any of these two sets, but the two sets are only for<br>  // testing anyway.<br><br>  Result result = (has_cache &amp;&amp; !script_source.GetCachedData()-&gt;rejected)<br>                      ? Result::kWithCache<br>                      : Result::kWithoutCache;<br>  if (optional_realm != nullptr) {<br>    DCHECK_EQ(this, optional_realm-&gt;env()-&gt;builtin_loader());<br>    RecordResult(id, result, optional_realm);<br>  }<br><br>  if (has_cache) {<br>    per_process::Debug(DebugCategory::CODE_CACHE,<br>                       &quot;Code cache of %s (%s) %s\n&quot;,<br>                       id,<br>                       script_source.GetCachedData()-&gt;buffer_policy ==<br>                               ScriptCompiler::CachedData::BufferNotOwned<br>                           ? &quot;BufferNotOwned&quot;<br>                           : &quot;BufferOwned&quot;,<br>                       script_source.GetCachedData()-&gt;rejected ? &quot;is rejected&quot;<br>                                                               : &quot;is accepted&quot;);<br>  }<br><br>  if (result == Result::kWithoutCache &amp;&amp; optional_realm != nullptr &amp;&amp;<br>      !optional_realm-&gt;env()-&gt;isolate_data()-&gt;is_building_snapshot()) {<br>    // We failed to accept this cache, maybe because it was rejected, maybe<br>    // because it wasn&#39;t present. Either way, we&#39;ll attempt to replace this<br>    // code cache info with a new one.<br>    // This is only done when the isolate is not being serialized because<br>    // V8 does not support serializing code cache with an unfinalized read-only<br>    // space (which is what isolates pending to be serialized have).<br>    SaveCodeCache(id, fun);<br>  }<br><br>  return scope.Escape(fun);<br>}<br></pre><h4>Bindings</h4><p>In the code base you will see files like tcp_wrap.cc, stream_wrap.cc, timers_wrap.cc These files often contain the logic to interface with lower-level system capabilities like tcp connection or libraries (like libuv for asynchronous I/O). They translate JavaScript calls into these lower-level operations and handle the results or callbacks. <br>So let’s say you are writing a javascript code where you want to access the libuv library functionalities, you can do it by using these bindings</p><h4>Handles</h4><p>Handles are data structures within libuv that represent long-lived objects. They are used for various asynchronous operations.</p><p>These handles enable Node.js to interact with libuv, facilitating the asynchronous execution of tasks like I/O operations, process spawning, and timing functions.</p><p>Handles are key to the communication and coordination between Node.js and libuv, especially for managing asynchronous tasks.<br>You will often see handle objects in node.js. There’s a mapping or correspondence between these handles in libuv and their representations or counterparts in Node.js. This mapping allows Node.js to interact effectively with libuv, bridging Node.js’s JavaScript environment with libuv’s lower-level, primarily C-based functionalities. Handles in Node.js are essentially JavaScript representations or abstractions of these libuv handles, enabling Node.js applications to manage and interact with asynchronous operations and resources handled by libuv.</p><h3>Http Server Start</h3><p>In this section, we will do an end to end flow analysis to get an idea of how everything that we have learnt so far — event loop, its io_poll, bindings etc — stitch together. <br>For this, let’s take the example of createServer javascript function of http library</p><pre>// lib/http.js<br><br>function createServer(opts, requestListener) {<br>  return new Server(opts, requestListener);<br>}</pre><pre>// lib/_http_server.js<br>function Server(options, requestListener) {<br>  if (!(this instanceof Server)) return new Server(options, requestListener);<br><br>  if (typeof options === &#39;function&#39;) {<br>    requestListener = options;<br>    options = kEmptyObject;<br>  } else if (options == null) {<br>    options = kEmptyObject;<br>  } else {<br>    validateObject(options, &#39;options&#39;);<br>  }<br><br>  storeHTTPOptions.call(this, options);<br>  net.Server.call(<br>    this,<br>    { allowHalfOpen: true, noDelay: options.noDelay ?? true,<br>      keepAlive: options.keepAlive,<br>      keepAliveInitialDelay: options.keepAliveInitialDelay,<br>      highWaterMark: options.highWaterMark });<br><br>  if (requestListener) {<br>    this.on(&#39;request&#39;, requestListener);<br>  }<br><br>  // Similar option to this. Too lazy to write my own docs.<br>  // http://www.squid-cache.org/Doc/config/half_closed_clients/<br>  // https://wiki.squid-cache.org/SquidFaq/InnerWorkings#What_is_a_half-closed_filedescriptor.3F<br>  this.httpAllowHalfOpen = false;<br><br>  this.on(&#39;connection&#39;, connectionListener);<br>  this.on(&#39;listening&#39;, setupConnectionsTracking);<br><br>  this.timeout = 0;<br>  this.maxHeadersCount = null;<br>  this.maxRequestsPerSocket = 0;<br><br>  this[kUniqueHeaders] = parseUniqueHeadersOption(options.uniqueHeaders);<br>}<br></pre><p>So as you see above when we call let server = createServer(callback), we have created a server instance and added a few events on it. (We are able to add events with a simple this.on because this server instance inherits all tcp properties which inherits all eventEmitter properties)<br>But we haven’t created a network socket yet on which we will listen for incoming requests</p><p>For this from our application code we do server.listen(PORT_NUMBER) where Net.js Server.prototype.listen function is called (because http server inherits net server)</p><pre>Server.prototype.listen = function(...args) {<br>...<br>      listenInCluster(this, null, options.port | 0, 4,<br>                      backlog, undefined, options.exclusive);<br>    }<br>    return this;<br>  }<br><br>...<br><br>};</pre><p>From here as you can see from code above listenInCluster in invoked which calls _listen2 which is actually alias of setupListenHandle function<br>Here the first server handle which is a tcp handle is created using createServerHandle function. And then does const err = this._handle.listen(backlog || 511); which is what creates the socket</p><pre>// lib/net.js<br><br><br>function setupListenHandle(address, port, addressType, backlog, fd, flags) {<br>  debug(&#39;setupListenHandle&#39;, address, port, addressType, backlog, fd);<br><br>  // If there is not yet a handle, we need to create one and bind.<br>  // In the case of a server sent via IPC, we don&#39;t need to do this.<br>  if (this._handle) {<br>    debug(&#39;setupListenHandle: have a handle already&#39;);<br>  } else {<br>    debug(&#39;setupListenHandle: create a handle&#39;);<br><br>    let rval = null;<br><br>    // Try to bind to the unspecified IPv6 address, see if IPv6 is available<br>    if (!address &amp;&amp; typeof fd !== &#39;number&#39;) {<br>    // this createServerHandle returns a tcp server handle (Explained in code               //    block below).<br><br>      rval = createServerHandle(DEFAULT_IPV6_ADDR, port, 6, fd, flags);<br><br>      if (typeof rval === &#39;number&#39;) {<br>        rval = null;<br>        address = DEFAULT_IPV4_ADDR;<br>        addressType = 4;<br>      } else {<br>        address = DEFAULT_IPV6_ADDR;<br>        addressType = 6;<br>      }<br>    }<br><br>    if (rval === null)<br>      rval = createServerHandle(address, port, addressType, fd, flags);<br><br>    if (typeof rval === &#39;number&#39;) {<br>      const error = new UVExceptionWithHostPort(rval, &#39;listen&#39;, address, port);<br>      process.nextTick(emitErrorNT, this, error);<br>      return;<br>    }<br>    this._handle = rval;<br>  }<br><br>  this[async_id_symbol] = getNewAsyncId(this._handle);<br>  this._handle.onconnection = onconnection;<br>  this._handle[owner_symbol] = this;<br><br>  // Use a backlog of 512 entries. We pass 511 to the listen() call because<br>  // the kernel does: backlogsize = roundup_pow_of_two(backlogsize + 1);<br>  // which will thus give us a backlog of 512 entries.<br>  const err = this._handle.listen(backlog || 511);<br><br>  if (err) {<br>    const ex = new UVExceptionWithHostPort(err, &#39;listen&#39;, address, port);<br>    this._handle.close();<br>    this._handle = null;<br>    defaultTriggerAsyncIdScope(this[async_id_symbol],<br>                               process.nextTick,<br>                               emitErrorNT,<br>                               this,<br>                               ex);<br>    return;<br>  }<br><br>  // Generate connection key, this should be unique to the connection<br>  this._connectionKey = addressType + &#39;:&#39; + address + &#39;:&#39; + port;<br><br>  // Unref the handle if the server was unref&#39;ed prior to listening<br>  if (this._unref)<br>    this.unref();<br><br>  defaultTriggerAsyncIdScope(this[async_id_symbol],<br>                             process.nextTick,<br>                             emitListeningNT,<br>                             this);<br>}</pre><p>In the above method we are creating a tcp handle using createServerHandle ()</p><pre>function createServerHandle(address, port, addressType, fd, flags) {<br>.....<br><br> // create tcp handle which will be used to interact with libuv api<br>    handle = new TCP(TCPConstants.SERVER);<br>    isTCP = true;<br>  }<br><br>  if (address || port || isTCP) {<br>    debug(&#39;bind to&#39;, address || &#39;any&#39;);<br>    if (!address) {<br>      // Try binding to ipv6 first<br>      err = handle.bind6(DEFAULT_IPV6_ADDR, port, flags);<br>      if (err) {<br>        handle.close();<br>        // Fallback to ipv4<br>        return createServerHandle(DEFAULT_IPV4_ADDR, port);<br>      }<br>// bind the handle to the port tcp connection is listening on<br>    } else if (addressType === 6) {<br>      err = handle.bind6(address, port, flags);<br>    } else {<br>      err = handle.bind(address, port);<br>    }<br>  }<br><br>  if (err) {<br>    handle.close();<br>    return err;<br>  }<br><br>  return handle;<br>}<br></pre><p>and then assigning an onconnection function to this handle (search this highlighted line in code snipped above — this._handle.onconnection = onconnection).</p><p>After this we invoke the handle’s listen function. The listen here is basically the listen in tcp_wrap.cc (as explained in the Handles section that these javascript handles are mapped to libuv handles) and in there we pass to uv_listen of libuv a callback called OnConnection.</p><pre>// src/tcp_wrap.cc<br><br>void TCPWrap::Listen(const FunctionCallbackInfo&lt;Value&gt;&amp; args) {<br><br>...<br><br>  int err = uv_listen(reinterpret_cast&lt;uv_stream_t*&gt;(&amp;wrap-&gt;handle_),<br>                      backlog,<br>                      OnConnection);<br>  args.GetReturnValue().Set(err);<br>}<br><br></pre><p>This callback — OnConnection is defined in connection_wrap.cc where the OnConnection function does this -</p><ol><li>Converts the data received as a parameter to a clientHandle and sets in argv</li><li>Does wrap_data-&gt;MakeCallback(env-&gt;onconnection_string(), arraysize(argv), argv); i.e it calls the net.js onconnection function (the same one which had assigned to the tcp handle’s onconnection attribute in the code above.</li></ol><p>And uv_listen of libuv does this</p><pre>//deps/uv/src/unix/stream.c<br><br>int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) {<br><br>   ...<br><br>    err = uv__tcp_listen((uv_tcp_t*)stream, backlog, cb);<br>    break;<br><br>    ...<br>    uv__handle_start(stream);<br><br>  return err;<br>}<br><br><br>// deps/uv/src/unix/tcp.c<br><br>int uv__tcp_listen(uv_tcp_t* tcp, int backlog, uv_connection_cb cb) {<br>  <br>  ...<br><br>  tcp-&gt;connection_cb = cb;<br>  tcp-&gt;flags |= UV_HANDLE_BOUND;<br><br>  /* Start listening for connections. */<br>  tcp-&gt;io_watcher.cb = uv__server_io;<br>  uv__io_start(tcp-&gt;loop, &amp;tcp-&gt;io_watcher, POLLIN);<br><br>  return 0;<br>}<br><br>//deps/uv/src/unix/core.c<br><br>void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {<br> ...<br><br>// add it to the watcher queue which we saw in the event loop section will be used in the io_poll phase <br><br>  if (uv__queue_empty(&amp;w-&gt;watcher_queue))<br>    uv__queue_insert_tail(&amp;loop-&gt;watcher_queue, &amp;w-&gt;watcher_queue);<br><br>  if (loop-&gt;watchers[w-&gt;fd] == NULL) {<br>    loop-&gt;watchers[w-&gt;fd] = w;<br>    loop-&gt;nfds++;<br>  }<br>}</pre><p>Lets also look at the <strong>onconnection</strong> javascript function which we had passed to the libuv uv_listen method</p><pre>// lib/net.js<br><br>function onconnection(err, clientHandle) {<br>  const handle = this;<br>  const self = handle[owner_symbol];<br><br>  debug(&#39;onconnection&#39;);<br><br>  if (err) {<br>    self.emit(&#39;error&#39;, new ErrnoException(err, &#39;accept&#39;));<br>    return;<br>  }<br><br>  if (self.maxConnections != null &amp;&amp; self._connections &gt;= self.maxConnections) {<br>    if (clientHandle.getsockname || clientHandle.getpeername) {<br>      const data = { __proto__: null };<br>      if (clientHandle.getsockname) {<br>        const localInfo = { __proto__: null };<br>        clientHandle.getsockname(localInfo);<br>        data.localAddress = localInfo.address;<br>        data.localPort = localInfo.port;<br>        data.localFamily = localInfo.family;<br>      }<br>      if (clientHandle.getpeername) {<br>        const remoteInfo = { __proto__: null };<br>        clientHandle.getpeername(remoteInfo);<br>        data.remoteAddress = remoteInfo.address;<br>        data.remotePort = remoteInfo.port;<br>        data.remoteFamily = remoteInfo.family;<br>      }<br>      self.emit(&#39;drop&#39;, data);<br>    } else {<br>      self.emit(&#39;drop&#39;);<br>    }<br>    clientHandle.close();<br>    return;<br>  }<br><br>  const socket = new Socket({<br>    handle: clientHandle,<br>    allowHalfOpen: self.allowHalfOpen,<br>    pauseOnCreate: self.pauseOnConnect,<br>    readable: true,<br>    writable: true,<br>    readableHighWaterMark: self.highWaterMark,<br>    writableHighWaterMark: self.highWaterMark,<br>  });<br><br>  if (self.noDelay &amp;&amp; clientHandle.setNoDelay) {<br>    socket[kSetNoDelay] = true;<br>    clientHandle.setNoDelay(true);<br>  }<br>  if (self.keepAlive &amp;&amp; clientHandle.setKeepAlive) {<br>    socket[kSetKeepAlive] = true;<br>    socket[kSetKeepAliveInitialDelay] = self.keepAliveInitialDelay;<br>    clientHandle.setKeepAlive(true, self.keepAliveInitialDelay);<br>  }<br><br>  self._connections++;<br>  socket.server = self;<br>  socket._server = self;<br>  self.emit(&#39;connection&#39;, socket);<br>  if (netServerSocketChannel.hasSubscribers) {<br>    netServerSocketChannel.publish({<br>      socket,<br>    });<br>  }<br>}<br><br></pre><p>This means whenever libuv gets a connection request on this socket it calls this onconnection which does <strong>self.emit(‘connection’, socket)</strong> . This will trigger the ‘connection’ event’s listener and pass the ‘socket’ object to this listener. Remember we had attached a listener to ‘connection’ event in http.js#createServer method above.<br>Also the clientHandle here is the same as passed by tcp_wrap::OnConnection function and it gets passed to new Socket({..}) constructor, as can be seen in code above, which eventually calls this.read(0)</p><p>The new Socket does something important. It has — stream.Duplex.call(this, options);</p><p>This means that the socket object inherits all the functions of the Duplex class which has all the methods of readable and writable class.</p><pre>// lib/net.js<br><br>function Socket(options) {<br> ....<br>  stream.Duplex.call(this, options);<br> ....<br>  // only the part of code relevant to the explanation is shown below. But reader can go through the whole code by navigation to the lib/net.js file<br><br>  initSocketHandle(this);<br><br>  this._pendingData = null;<br>  this._pendingEncoding = &#39;&#39;;<br><br>  // If we have a handle, then start the flow of data into the<br>  // buffer.  if not, then this will happen when we connect<br>  if (this._handle &amp;&amp; options.readable !== false) {<br>    if (options.pauseOnCreate) {<br>      // Stop the handle from reading and pause the stream<br>      this._handle.reading = false;<br>      this._handle.readStop();<br>      this.readableFlowing = false;<br>    } else if (!options.manualStart) {<br>      this.read(0);<br>    }<br>  }<br><br>.....<br>}<br></pre><pre>// lib/net.js<br><br><br>Socket.prototype.read = function(n) {<br>  if (this[kBuffer] &amp;&amp; !this.connecting &amp;&amp; this._handle &amp;&amp;<br>      !this._handle.reading) {<br>    tryReadStart(this);<br>  }<br><br> <br>  return stream.Duplex.prototype.read.call(this, n);<br>};</pre><p>So we call here stream.Duplex.protoype.read.call(this,0) -&gt; because n=0</p><pre>// lib/internal/streams/readable.js<br><br>Readable.prototype.read = function(n) {<br>.....<br>// Call internal read method<br>    try {<br>      this._read(state.highWaterMark);<br>    } catch (err) {<br>      errorOrDestroy(this, err);<br>    }<br>.....<br>}</pre><p>Because of function overriding, this highlighted this._read is actually gonna call the net.js _read</p><pre>Socket.prototype._read = function(n) {<br>  debug(<br>    &#39;_read - n&#39;, n,<br>    &#39;isConnecting?&#39;, !!this.connecting,<br>    &#39;hasHandle?&#39;, !!this._handle,<br>  );<br><br><br>  if (this.connecting || !this._handle) {<br>    debug(&#39;_read wait for connection&#39;);<br>    this.once(&#39;connect&#39;, () =&gt; this._read(n));<br>  } else if (!this._handle.reading) {<br>    tryReadStart(this);<br>  }<br>};<br>function tryReadStart(socket) {<br>  // Not already reading, start the flow<br>  debug(&#39;Socket._handle.readStart&#39;);<br>  socket._handle.reading = true;<br>  const err = socket._handle.readStart();<br>  if (err)<br>    socket.destroy(new ErrnoException(err, &#39;read&#39;));<br>}</pre><p>socket._handle.readStart() is mapped to libuv’s uv_read_start as explained earlier in the handles section</p><pre>// src/stream_wrap.cc <br><br>int LibuvStreamWrap::ReadStart() {<br>  return uv_read_start(<br>      stream(),<br>      [](uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) {<br>        static_cast&lt;LibuvStreamWrap*&gt;(handle-&gt;data)<br>            -&gt;OnUvAlloc(suggested_size, buf);<br>      },<br>      [](uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) {<br>        LibuvStreamWrap* wrap = static_cast&lt;LibuvStreamWrap*&gt;(stream-&gt;data);<br>        TryCatchScope try_catch(wrap-&gt;env());<br>        try_catch.SetVerbose(true);<br>        wrap-&gt;OnUvRead(nread, buf);<br>      });<br>}<br><br>// OnUvRead gets invoked once there is data available on the socket to be read.<br>//This then calls the which through an event listener mechanism executes a javascript OnStreamRead function which.</pre><p>uv_read_start is the libuv method which pushes this stream object (which is essentially a transformed form of the js socket object with file descriptor etc) to the event loop watchers_queue so that libuv event loop keeps checking for data on this file descriptor during the uv_io_poll phase</p><pre>// deps/uv/src/unix/stream.c<br><br>int uv__read_start(uv_stream_t* stream,<br>                   uv_alloc_cb alloc_cb,<br>                   uv_read_cb read_cb) {<br><br>...<br><br><br> // read_cb is the javascript callback essentially<br>  stream-&gt;read_cb = read_cb;<br>  stream-&gt;alloc_cb = alloc_cb;<br><br>// starts listening for incoming data on this file descriptor<br>  uv__io_start(stream-&gt;loop, &amp;stream-&gt;io_watcher, POLLIN);<br>  uv__handle_start(stream);<br>  uv__stream_osx_interrupt_select(stream);<br><br><br>  return 0;<br>}<br></pre><p>Note : Watcher queue is just a double link list with watcher objects being the actual nodes. Watcher object has watcher_queue attribute which has next and previous pointers which point to the next or previous watcher object in this watcher link list</p><p>uv__handle_start — marks this handle as active handle because only active handles are watched.</p><p>OnUvRead gets invoked once there is data available on the socket to be read.</p><p>This then through an event listener mechanism executes a javascript OnStreamRead function which.</p><pre>//src/stream_wrap.cc<br><br><br>Maybe&lt;void&gt; LibuvStreamWrap::OnUvRead(ssize_t nread, const uv_buf_t* buf) {<br>  .......<br><br>  EmitRead(nread, *buf);<br>  return JustVoid();<br>}</pre><pre>// src/stream_base-inl.h<br><br>void StreamResource::EmitRead(ssize_t nread, const uv_buf_t&amp; buf) {<br>  DebugSealHandleScope seal_handle_scope;<br>  if (nread &gt; 0)<br>    bytes_read_ += static_cast&lt;uint64_t&gt;(nread);<br>  listener_-&gt;OnStreamRead(nread, buf);<br>}</pre><pre>// lib/internal/stream_base_commons.js<br><br>function onStreamRead(arrayBuffer) {<br>  const nread = streamBaseState[kReadBytesOrError];<br><br>  const handle = this;<br>  const stream = this[owner_symbol];<br><br>  stream[kUpdateTimer]();<br><br>  if (nread &gt; 0 &amp;&amp; !stream.destroyed) {<br>   ...<br>    } else {<br>      const offset = streamBaseState[kArrayBufferOffset];<br>      const buf = new FastBuffer(arrayBuffer, offset, nread);<br>      result = stream.push(buf);<br>    }<br>    ...<br>}</pre><p>So here stream.push(buf) happens where buf is the data. Steam is the socket object which has inherited functions of readable.js remember. And push is implemented in readable class.</p><pre>//lib/internal/streams/readable.js<br>Readable.prototype.push = function(chunk, encoding) {<br>  debug(&#39;push&#39;, chunk);<br><br><br>  const state = this._readableState;<br>  return (state[kState] &amp; kObjectMode) === 0 ?<br>    readableAddChunkPushByteMode(this, state, chunk, encoding) :<br>    readableAddChunkPushObjectMode(this, state, chunk, encoding);<br>};<br><br><br><br>// This if you follow the code from here calls addChunk method<br>function addChunk(stream, state, chunk, addToFront) {<br>  if ((state[kState] &amp; (kFlowing | kSync | kDataListening)) === (kFlowing | kDataListening) &amp;&amp; state.length === 0) {<br>    // Use the guard to avoid creating `Set()` repeatedly<br>    // when we have multiple pipes.<br>    if ((state[kState] &amp; kMultiAwaitDrain) !== 0) {<br>      state.awaitDrainWriters.clear();<br>    } else {<br>      state.awaitDrainWriters = null;<br>    }<br><br><br>    state[kState] |= kDataEmitted;<br>    stream.emit(&#39;data&#39;, chunk);<br>  } else {<br>    // Update the buffer info.<br>    state.length += (state[kState] &amp; kObjectMode) !== 0 ? 1 : chunk.length;<br>    if (addToFront) {<br>      if (state.bufferIndex &gt; 0) {<br>        state.buffer[--state.bufferIndex] = chunk;<br>      } else {<br>        state.buffer.unshift(chunk); // Slow path<br>      }<br>    } else {<br>      state.buffer.push(chunk);<br>    }<br><br><br>    if ((state[kState] &amp; kNeedReadable) !== 0)<br>      emitReadable(stream);<br>  }<br>  maybeReadMore(stream, state);<br>}</pre><p>And, as the reader can see, here we emit — ‘data’ event</p><p>Now we had already during server initialization attached a listener — connectionListener on ‘connections’ event. And ‘connections’ event get emitted in our lib/net.js#onconnection method. So connectionListener is called which by invoking a couple of functions (you will find if you follow the code) has attached a callback with ‘data’ event.</p><p>[start from lib/_http_server.js#Server(options, requestListener){ … this.on(‘connection’, connectionListener); … }]</p><pre>// lib/_http_server.js<br><br><br>function connectionListener(socket) {<br>  defaultTriggerAsyncIdScope(<br>    getOrSetAsyncId(socket), connectionListenerInternal, this, socket,<br>  );<br>}<br><br>function connectionListenerInternal(server, socket) {<br>......<br><br>  state.onData = socketOnData.bind(undefined,<br>                                   server, socket, parser, state);<br>......<br>   socket.on(&#39;data&#39;, state.onData);<br>......<br>  parser.onIncoming = parserOnIncoming.bind(undefined,<br>                                            server, socket, state);<br>.......<br><br> }<br><br>function socketOnData(server, socket, parser, state, d) {<br>  assert(!socket._paused);<br>  debug(&#39;SERVER socketOnData %d&#39;, d.length);<br><br>  const ret = parser.execute(d);<br>  onParserExecuteCommon(server, socket, parser, state, ret, d);<br>}<br><br></pre><p>This parser.execute is through bindings in node_http_parser.cc get called as a c++ method and then it calls its own on_headers_complete method which then calls the js parserOnHeadersComplete function which in its last line calls parser.onIncoming(incoming, shouldKeepAlive);</p><p>And if you were reading carefully you must have realized that we had bound parser.onIncoming to parserOnIncoming javascript method in our connectionListenerInternal method</p><pre>// lib/_http_server.js<br><br>// The following callback is issued after the headers have been read on a<br>// new message. In this callback we setup the response object and pass it<br>// to the user.<br>function parserOnIncoming(server, socket, state, req, keepAlive) {<br><br> ...<br><br>  if (!handled) {<br>    server.emit(&#39;request&#39;, req, res);<br>  }<br><br>  return 0;  // No special treatment.<br>}<br></pre><p>parserOnIncoming calls the ‘request’ event which has our original callback (which we passed during createServer call) attached to it — check the createServer method.</p><p>So, we close the loop — from calling the createServer function of node.js, then listening on the port for incoming connections using a socket and receiving data on that socket and finally executing the callback that we had passed to the createServer function earlier.</p><h3>References</h3><p><a href="https://github.com/nodejs/node/blob/main/src/node_main.cc#L96"><em>https://github.com/Node.js/node/blob/main</em></a></p><h3>Authors</h3><p>Piyush Shukla — is Tech Manager at Zupee. He aims to be just a bit better every day, learn from his peers, leaders and in fact from everyone, and contribute in any small or big but meaningful way to the responsibilities he carries.</p><p>We’d love to hear your thoughts, experiences, or even curiosities on this subject. Engage with us in the comments section below. If you found value in this article, please share it across. Let’s foster a community where knowledge and ideas flow freely!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbcb430c3908" width="1" height="1" alt=""><hr><p><a href="https://tech.zupee.com/do-you-really-really-know-nodejs-cbcb430c3908">Do you really really know nodejs?</a> was originally published in <a href="https://tech.zupee.com/">Zupee TechLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zupee Apps’ ‘plug-and-play design’ ensures Cross-App Liquidity]]></title>
            <link>https://tech.zupee.com/zupee-apps-plug-and-play-design-ensures-cross-app-liquidity-c53bfafbebad?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/c53bfafbebad</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[game-design]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 04:13:36 GMT</pubDate>
            <atom:updated>2023-09-26T04:14:27.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*v1kXKk5RB4O7QfE-ZYuGoQ.jpeg" /></figure><h3>Introduction</h3><p>As we grew from having one gaming application to having multiple casual gaming apps, we felt a need to bring these apps under a common umbrella platform. This improved the discoverability of our games and also provided users with more options to develop and explore their gaming interests. Delving into this venture required meticulous planning and precise execution, ensuring that our vast user base experienced a smooth transition.</p><p>Our design and decision making were primary guided by following criteria</p><ul><li>Seamless user experience during and after this transition</li><li>Designing for scale</li><li>Plug and Play of Games</li><li>Shared Liquidity across any application — Anybody can be matched with anybody across ios, android, app distributions etc</li></ul><p>This post will walk you through this transformative journey, our approach to the problem, the challenges faced and our learnings.</p><h3>Table of Contents : What’s in store for you :</h3><p>Section 1: The Problem</p><p>Section 2: Our Approach</p><p>Section 3: Implementation Details</p><p>Section 4: Challenges Faced</p><p>Section 5: Lessons Learned</p><p>Section 6: Conclusion</p><h3>The Problem</h3><p>There were 4 key requirements as mentioned briefly in the introduction :</p><ul><li>Seamless user experience during and after this transition — Guided and gradual migration from exposing one game to exposing multiple games.</li><li>Designing for scale — We ensured that all bottlenecks to scaling games and scaling users on individual games as well as number of games on platform — should be removed. All the games must be completely decoupled and must not impact each other in any way. Hence if one game has some issue, it should impact the game experience of other games running.</li><li>Plug and Play of Games — Since our app is majorly distributed through the website, we wanted to limit the updates to the app. Introducing a new game will automatically trigger an update in the normal scenario. We wanted to completely avoid that. Any new game should be able to be introduced to the customers without the need of updating the app. This should happen both from frontend and backend.</li><li>Enabling Cross app gameplay — We wanted to make sure that anybody can match and play with anybody even if one is playing on android, the other is on ios, the other one is on another version of the app and the other one is on webapp.</li></ul><h3>Approach</h3><h4>Seamless transition to standalone to platform</h4><p>To provide a seamless user experience, we adopted a phased introduction approach on the current running production app. Initially, users were presented solely with the familiar game. Over time, we subtly introduced additional games, ensuring a smooth and familiar progression for our audience.</p><h4>Designing for scale</h4><p>We aimed for scalability on two fronts: number of games and user engagement. It was essential that adding countless games or a surge in player counts for any game wouldn’t strain the App Platform or affect other sub-games.</p><p>The techniques we used to achieve this were broadly</p><ol><li>Decouple gameplay with platform: We strictly decoupled our platform infrastructure, responsible for all our non game journeys from the game infrastructure, which manages gameplay mechanics like table assignments, game starts, moves, and turns. This thorough separation spans from load balancers, target groups, and servers, right down to databases, queues, and caches. Given our existing commitment to a microservice architecture, this choice was a straightforward one.</li></ol><p>2. Bi directional information exchange between the Zupee Platform Services and Games Servers and no communication directly between the games .</p><p>a. While our architecture’s design predominantly adheres to a top-down model from Platform Services to Game Services, we recognized the value of bi-directional communication for specific use-cases. One primary motivation was the need for real-time data — to understand the state of a game instantly or to manage caching more efficiently. Instead of continuously polling the games for status, which is resource-intensive, we implemented webhooks in our platform services.<br>By doing so, games can instantly notify the platform of any significant events or changes in their state. This approach ensures that the platform is always informed without unnecessary overhead, improving both performance and user experience. It also underpins our ability to provide users with up-to-date game information, enhancing the overall dynamism of our Zupee App.</p><p>b. There’s no direct communication channel between games; any game requiring information about the state of another game would need to obtain it through the Platform services. This deliberate design choice serves a dual purpose:</p><ul><li><strong>Independence in Management and Scaling</strong>: Each game operates in its own isolated environment. This allows our team to manage, update, and scale each game independently. Whether it’s adjusting to changing user demand or rolling out game-specific updates, the operations on one game have no adverse effect on others.</li><li><strong>Centralized State Management</strong>: By channeling state information through the Platform services, we maintain a single source of truth. This not only simplifies data management but also enhances the reliability of state information for all games.</li></ul><h3>Plug and Play of Games</h3><p>Adding a game to the platform feels akin to inserting a USB device into a computer — plug-and-play. So to add a new game to our platform -</p><ol><li>Develop the game, i.e game subAPK and backend services. Once a game is developed and ready for deployment, all we need to do is spin up its gameplay servers.</li></ol><p>2. Once servers are initialized, the game’s vital details, including its name, and endpoints, are communicated to the Zupee App. This ensures that the integration is seamless, without necessitating massive overhauls or changes to the existing Zupee App infrastructure.</p><p>3. Zupee App simply lists this new game through a config change.</p><p>4. Each game is encapsulated as a sub-APK, installing only upon user demand. This keeps the platform lightweight and adaptive.</p><p>5. Once the gameplay starts the <strong>SubAPK directly communicates with the game servers for gameplay without any involvement of the Zupee Platform services.</strong> Thus there is very little to almost zero coupling between the Zupee Platform App backend services, Zupee App APK and the game SubAPK and game services.</p><p>This architecture also provides maximum flexibility for both frontend APKs and backend services. Example — some of our subApp APKs are developed using Kotlin, some using Unity and recently we launched a game built using PlayCanvas WebGL. This is true for backend services as well where some of our games are deployed on Kubernetes pods and some are on plain docker containers.</p><p>Our decoupled structure allows us to even integrate third-party games. All that is needed is to provide them with two essential webhooks for monetary transactions — one to deduct money from a user’s wallet within our ecosystem and another to credit winnings, while the gameplay can happen at their servers.</p><h3>Shared Liquidity</h3><p>To facilitate interaction between standalone game users and those on the Zupee App, we adopted a shared gameplay infrastructure. This integration became feasible for two main reasons:</p><ul><li>Our clear distinction between platform services and game-specific services.</li><li>The design permits frontend APKs, be it Zupee or standalone game apps, to directly interface with gameplay servers. All that’s required is relaying the gameplay server endpoints to these APKs, ensuring smooth connectivity before game commencement.</li></ul><p>By sharing gameplay infra, we also guarantee that irrespective of the access point — be it a standalone game or the Zupee App — the gaming experience remains consistent. Whether it’s the gameplay mechanics, real-time updates, or the competitive environment, every player gets an identical experience. This ensures that no user feels at a disadvantage or witnesses a different gameplay variant simply because of the access portal they’ve chosen.</p><p>Also until a game amassed a sizeable user base on the Zupee App, its standalone app provided a pool of users for Zupee App players to match with. This not only enriched the gameplay experience but also safeguarded Zupee App players from potential misconduct like collusion and fraud.</p><h3>Implementation Details</h3><h3>Components and Infrastructure</h3><ul><li>Frontend Components — A platform skeleton APK and multiple subAPKs for individual games</li><li>Backend Infrastructure (only relevant ones are listed here) -</li><li>Gateway service called super app service</li><li>User Service and corresponding data store</li><li>Wallet Service and Payment Service and corresponding data store</li><li>Gameplay Service for all games</li></ul><h3>Flow</h3><ol><li>User click to play a game on app</li><li>Frontend makes a join request to the Gateway Service — Superapp Service</li><li>Superapp Service registers the join request by calling the appropriate gameplay service</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sVYAC6e1W2wpd2jE" /></figure><p>4. The worker service is responsible for matchmaking and selects the game servers via round robin algorithm to play the game. The information is passed to the app which then connects to the gameplay servers.</p><p>5. Game SubApk takes over and connects to gameplay web socket servers and game starts and continues through direct communication between subAPK and gameplay servers</p><p>6. At the end of the game, the gameplay server pushes winner info to platform wallet service which credits rewards accordingly to the winning users. This is the bi directional communication which was earlier discussed under the Approach section. SubApk hands back the control to parent Zupee App.</p><p>7. Notice at no point do the games communicate with each other or are even aware of their presence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9noeO6AJ3m8pjbRO" /></figure><p>8. Also notice that both the Zupee App Frontend and the Standalone Game App’s users play on the same server and so are able to match with each other.</p><h3>Adding a new Game</h3><p>Adding a new game requires developing a new game, both frontend APK and backend service and integrating it into the Zupee ecosystem. Integration is very convenient and only requires minimal changes to existing ecosystem such as listing the game on the Zupee app and adding suitable endpoints mapped to game name at the backend services</p><p>Diagram below describes the addition of new games to our ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MngP974Er-WgrVZw" /></figure><h3>Challenges Faced</h3><ul><li><strong>Navigating Uncharted Waters</strong>: Venturing into a Super App model from standalone games was a substantial risk of running into unknowns both from the user behaviour perspective as well as technical aspects. To solve this we executed a proof-of-concept by upgrading another game into a semi-platform app housing two games. This highlighted key issues such as business configuration challenges, timeouts issue on external Application Load Balancer (ALB) calls as well as key behaviour insights of users.</li><li><strong>Performance on scale</strong>: The platform POC wasn’t sufficient to gauge how our design would perform on scale as the scale of our main game app was on an altogether different level. It was paramount to ensure our architecture could handle the influx of a growing user base. To solve this a production test environment was set up for scale testing.</li><li><strong>Communication between Games: </strong>One challenge we encountered was ensuring a user’s game was started only when they weren’t already engaged in another game. Adhering to our decision to prevent direct game-to-game communication, we centralized gameplay states within our gateway service. Games updated their status at the gateway service and other games could then query the gateway service for this status when needed.</li><li><strong>Parallel Developments</strong>: As we developed the platform App, new features were simultaneously being added to existing apps and backend services. This potential conflict and potential backward compatibility issue was resolved by establishing a separate repository for the platform app. This allowed us to roll out the app to our existing user base without requiring any downtime.</li></ul><h3>Lessons Learned</h3><ul><li>The POC Advantage: The upgrade experiment was a revelation. We identified crucial pain points early, like the timeouts on external ALB calls, which was later rectified by leveraging internal load balancers. This underscores the value of testing in real-world conditions. It’s one thing to design a system on paper and another to see it perform under live user conditions.</li><li>Segregation Benefits: The complete decoupling between games emerged as a boon. Not only did it ensure that issues in one game didn’t spill over to another. This containment means that while one game might be down or under maintenance, the rest of the platform remains unaffected.<br>It also meant that if one game experienced a surge in users, only its specific servers needed to be scaled up. This dynamic scaling is both cost-effective and efficient.<br>It also played a large role in enabling plug and play of games</li><li>Seamless Transition is Vital: While transitioning one game players to the platform App, we recognized the importance of making change gradual. By initially exposing players to familiar content and slowly introducing new games, we could maintain user trust and engagement.</li><li>Migration Challenges: Migrating to the new architecture posed initial challenges for developers. The lesson here underscored the importance of gradual transitions, comprehensive training, robust documentation, and fostering a supportive environment for smoother migrations. This is something which in hindsight could have been planned better.</li></ul><h3>Conclusion</h3><p>In our quest to transition from a single-game platform to a robust superapp, the Zupee journey has been both challenging and enlightening. At the heart of this evolution was the problem of seamlessly integrating multiple games without compromising on user experience or system efficiency. Our approach to decoupling services, establishing a plug-and-play architecture, and prioritizing user communication has proven to be the game-changer, ensuring a seamless and enhanced user experience.</p><p>The significance of this transformation isn’t merely technical; it’s about reshaping how users interact with our platform. By offering a multitude of gaming options under one umbrella while ensuring each game’s independent functionality, we’ve addressed both scalability and user-centricity. Our strategy’s success, particularly the decoupling of services, stands as a testament to its viability for future app developers looking to expand without diluting user experience.</p><p>We invite our readers to dive deep into the concepts discussed here. Whether you’re an app developer facing similar challenges or a curious tech enthusiast, exploring the intricacies of such a transition can offer valuable insights. Embracing change, learning from challenges, and innovating solutions is the path forward, and we at Zupee are excited to be at the forefront of this journey.</p><h3>References</h3><ol><li>Newman, S. (2015). Building Microservices: Designing Fine-Grained Systems. O’Reilly Media.</li><li><a href="https://en.wikipedia.org/wiki/Law_of_Demeter">https://en.wikipedia.org/wiki/Law_of_Demeter</a></li></ol><h3>Authors</h3><p><strong>Piyush Shukla</strong> — is tech lead at Zupee. He aims to be just a bit better every day, learn from his peers, leaders and in fact from everyone, and contribute in any small or big but meaningful way to the responsibilities he carries.</p><p>We’d love to hear your thoughts, experiences, or even curiosities on this subject. Engage with us in the comments section below. If you found value in this article, please share it widely. Let’s foster a community where knowledge and ideas flow freely!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c53bfafbebad" width="1" height="1" alt=""><hr><p><a href="https://tech.zupee.com/zupee-apps-plug-and-play-design-ensures-cross-app-liquidity-c53bfafbebad">Zupee Apps’ ‘plug-and-play design’ ensures Cross-App Liquidity</a> was originally published in <a href="https://tech.zupee.com/">Zupee TechLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abolish maintenance hours: Scaling MongoDB without any downtime]]></title>
            <link>https://tech.zupee.com/abolish-maintenance-hours-scaling-mongodb-without-any-downtime-2d70f18e80b0?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d70f18e80b0</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 09:45:15 GMT</pubDate>
            <atom:updated>2023-09-16T08:13:05.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Lg0QSYGa2Fn4J1tXsCkV5Q.jpeg" /></figure><h3>Introduction</h3><p>Seamless, uninterrupted, and reliable — these are the attributes we seek when it comes to managing our <strong>MongoDB</strong> databases. In a world where downtime can translate to lost revenue, diminished user trust, and disrupted operations, the quest for achieving zero downtime becomes paramount. Enter <strong>MongoShake</strong>, a powerful tool developed by Alibaba that promises to revolutionize your database management strategy. In this guide, we’ll embark on a journey through the realms of zero downtime, delving into the art of splitting MongoDB databases using the MongoShake tool. From understanding its core principles to mastering its implementation, this guide will equip you with the insights you need to ensure your MongoDB deployments remain resilient, available, and always operational.</p><p>By mastering the art of splitting MongoDB databases with MongoShake, organizations can confidently make crucial changes to their databases without disrupting their services. This guide aims to unlock the path to achieving zero downtime, enabling readers to understand the significance of uninterrupted database operations and providing them with the knowledge needed to implement a robust database management strategy. Whether you’re an IT professional, a database administrator, or a business owner, embracing the insights shared in this guide can lead to improved operational resilience, enhanced user experiences, and a competitive edge in today’s 24/7 digital ecosystem.</p><h3>The Problem</h3><p>As our customer base grew rapidly and massively, we encountered a significant hitch: our single MongoDB replica set was struggling to handle the increasing traffic from various microservices. With our business growing and diverse types of data pouring in, we realized we needed a tech fix. The mix of many microservices, different data needs, and the complexity of dealing with one huge database was causing a real headache.</p><p>So, we had a choice: either deal with the downtime that came with splitting up the database or find a clever solution to move parts of the database to new, smaller MongoDB setups for each microservice. This alternative meant no downtime, better performance, and the ability to manage different services separately.</p><h3>The Approach</h3><p>Our strategy to conquer the challenges posed by our growing MongoDB setup and the need for database separation was a step-by-step process, carefully orchestrated to ensure smooth transitions and minimal disruptions. Let’s delve into our approach by diving into the technical details of tasks that guided our path:</p><p><strong>1. Moving MongoDB access code through DAO class</strong></p><p>We began by reorganizing our codebase. By centralizing all interactions with MongoDB through a dedicated Data Access Object (DAO) class, we enhanced the maintainability and flexibility of our code.</p><p>To enhance data isolation, we made sure that direct access to the collections related to the micro service was removed from different parts of our code. This step streamlined data management and reduced dependencies. Other services can make an API call to the micro service in case they need data from the service collection.</p><p><strong>2. Setting up a new MongoDB cluster for microservice in PT setup</strong></p><p>In our pre-production (PT) environment, we established a fresh MongoDB cluster specifically dedicated to handling the micro service. This cluster served as a controlled environment for testing and fine-tuning our database separation plan.</p><p><strong>3. Establishing a new MongoDB cluster for microservice in production</strong></p><p>The same approach was replicated in our production environment. We introduced a new MongoDB cluster solely for the microservice, ensuring a smooth transition by meticulously migrating data.</p><p><strong>4. Data migration and real-time syncing:</strong></p><p>With the isolated clusters in place, we embarked on migrating data from the existing setup to the new clusters. To ensure data consistency, we implemented mechanisms for real-time synchronization between the old and new setups.</p><p><strong>5. Rigorous performance testing on the PT cluster</strong></p><p>The freshly created PT cluster underwent intensive stress testing. This process evaluated the cluster’s responsiveness, resilience, and capacity to handle the unique demands of the micro service.</p><p><strong>6. Production rollout of the micro service</strong></p><p>Having validated the setup through testing, we proceeded with the production rollout phase</p><p><strong>7. Post-migration data cleanup</strong></p><p>After the migration, we meticulously cleaned up the data environment. We ensured that any remnants from the old setup were effectively managed, and irrelevant data was purged.</p><p><strong>8. Establishing a backup schedule</strong></p><p>To safeguard against data loss, we instituted a routine backup schedule. This proactive measure minimized the risk of data-related mishaps and allowed for swift disaster recovery if necessary, similar to our main monolith replica set.</p><p>By following this methodical approach, guided by the technical intricacies of the Jira sub-tasks, we successfully navigated the terrain of database separation. From code restructuring to data migration, rigorous testing, and ongoing management, our journey with MongoShake and these targeted steps empowered us to achieve zero downtime, enhance performance, and effectively manage our databases across the microservices landscape.</p><h3>Implementation Details</h3><p><strong>Our Practical Approach with MongoShake</strong></p><p>In our quest for smooth database migration and replication using MongoShake, we followed a clear-cut plan. Here’s a straightforward rundown of how we put MongoShake to work, emphasizing its practical applications in achieving seamless transitions and uninterrupted operations.</p><p><strong>1. Optimizing Hardware and Setup</strong></p><p>We prioritized performance by opting for a beefy 16-core machine. This decision allowed us to handle multiple tasks simultaneously, especially when working with numerous worker nodes. This approach distributed the workload efficiently, ensuring a smooth data migration process.</p><p><strong>2. Customizing the Configuration File</strong></p><p>Our configuration file was tailored to match our migration goals. Here’s a glimpse of the essential settings we used:</p><pre>conf.version = 9<br>id = mongoshake<br>master_quorum = false<br>full_sync.http_port = 9101<br>incr_sync.http_port = 9100<br>system_profile_port = 9200<br>log.level = info<br>log.dir =<br>log.file = collector.log<br>log.flush = false<br>sync_mode = incr<br>mongo_urls = &lt;source mongo srv&gt;<br>mongo_cs_url =<br>mongo_s_url =<br>tunnel = direct<br>tunnel.address = &lt;destination mongo primary srv&gt;<br>tunnel.message = raw<br>tunnel.kafka.partition_number = 1<br>tunnel.json.format =<br>mongo_connect_mode = secondaryPreferred<br>filter.namespace.black =<br>filter.namespace.white =<br>filter.pass.special.db =<br>filter.ddl_enable = false<br>filter.oplog.gids = false<br>checkpoint.storage.url = &lt;destination mongo primary srv&gt;<br>checkpoint.storage.db = mongoshake<br>checkpoint.storage.collection = ckpt_default<br>checkpoint.start_position = 1970–01–01T00:00:00Z<br>transform.namespace =<br>full_sync.reader.collection_parallel = 64<br>full_sync.reader.write_document_parallel = 2048<br>full_sync.reader.document_batch_size = 5096<br>full_sync.reader.read_document_count = 0<br>full_sync.collection_exist_drop = true<br>full_sync.create_index = background<br>full_sync.executor.insert_on_dup_update = false<br>full_sync.executor.filter.orphan_document = false<br>full_sync.executor.majority_enable = false<br>incr_sync.mongo_fetch_method = oplog<br>incr_sync.change_stream.watch_full_document = false<br>incr_sync.oplog.gids =<br>incr_sync.shard_key = collection<br>incr_sync.shard_by_object_id_whitelist =<br>incr_sync.worker = 64<br>incr_sync.tunnel.write_thread = 64<br>incr_sync.target_delay = 0<br>incr_sync.worker.batch_queue_size = 2048<br>incr_sync.adaptive.batching_max_size = 5096<br>incr_sync.fetcher.buffer_capacity = 1024<br>incr_sync.executor.upsert = false<br>incr_sync.executor.insert_on_dup_update = false<br>incr_sync.conflict_write_to = none<br>incr_sync.executor.majority_enable = false<br>special.source.db.flag =</pre><p><strong>3. Harnessing Parallel Processing</strong></p><p>Parallel processing came to our rescue. By setting parameters like incr_sync.worker, full_sync.reader.collection_parallel, and incr_sync.tunnel.write_thread to 64, we tapped into the machine’s power, speeding up the data migration process.</p><p><strong>4. Ensuring Data Consistency</strong></p><p>To maintain consistent data during migration, we worked with the checkpoint.storage configuration. This setting tracked the last synchronized data point, preventing any data gaps or inconsistencies.</p><p><strong>5. Simple Transformation and Filtering</strong></p><p>Although our migration wasn’t complex, it’s good to know that MongoShake supports transformation and filtering for more intricate scenarios. However, we mainly focused on replication without intense data manipulation.</p><p><strong>6. Staying Informed with Logs</strong></p><p>Logs played a vital role in tracking the migration process. We set log.level to ‘info’ and ensured our logs were well-stored. This helped us monitor the migration’s progress and promptly address any issues.</p><p>In a nutshell, our MongoShake journey combined hardware finesse, configuration finesse, and parallel processing expertise. This holistic approach allowed us to migrate databases effortlessly, maintain uptime, and ensure seamless synchronization. Our choices were tailored to our needs, enabling us to harness MongoShake’s true potential for smooth database replication and management.</p><h3>Real-time Monitoring and Achieving Zero Downtime</h3><p>In our pursuit of real-time insights we used this command to gauge lag:</p><p><strong>./mongoshake-stat — port=9100</strong></p><p>This tool provided us with clear visibility into the lag between our new replica set and the main monolith replica set. This real-time status check became a cornerstone in our migration strategy.</p><h3>Setting the Stage: Scaling Up the New Replica Set</h3><p>Initially, we set up a new replica set of the same size as the main monolith replica set. This ensured we had ample disk space and could handle the data sync process. While collection-level syncing (which we considered but eventually ignored) could have been cost-effective, our main focus was speed and efficiency.</p><h3>Data Sync Process and Continuous Monitoring</h3><p>With data syncing was underway, our objective was to be thorough. We kept the sync process running to catch any potential oversights. This meant that if data was inadvertently directed to the older replica set even after the switch, it was promptly synchronised in real time.</p><h3>Real-time Client Strategy for Smooth Transition</h3><p>To seamlessly switch between the replica sets without downtime, we employed a clever strategy. We created two real-time clients from our application to both replica sets. The control over which replica set to interact with was dynamic, regulated by a configurable setting. This setting could be adjusted in real time using a Data Access Object (DAO), providing us with the flexibility to switch to the new cluster, when the time was right.</p><h3>Setting Up and Running MongoShake on Ubuntu 20.04</h3><p>To make MongoShake run smoothly on Ubuntu 20.04, we encountered a few steps worth sharing. Here’s a script you can use to streamline the process:</p><pre>#!/bin/bash<br># Create a virtual environment using Python 2.7<br>virtualenv -p /usr/bin/python2.7 venv<br># Activate the virtual environment<br>source venv/bin/activate<br># Install required packages (you may need to modify this according to your needs)<br>pip install -r requirements.txt<br># Start the sync process in the background using screen<br>screen -dmS mongoshake-sync venv/bin/mongoshake -config /path/to/config.yaml<br># Optionally, you can use &#39;screen -r mongoshake-sync&#39; to attach to the screen session and monitor the sync process<br># Add any other necessary steps or configurations here<br># After everything is set up, you can deactivate the virtual environment<br>deactivate<br># Provide a message indicating that setup is complete<br>echo &quot;MongoShake setup and sync process initiated.&quot;</pre><p>Please note the following:</p><ul><li>We’re creating a virtual environment named ‘venv’ and using Python 2.7 to ensure compatibility.</li><li>We activate the virtual environment to isolate dependencies.</li><li>The requirements.txt file should list any necessary packages for your setup.</li><li>We’re using the ‘screen’ utility to run the sync process in the background, allowing you to monitor it later.</li><li>You can use screen -r mongoshake-sync to attach to the screen session and check the sync process.</li><li>Make sure to replace /path/to/config.yaml with the actual path to your MongoShake configuration file.</li></ul><p>Remember that this script is just a starting point and should be adjusted according to your specific needs and configurations.</p><h3>The Result: Achieving Zero Downtime</h3><p>Basis these meticulous steps, we successfully achieved zero downtime. Our transition from the monolith replica set to the new one was executed without any interruption in services. The real-time monitoring, synchronization, and dynamic client management played pivotal roles in ensuring a smooth and uninterrupted migration process.</p><h3>Important Notes on Log Sequence Numbers (LSN) in MongoShake</h3><p>In the realm of MongoDB replication and synchronization, understanding Log Sequence Numbers (LSNs) is pivotal. These numerical indicators provide insight into the progress and status of your synchronization process. Here are key definitions to keep in mind:</p><p>1. LSN (Log Sequence Number):</p><p>LSN stands for Log Sequence Number. It’s a unique identifier assigned to each operation in the MongoDB oplog. LSN indicates the newest oplog sequence number that has already been transferred. This number helps MongoShake keep track of the operations it has already processed.</p><p>2. LSN_ACK (Acked Log Sequence Number):</p><p>LSN_ACK stands for Acked Log Sequence Number. It signifies the maximum LSN acknowledged or received. In other words, LSN_ACK indicates that the successful LSN has been written to the consumer. It’s a confirmation that the operations up to this LSN have been successfully processed.</p><p>3. LSN_CKPT (Checkpoint Log Sequence Number):</p><p>LSN_CKPT stands for Checkpoint Log Sequence Number. This number indicates a checkpoint that has been persisted. In the context of MongoShake, it signifies a point at which the synchronization process has been successfully recorded. LSN_CKPT helps in tracking the progress of synchronization, ensuring data integrity.</p><p>Understanding and monitoring these Log Sequence Numbers as shown in fig-1 is crucial for managing and tracking your synchronization process accurately. They provide a way to assess progress, acknowledge successful synchronization, and ensure data consistency. As you work with MongoShake or any similar tools, keeping these LSN-related concepts in mind will be invaluable for effective database management and replication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hdhm9IMD5mTIRhh-" /><figcaption>(fig-1 showing the sync status)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*UJy957xJ_9oXBqCV" /><figcaption>(fig-2 showing the cpu and memory utilization from the sync process)</figcaption></figure><p>Optimizing the New Cluster for Microservice with our APM monitoring tool and MongoDB Operations</p><p>Our journey towards a finely tuned MongoDB cluster catering exclusively to our microservice involved several strategic moves. Leveraging our service monitoring tool, was central to our optimization process. Here’s how we transformed our setup:</p><p><strong>1. Identifying Microservice-Associated Collections:</strong></p><p>To ensure precision, we enlisted New Relic’s prowess. By analyzing our microservice’s behavior, we pinpointed the exact collections being actively used. This data-driven approach allowed us to remove unnecessary collections from the replica set, ensuring efficiency.</p><p><strong>2. Cleaning the Data:</strong></p><p>With insight from our monitoring tool, we embarked on a data-cleaning mission. Removing unused collections helped streamline the new cluster and optimize data storage. This process ensured that only essential data remained, enhancing performance and management.</p><p><strong>3. Right Sizing with Secondary Nodes:</strong></p><p>To bolster the robustness of our setup and optimize it even further, we introduced three new secondary nodes with low disk size and relatively lower resource configuration.</p><p><strong>4. Ensuring Write Retryability:</strong></p><p>During the transition to the new cluster, maintaining data integrity was paramount. We embedded exponential retry mechanisms using <a href="https://www.npmjs.com/package/exponential-backoff">exponential-backoff</a> in our application code to handle write failures. This ensured that any hiccups during the primary switch wouldn’t compromise data consistency.</p><p><strong>5. Meticulous Primary Switch:</strong></p><p>With safeguards in place, we executed the primary switch. This involved shifting the role of a node to primary, thereby ensuring uninterrupted service. Concurrently, we deactivated the over-provisioned nodes from the replica set.</p><p><strong>6. A Lean and Optimized Cluster:</strong></p><p>The result of our meticulous optimization journey is a lean, fully optimized cluster. It now exclusively caters to the microservice’s needs, independent of any extraneous elements. This refinement of resources translated to enhanced performance, better resource utilization, and a setup perfectly aligned with our microservice’s demands.</p><h3>Challenges: Learning Curve with MongoShake</h3><p>As we delved into the realm of MongoShake, a significant aspect of our learning curve revolved around achieving optimal performance during data syncing. This phase brought its own set of challenges, with right sizing and configuration emerging as crucial factors. Here’s how we tackled these hurdles and optimized our setup for faster and stable syncing:</p><p><strong>1. Understanding Right Sizing:</strong></p><p>Navigating through the learning curve, we realized the importance of right sizing our setup. We dived into the <a href="https://www.mongodb.com/docs/manual/faq/">FAQ page</a> and meticulous documentation, seeking insights into the optimal hardware specifications for our environment.</p><p><strong>2. Iterative Configurations:</strong></p><p>To achieve faster syncing, we embarked on an iterative journey of configurations. Armed with our understanding of MongoShake’s capabilities, we fine-tuned settings to match the demands of our data migration. These iterations were informed by both the official documentation and practical experimentation.</p><p><strong>3. Avoiding Overwork and Crashes:</strong></p><p>A significant challenge we faced was ensuring that our syncing server didn’t crash due to overwork. As we pushed the envelope to maximize performance, we encountered instances where the server struggled to cope with the load. This led us to recalibrate our configurations and adjust parameters to strike the right balance.</p><p><strong>4. Learning from Failures:</strong></p><p>Challenges and failures during the syncing process were turned into invaluable learning opportunities. Each instance of a crash or slowdown prompted us to analyze, tweak, and optimize our configurations. This iterative approach ensured that we learned from our mistakes and continually improved the syncing process.</p><p><strong>5. Stability v/sSpeed:</strong></p><p>Another crucial lesson was the delicate balance between speed and stability. While we aimed for faster syncing, stability was paramount. We learned that reckless adjustments for speed could compromise the reliability of the process. Striking the right equilibrium between the two became a top priority.</p><p><strong>6. The Rewards of Optimization:</strong></p><p>Our dedication to right sizing and fine-tuning configuration settings ultimately paid off. The syncing process that initially posed challenges evolved into a streamlined and stable operation. By aligning our setup with the optimal configuration, we achieved the desired speed without sacrificing reliability.</p><p>In the end, our learning curve with MongoShake’s configuration was an exercise in perseverance, adaptability, and technical acumen. The challenges we faced while optimizing performance underscored the importance of continuous improvement. This journey exemplified how trial and error, coupled with careful consideration of documentation and practical experience, paved the way for a synchronized setup that excelled in both speed and stability.</p><h3>Lessons Learned</h3><p>Throughout our MongoShake journey, we learned that meticulous attention to detail, especially in reading documentation and scrutinizing comments, played a pivotal role in overcoming crashes and streamlining longer syncing times. This practice of precision allowed us to navigate complexities effectively, swiftly addressing challenges and optimizing our implementation with greater confidence and success.</p><p>During our MongoShake expedition, we learned a valuable trick: if sync goes haywire, you don’t always need to start from scratch. Clearing sync collection metadata and rebooting the process is often a quicker fix. This quick workaround turbocharged our iterations, cutting downtime when dealing with sync hiccups. This pragmatic approach highlighted the importance of adaptability and resourcefulness, making our project more resilient.</p><h3>Conclusion</h3><p>In the realm of database optimization and migration, our encounter with MongoShake proved transformative. The challenge of untangling a monolithic MongoDB setup while avoiding downtime demanded innovative solutions.Through collaborative problem-solving and a dedication to continuous learning, we managed to strike the delicate balance between performance and stability.</p><p>We meticulously fine-tuned configuration settings, adapting in real time to optimize performance. Importantly, our newfound understanding of tackling sync glitches via metadata cleaning added an extra layer of efficiency.</p><p>We invite fellow developers and teams to explore these concepts further. By harnessing real-time monitoring, precision in configuration, and problem-solving prowess, they can navigate complex database migrations with greater confidence, ultimately achieving a more streamlined and optimized environment.</p><h3>References</h3><ol><li>MongoShake GitHub Repository: <a href="https://github.com/alibaba/MongoShake">https://github.com/alibaba/MongoShake</a></li></ol><p>2. MongoShake FAQs : <a href="https://github.com/alibaba/MongoShake/wiki/FAQ">https://github.com/alibaba/MongoShake/wiki/FAQ</a></p><p>3. MongoDB Official Documentation: <a href="https://docs.mongodb.com/">https://docs.mongodb.com/</a></p><p>4. MongoDB Oplog: <a href="https://docs.mongodb.com/manual/core/replica-set-oplog/">https://docs.mongodb.com/manual/core/replica-set-oplog/</a></p><p>5. Virtual Environment (venv) Documentation: <a href="https://docs.python.org/3/library/venv.html">https://docs.python.org/3/library/venv.html</a></p><p>6. Screen Command Documentation: <a href="https://linux.die.net/man/1/screen">https://linux.die.net/man/1/screen</a></p><p>7. MongoDB Specifications for client: <a href="https://github.com/mongodb/specifications/tree/master/source">https://github.com/mongodb/specifications/tree/master/source</a></p><p>We invite you to join the conversation and share your thoughts on our journey to achieving seamless database migrations using the powerful MongoShake tool. Do you have questions, insights, or experiences to share? We’d love to hear from you in the comments section below.</p><p>For more in-depth discussions on database optimization, migration, and other technical topics, be sure to explore related blog posts on our website. Your engagement fuels the exchange of knowledge and empowers the developer community to conquer challenges with innovative solutions.</p><p>If you found this blog post valuable, why not spread the knowledge? Share it with your peers on social media platforms, enabling others to benefit from our experiences and insights. Together, we can pave the way for smoother, more efficient database management and elevate the standards of software engineering.</p><h3>About Author</h3><p><strong>Atique Firoz</strong> is a <strong>Senior Software Engineer</strong> at Zupee with a strong foundation in backend development. His expertise extends to the intricate world of <strong>MongoDB</strong> and database systems, where he excels in managing and scaling primary database systems. With a passion for optimizing performance and streamlining operations, Atique has contributed significantly to his company’s database management strategies. His drive to unravel complex database challenges has led him to explore innovative solutions, as exemplified in his work with MongoShake for achieving seamless database migrations. Atique’s dedication to enhancing system efficiency and his deep appreciation for the intricacies of database systems have earned him a prominent place in the realm of software engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d70f18e80b0" width="1" height="1" alt=""><hr><p><a href="https://tech.zupee.com/abolish-maintenance-hours-scaling-mongodb-without-any-downtime-2d70f18e80b0">Abolish maintenance hours: Scaling MongoDB without any downtime</a> was originally published in <a href="https://tech.zupee.com/">Zupee TechLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Coffee Break with Test Automation]]></title>
            <link>https://tech.zupee.com/a-coffee-break-with-test-automation-b3ac6670d4fd?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3ac6670d4fd</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 07:50:42 GMT</pubDate>
            <atom:updated>2023-09-16T08:31:41.735Z</atom:updated>
            <content:encoded><![CDATA[<p>By Vishal Agarwal, QA Lead @ Zupee</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Uj58DBlXo5IyTDODDXrQlw.jpeg" /></figure><h3>Introduction</h3><p>Picture this: a serene moment in the midst of a bustling day, where the aroma of freshly brewed coffee wafts through the air. It’s more than just a break; it’s an opportunity to step away from the daily grind and explore the world of test automation. Just like that cup of coffee, test automation offers a refreshing perspective on software testing, empowering you to enhance efficiency, accuracy, and quality in your projects. Join us for a stimulating journey as we take a coffee break with test automation, delving into its benefits, best practices, and the art of blending code and creativity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*a7gVpa6h4yKoLBdoyRsGnA.jpeg" /><figcaption><strong>Figure 1‑ Test Automation</strong></figcaption></figure><h3>Innovation</h3><p>What comes first in my mind is what this term “innovation” is?</p><ul><li>Wikipedia says, “Innovation as a <em>process</em> that brings together various novel ideas in a way that they have an impact on society”.</li><li>The greatest innovations are the ones we take for granted, like light bulbs, refrigeration and penicillin.</li><li>What Innovation to me is doing things in a different way i.e. to solve a problem that can create a positive impact in the society, in our case — organization</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*LD99D0cm-AcwaD7-Iuw8Lg.jpeg" /><figcaption><strong>Figure 2 — Defining Innovation</strong></figcaption></figure><h3>Lesson 1:- Necessity is the mother of Invention</h3><p>In 2021–22, we had a necessity, a challenge to reduce the efforts required towards the testing of our solutions in the App front. We had a challenge which required considerable efforts to test the mobile front for every release.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*-FAQKq61MfZjGEzuMuzq-g.jpeg" /><figcaption><strong>Figure 3‑ Zupee Platform</strong></figcaption></figure><p><strong>Target for Testing: </strong>Regression + Sanity</p><p><strong>Test Cases or Scenarios: </strong>900</p><p><strong>Time taken to Execute Manually: 5–6(In Person Days)</strong></p><p>Challenges for Test Automation Team:-</p><ul><li>Automate 900+ cases in the Zupee platform which is such a huge and evolving product.</li><li>Task to automate not only Zupee platform but also to put a standard layout/structure &amp; framework.</li><li>Required a different and innovative approach, something new which had never been done before in the company.</li></ul><p>So it’s time to walk you through the journey of what we have innovated that has helped the organization release faster &amp; helped our products to become more stable on production.</p><h3>Lesson 2:- Identify the problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S1yyyAE2peh5lWGm" /><figcaption><strong>Figure 4</strong>:- <strong>Identifying the Challenge</strong></figcaption></figure><h3><strong>Lesson 3:- Redefine the old ways</strong></h3><p>We understood that the way forward is automation since the regression suite is a repeatable set of tests which holds the key to make faster releases on production with highest stability &amp; quality.</p><p>Automation has below advantages for repeatable set of test cases (for instance, sanity &amp; regression suites) -:</p><ul><li>Effort required for manual testing is too high.</li><li>Slow and costly in terms of timelines.</li><li>Possibility of human error / Inconsistent results</li><li>Difficult to manage</li><li>Proves boring for the team to repeat similar tests in every release cycle.</li></ul><h3>Lesson 4:- There is no education like adversity</h3><p>Engineers view the system as WHITE BOX and Customer views the solution as BLACK BOX. The confidence on the quality of the solution for customers is primarily based on the UI/UX.</p><p>For some people, it might look like a simple triangle, but for us, it was the focus point for automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/0*0vXAvmmzjnFRQ7AG" /><figcaption><strong>Figure 6 — Engineer’s View (Unit Tests as the base) — Customer View (GUI Tests as the base)</strong></figcaption></figure><h3><strong>Lesson 5:- Every problem is an opportunity — THE JOURNEY</strong></h3><h4>Expanding Toolset and Upskilling</h4><ul><li>Our initial step was to develop a Java-based framework and slowly started creating a robust &amp; scalable framework based out of Cucumber Java Appium. This allowed us to adapt quickly to different project requirements and technologies.</li><li>We needed to identify a task force to start the pilot version of the automation project. This task force would consist of QA members who not only could upskill themselves but also could help others in upskilling for this journey. After identifying a core team, we started training them by sharing online resources / documents along with a closed group mentoring exercise. Once we successfully upskilled our team in mobile application automation tools, it gave them confidence on the coding front &amp; enabled us to efficiently automate critical mobile scenarios.</li></ul><h4>Prioritizing High-Impact Scenarios</h4><ul><li>We identified and coordinated with our stakeholders (product/development/CRM team) to identify the P0 user journeys in addition to our regression suite. Then we strategically started to automate high-priority test cases, leading to increased confidence from both our team and stakeholders in the reliability of our automation suite.</li></ul><h4>Leveraging Cloud Device Farms:</h4><ul><li>We have also leveraged platforms like BrowserStack and Lambda Test for efficient cross-device testing. This enabled us to ensure a seamless user experience across a variety of environments.</li><li>This brought a lot of learnings in the team and we got to know about the show stoppers.</li></ul><p>We analyzed the requirements, saw the opportunity and we came up with a strategy and implemented it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f_y6B_it7hdaMVh2" /><figcaption><strong>Figure 7 — Automation Team Homework</strong></figcaption></figure><h3>Lesson 6:- Hit the Bull’s Eye</h3><ul><li>All P0 priority test scenarios are now automated and execution happens without any manual intervention.</li><li>Pre and Post test conditions and dependencies are accommodated during the automation process. As such the test suites are self sufficient and independently executed.</li><li>GUI elements data validations done for identified scenarios</li><li>Every test case is independent of each other so that tests can be executed in parallel or in any order.</li><li>Tests which are executed through automation do not have any persistent side effects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*FEYvn1Aqz5st-ZRp" /><figcaption><strong>Figure 8 — Hit the Target</strong></figcaption></figure><h3>Promising Results : A Direct Saving of 3 days worth of effort.</h3><p>Test automation is like “<strong>DA VINCI CODE</strong>” because whether it is the Vinci Code or the Test Automation, they were present earlier also, they still exist and they will be present in future and whoever cracks it will get the HOLY GRAIL. In case of test automation, the holy grails are –</p><ul><li>Saves valuable time</li><li>Consistency i.e the same repeatable tests can be run multiple times in exactly the same manner eliminating the risk of human errors</li><li>Maintenance of the test suite</li><li>Can be reused on different app releases</li><li>Increase Coverage</li><li>Cost Reduction</li></ul><p><strong>Test Cases Automated: 350+</strong></p><p><strong>Time Saved: </strong>10 hours of manual regression effort</p><p><strong>Current App Release Time: </strong>6 MD -&gt; 2.5 MD <strong>(In Person Days)</strong></p><p>The same code is getting maintained now for different app releases of<a href="http://mahindracomviva.com/products/MFS/mobiquity.htm"> </a>Zupee Platform. After making “delta” changes in the code, various versions of<a href="http://mahindracomviva.com/products/MFS/mobiquity.htm"> </a>Zupee app releases are being automated and they were able to save time, cost and effort. Teams are now getting time to do exploratory testing which is helping the QA team to find a lot of issues which might not be able to be figured out if we would have stayed with manual testing.</p><h3>What’s Next</h3><h3>Scaling Test Coverage</h3><p>We are also considering expanding our test coverage to include more critical and frequently used features. We need to identify areas that have high business impact and prioritize automation for them. For this, we are constantly taking feedback from product managers and the stakeholders team.</p><h3>Reducing Flaky Tests</h3><p>We are also focused on identifying and resolving flaky tests to ensure that automation results are consistent and trustworthy. We are consistently investing time in root cause analysis and implementing strategies to minimize test flakiness.</p><h3>Maintenance and Refactoring</h3><p>We are regularly reviewing and refactoring our automation codebase to ensure it remains maintainable and adaptable to changes in the application. However, it is an ongoing process and it will be carried as and when features are added/modified.</p><h3>Feedback Loop and Continuous Improvement</h3><p>We have also established a feedback loop with our development and product team to address any identified issues promptly. We have to continuously seek ways to improve our automation process else we will lag behind with our current progress as well.</p><h3>Closing Words</h3><p>At last I can say that we have tried something different, we brought something new, something different to the plate which has created an impact in the organization. We are not DONE yet, we still have a long way to go to achieve our motives, our goals and on a lighter note, our KRAs.</p><p>People are aware of Test Automation, Agile, they are still aware and they are doing it in their way. For us, words like “<strong>CATALYST</strong>”, “<strong>AGILE ‘’</strong>, “<strong>LAMBDA TEST</strong>” means a lot, it helped us to improve. We can’t say that we have invented something very new; however, we can say that we have served the dish on the plate in a “<strong>DIFFERENT</strong>” manner; we just tried a “<strong>SHIFT IN MINDSET</strong>”.</p><p>I would like to end this by a Thomas Alva Edison’s statement –</p><p><strong>“Be brave as your fathers before you. Have faith and go forward”</strong></p><p><strong>Vishal Agarwal</strong></p><p>Technology Group</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3ac6670d4fd" width="1" height="1" alt=""><hr><p><a href="https://tech.zupee.com/a-coffee-break-with-test-automation-b3ac6670d4fd">A Coffee Break with Test Automation</a> was originally published in <a href="https://tech.zupee.com/">Zupee TechLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing the Power of Sharding: Scaling MySQL for high TPS]]></title>
            <link>https://tech.zupee.com/unleashing-the-power-of-sharding-scaling-mysql-for-high-tps-a56003b7b38?source=rss-3bb4617bbf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/a56003b7b38</guid>
            <category><![CDATA[sharding]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Zupee TechLab]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 16:17:39 GMT</pubDate>
            <atom:updated>2023-09-16T08:32:41.211Z</atom:updated>
            <content:encoded><![CDATA[<p>By Amit Garg, Tech Lead @ Zupee</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*nq4fgeYKLQdc3u0wAxD3qA.jpeg" /></figure><h3>Introduction</h3><p>With increasing scale and big marketing campaigns around the corner, tech was apprised of the increase in traffic. As logical engineers, we started with predicting the traffic at scale and reviewing our internal infrastructure and load patterns.One of the bottlenecks was the usage of a single mysql instance. It was high time for us to make our systems horizontally scalable. <strong>Sharded MySql </strong>was the only solution to our problem. Making mysql sharded on a running production system with minimum downtime is a very challenging yet thrilling experience. It required careful planning and precise execution.</p><h3>The Problem</h3><h3>Approach</h3><p>Let’s take a bird’s eye view on how we approached the problem.</p><p>Was sharding the only solution? Couldn’t we just increase the instance size? Couldn’t we replace mysql with any Nosql sharded solution?</p><p>Let’s understand answer to these questions in detail</p><p>Let’s take a look at how our passbook transactions look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zD1nM7l4SPdbLwz66Fl61g.png" /></figure><p><strong>Atomicity</strong>: Adding money and no record in db whereas the customer got the successful response could be a very frustrating experience for your customers. Also multiple concurrent transactions without atomicity could lead to any random amount in users account</p><p><strong>Consistency</strong>: You never want your money to be debited multiple times when you withdraw only once. Also multiple revert transactions against any single transaction should be blocked.</p><p><strong>Isolation: </strong>None of the 2 transactions should be interlinked and they should be happening independently.</p><p><strong>Durability: </strong>If a customer is acknowledged with a successful transaction, then he should be able to see his transaction in his passbook even if there is any system outage.</p><p>Got it. Clearly we required ACID properties of RDBMS for maintaining the passbook of the users. So a nosql database is out of the question. Let’s check other aspects if vertical scaling could help us or not.</p><p>There’s always a limit while scaling vertically. You can not increase your db instance size indefinitely, sooner or later you would hit the dead end. Cost increase is also exponential with every extra core you purchase while scaling vertically. Whereas horizontal scaling is linear and a better approach. Also it is cost effective solution</p><p><strong>OK, SHARDING DECIDED, but how? </strong>What aspects do we need to consider before starting? Can we just add more instances and be assured that everything will work? Is our system sharding friendly?</p><p>One of the main aspects of sharding is the shard key. If not chosen rightly, sharding is of no use. You can face the hotkey problem. Also we had to ensure that all the join operation data falls under the same shard. Let’s take a deeper look at the how we implemented sharding for our system</p><h3>Implementation Details:</h3><p><strong>Choosing the Right Shard Key:</strong> We maintain wallet and user’s passbook in mysql so user’s id as shard key was a simple choice but we had to be careful as warned by mysql regarding hotkey problem. We ran following hash algorithms on our transacting users data and overall data</p><ul><li>Simple Modulo</li><li>CRC-16</li><li>MD5</li><li>SHA256</li><li>Murmur2</li><li>murmur3</li><li>For any sample duration (from &amp; end timestamp), we split the sample into partial intervals of 5 seconds.</li><li>For each interval, calculate the uid frequency map.</li><li>Then, for each interval, calculate load distribution on shards (using hash function on uid)</li><li>Apply Pearson’s chi-squared test &amp; also calculate maximum load deviation % on any shard compared with avg load</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IwP0E9DmvnWolpNp" /></figure><p><strong>Results clearly were positive for the choice of user id as our shard key</strong></p><p><strong>Transitioning a live system with minimal downtime: </strong>Making a sharded mysql cluster would be easier if done from scratch but transitioning a live system from non sharded mysql instance to a sharded cluster is quite a challenge. A minute mistake could bring the whole business to collapse. We achieved this using the following approach:</p><ol><li>Added 4 Shards as replicas of the primary mysql instance. Now all the newly added shards have a complete copy of data as our primary instance has.</li><li>One replica for each replica had been set up.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*88xxBa7bju_uaE6w" /></figure><p>3. Made our wallet service to support sharded clusters as well as single instances behind a feature flag.</p><p>4. Read lock on primary single instance has taken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VYHT_kC1dJJPkITu" /></figure><p>5. Now no new writes will come to the primary instance. We had to wait till the replication lag is 0 between the primary instance and the replicas of the primary instance.</p><p>6. Stop the replication and enable writes on every shard. Run the following commands on every shard.</p><pre>STOP SLAVE<br>SET GLOBAL read_only = OFF;</pre><p>Post above steps, system would look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8ar6kKP67Z0Ie_8K" /></figure><p>Now make the service point to the sharded cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dRAAU0XFAhZpU6qt" /></figure><p>Voila! We are done !</p><h3>Challenges</h3><p>Maintaining a self managed sharded database comes with its own challenges. Following are some of the challenges we faced.</p><ol><li><strong>Keeping mysql’s constraint across the shards : </strong>We need to ensure all table’s unique key constraint across the shard is not violated. To maintain a separate set of primary keys across shards we set different starting points for each shard. So for introducing 4 shards,</li></ol><p><em>First shard’s primary key incremental counter will start from 1</em></p><p><em>Second shard’s primary key incremental counter will start from x</em></p><p><em>Third shard’s primary key incremental counter will start from 2x</em></p><p><em>Fourth shard’s primary key incremental counter will start from 3x</em></p><p>X is chosen in such a way that it should be sufficient for at least 10 years of transactions. You might say this is not an ideal way of doing, I agree but considering the time frame in which we have to achieve sharding, this approach seemed convenient. This approach comes with its own benefits of simplicity and ease of adding a new shard. Following is another way of solving this</p><p><em>First shard’s primary keys will be starting from 1 then increasing with a delta of 4</em></p><p><em>Second shard’s primary keys will be starting from 2 then increasing with a delta of 4</em></p><p><em>Third shard’s primary keys will be starting from 3 then increasing with a delta of 4</em></p><p><em>Fourth shard’s primary keys will be starting from 4 then increasing with a delta of 4</em></p><p>But in this approach there is no room for altering the number of shards and it is not as simple as the first one. So we chose the first approach</p><p><strong>DB lookups to remain the same: </strong>One of the major challenges was to keep the same number of DB lookups. Searching in all the shards is easy and tempting but could impact the overall application performance rather than optimizing it. Also all our bulk read/writes where multiple user ids were involved in batching required revamp and batching around the same shard was done.</p><h3>Conclusion</h3><p>It felt really overwhelming when our own managed sharded cluster is live and serving our valued customers. At the end of this activity one thing I realized is that mysql is not sharding friendly, you have to analyze your systems thoroughly before considering sharding as a solution and following are some recommendations to start with.</p><ul><li><em>A database where you need to search based on multiple columns sharding is not something you will consider</em></li><li><em>Higher the normalization form in your database lesser are the chances of sharding</em></li><li><em>Too many db level constraints also makes it difficult to shard the cluster</em></li></ul><p>In short it depends on your application, if your application at any time while interacting with one of the shards does not require any data from other shards you can choose to own a sharded cluster as a solution for a horizontally scalable system else it can give you nightmares instead of sound sleep.</p><p>I invite all the readers to further dive deeper in the concepts of mysql sharding. If sharding is done correctly, achieving the scale of billions of transactions would be very easy. In today’s world where we have generated 90% of data in the last 2 years and pace is still increasing, scalable solutions are the only way forward.</p><h3>By Amit Garg</h3><p>He is tech lead at Zupee. Making scalable and distributed systems is a passion for him. He has an overall 7+ years of experience in system design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a56003b7b38" width="1" height="1" alt=""><hr><p><a href="https://tech.zupee.com/unleashing-the-power-of-sharding-scaling-mysql-for-high-tps-a56003b7b38">Unleashing the Power of Sharding: Scaling MySQL for high TPS</a> was originally published in <a href="https://tech.zupee.com/">Zupee TechLab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>