<?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 Ini Etienam on Medium]]></title>
        <description><![CDATA[Stories by Ini Etienam on Medium]]></description>
        <link>https://medium.com/@ietienam?source=rss-aed93ddf5f14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-PqZ9G3GFp5kia7679jJSQ.jpeg</url>
            <title>Stories by Ini Etienam on Medium</title>
            <link>https://medium.com/@ietienam?source=rss-aed93ddf5f14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:43:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ietienam/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[The ‘Senior’ Trap: Why Engineers Burn Out Fixing Mediocre Systems]]></title>
            <link>https://medium.com/@ietienam/the-senior-trap-why-engineers-burn-out-fixing-mediocre-systems-907807878683?source=rss-aed93ddf5f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/907807878683</guid>
            <category><![CDATA[engineering-mangement]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Ini Etienam]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 18:23:59 GMT</pubDate>
            <atom:updated>2025-07-13T18:23:59.821Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In engineering, as in life, titles often precede the work rather than follow it. The danger is when we start believing they’re the same thing.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*itsP5m27AfL1HN7U" /><figcaption>Photo by <a href="https://unsplash.com/@atoto_photo?utm_source=medium&amp;utm_medium=referral">Aidan Tottori</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Shifting Meaning of “Senior”</h3><p>Over time, the title <em>Senior Engineer</em> has quietly lost its weight.</p><p>Once a marker of technical leadership and architectural maturity, it’s now often used as a retention tool, a leveling badge, or simply a way to signal tenure. That wouldn’t be a problem if the title still reflected the underlying responsibilities.</p><p>But too often, it doesn’t. And the gap between title and capability can quietly corrode the system.</p><h3>When the System Doesn’t Match the Titles</h3><p>In environments where titles are inflated or misaligned, recurring patterns tend to emerge:</p><ul><li>Brittle systems with no clear ownership</li><li>Engineers avoiding uncomfortable decisions around tech debt</li><li>Architecture led by group consensus instead of technical clarity</li></ul><p>And somewhere in the background, there’s usually someone picking up the slack.</p><p>Not loudly. Not ceremoniously. Just consistently.</p><p>They’re the ones reviewing core services, patching edge cases, and thinking three steps ahead without fanfare or title drama. But over time, their energy drains. Because when responsibility is distributed but authority isn’t, burnout is inevitable.</p><h3>The Burnout Loop</h3><p>It usually looks like this:</p><ol><li>Systems start to degrade from rushed decisions or neglect.</li><li>The most competent engineers step in to stabilize things.</li><li>Their work goes unnoticed or worse, is treated as overengineering.</li><li>Decision-making continues without them.</li><li>They burn out, check out, or leave.</li></ol><p>Burnout in engineering isn’t always about too much work. Sometimes, it’s about watching a system you care about decay while you’re powerless to change it.</p><h3>What Real Seniority Looks Like</h3><p>Titles aside, engineering maturity tends to show up in behavior:</p><ul><li>Thinking in systems, not just features</li><li>Designing for failure, not just the happy path</li><li>Prioritizing boring, stable solutions over shiny complexity</li><li>Elevating team velocity by reducing ambiguity</li><li>Saying “no” when necessary, without ego</li></ul><p>These engineers may not have the loudest opinions in meetings. But when production is on fire, everyone calls them first.</p><h3>Moving Forward, Thoughtfully</h3><p>This is a reminder that engineering culture shapes engineering outcomes.</p><p>If the goal is to build systems that scale not just in traffic, but in time, we need to:</p><ul><li><strong>Use titles carefully</strong>, and tie them to deep responsibility</li><li><strong>Reward invisible work</strong>, not just velocity or output</li><li><strong>Invest in technical stewardship</strong>, not just management optics</li><li><strong>Challenge shallow culture</strong>, especially when it looks polished on the surface</li></ul><p>Because when engineering leadership is based on politics instead of craft, the system eventually reflects that.</p><h3>Final Thought</h3><p><em>You don’t become senior because of your title.<br>You become senior the moment you start making decisions with the system , not yourself in mind.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=907807878683" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If You Don’t Know What Logs First, You Don’t Understand JavaScript — And That’s a Problem]]></title>
            <link>https://medium.com/@ietienam/if-you-dont-know-what-logs-first-you-don-t-understand-javascript-and-that-s-a-backend-problem-0a4146efeb67?source=rss-aed93ddf5f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a4146efeb67</guid>
            <category><![CDATA[promises-in-javascript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Ini Etienam]]></dc:creator>
            <pubDate>Wed, 07 May 2025 20:44:36 GMT</pubDate>
            <atom:updated>2025-05-08T15:00:55.993Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>If You Don’t Know What Logs First, You Don’t Understand JavaScript — And That’s a Problem</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpKegjtzR2H7Z3FxllB0Ag.png" /><figcaption>Javascript Promise</figcaption></figure><p>Consider the following snippet:</p><pre>console.log(&#39;A&#39;);<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;B&#39;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&#39;C&#39;);<br>});<br><br>console.log(&#39;D&#39;);</pre><p>If you’re not entirely sure what gets logged in what order, you’re not alone and you’re not ready to write reliable, performant backend JavaScript at scale.</p><p>The correct output is:</p><pre>A<br>D<br>C<br>B</pre><p>Why? Because JavaScript’s concurrency model is not threaded but event-driven. The console.log(&#39;A&#39;) and console.log(&#39;D&#39;) are synchronous and run immediately. Promise.resolve().then(...) queues a <em>microtask</em>, which runs right after the current call stack is empty. setTimeout(..., 0) queues a <em>macrotask</em>, which only runs after all microtasks are complete.</p><p>If you didn’t know that, then you don’t truly understand the execution flow of your backend code — especially when it comes to async/await, I/O operations, and performance bottlenecks.</p><p>And that’s a problem.</p><h3>Why “Good Enough” JavaScript Backends Collapse at Scale</h3><p>JavaScript (Node.js) seems performant and easy at first. A basic API with some queries and a few users runs fine. But as your user base and data grow, naive patterns like await inside for loops, unnecessary awaits or fire-and-forget writes start to crack under pressure.</p><h4>The Loop Misconception</h4><pre>for (const record of records) {<br>  await db.save(record);<br>}</pre><p>This is serial. Each iteration waits for the previous one. It’s fine for a dozen records, but terrible for thousands. Worse, some developers think async/await inherently means “parallel”—but it doesn’t. Without <strong>Promise.all</strong> or <strong>batching</strong>, you&#39;re queuing work one by one.</p><h4>Bulk Operations: Your Database’s Best Friend</h4><p>Instead of individual calls, leverage bulk operations like:</p><pre>await db.insertMany(records);</pre><p>or for updates:</p><pre>await db.collection.bulkWrite([<br>  { updateOne: { filter: {...}, update: {...} }},<br>  ...<br>]);</pre><p>These drastically reduce database round-trips, improve throughput, and help avoid connection pool exhaustion.</p><h4>The Silent Killer: Missing Transactions</h4><p>Developers often chain multiple await calls thinking if the code doesn’t throw, the data is fine:</p><pre>await db.createInvoice(invoice);<br>await db.markOrderComplete(orderId);</pre><p>But if that second call fails, your system is left in a corrupted state. In production, these failures are rare enough to escape detection — until data inconsistencies start affecting users.</p><p>Use transactions:</p><pre>const session = await db.startSession();<br>await session.withTransaction(async () =&gt; {<br>  await db.createInvoice(invoice, { session });<br>  await db.markOrderComplete(orderId, { session });<br>});</pre><p>Transactions ensure all-or-nothing behaviour. They add complexity, yes, but they save you from the hell of retroactive data repair.</p><h3>Understanding Promises Is Not Optional</h3><p>The way JavaScript schedules work — <strong>microtasks</strong>, <strong>macrotasks</strong>, <strong>event loop phases</strong> — directly impacts your backend’s performance and correctness. If you misunderstand it, your code might:</p><ul><li>Execute slower than expected</li><li>Overwhelm the DB with sequential or uncontrolled parallel requests</li><li>Leave data half-written without you realising</li></ul><p>Backends aren’t just about building APIs — they’re about building systems that <em>scale</em>, <em>recover</em>, and <em>perform</em>.</p><p>So if that logging snippet confused you, it’s a sign. Learn how promises work. Learn the event loop. And rethink your backend strategy — before your success becomes your bottleneck.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a4146efeb67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Node.js API to Google Kubernetes Engine (GKE) Using GitHub Actions]]></title>
            <link>https://medium.com/@ietienam/deploying-a-node-js-api-to-google-kubernetes-engine-gke-using-github-actions-55742479cab7?source=rss-aed93ddf5f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/55742479cab7</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Ini Etienam]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 10:20:59 GMT</pubDate>
            <atom:updated>2024-10-22T14:43:46.092Z</atom:updated>
            <content:encoded><![CDATA[<p>In this guide, we’ll take a simple <strong>Node.js API</strong>, containerise it, and deploy it to Google <strong>Kubernetes Engine (GKE)</strong> using <strong>GitHub Actions</strong> for automated <strong>Continuous Integration/Continuous Deployment (CI/CD)</strong>. By the end, you’ll have an automated pipeline that builds, pushes, and deploys your code to <strong>GKE</strong> every time you push to the main branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWa-9sOKtyoP9TPF50PuRw@2x.jpeg" /><figcaption>Photo by <a href="https://carrierlost.myportfolio.com/">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While this guide gets you off the ground, I’ll admit, it’s not fully production-ready. We’ll focus on a few key areas like autoscaling and health checks, but there’s still a lot more to do before you’d want to run real traffic on this. Let’s dive in.</p><h4><strong>Prerequisites</strong></h4><p>You’ll need:</p><p>• A <strong>Google Cloud account</strong> with billing enabled.<br> • A <strong>GKE cluster</strong> set up.<br> • <strong>Docker</strong> installed on your local machine.<br> • <strong>Node.js</strong> and npm installed.<br> • Basic familiarity with <strong>Kubernetes</strong> and <strong>CI/CD</strong> concepts.</p><h4>Step 1: Create a Simple Node.js API</h4><p>Let’s start by creating a basic Node.js API. In your terminal, create a new project directory and set up a basic Express app:</p><pre>mkdir nodejs-api<br>cd nodejs-api<br>npm init -y<br>npm install express</pre><p>Next, create an index.js file in your project directory with the following code:</p><pre>const express = require(‘express’);<br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br> res.send(&#39;Hello, World!&#39;);<br>});<br><br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; {<br> console.log(`Server is running on port ${PORT}`);<br>});</pre><p>To test it, run:</p><pre>node index.js</pre><p>Visit <a href="http://localhost:3000/">http://localhost:3000</a> in your browser, and you should see “<em>Hello, World!</em>” displayed.</p><h4>Step 2: Dockerize the Application</h4><p>Next, we’ll Dockerize the Node.js API. In the root of your project, create a Dockerfile:</p><pre># Use the official Node.js image<br>FROM node:14<br># Set the working directory<br>WORKDIR /app<br># Copy package.json and install dependencies<br>COPY package*.json ./<br>RUN npm install<br># Copy the rest of the application<br>COPY . .<br># Expose port 3000<br>EXPOSE 3000<br># Command to run the application<br>CMD [&quot;node&quot;, &quot;index.js&quot;]</pre><p>To build and test the Docker image locally:</p><pre>docker build -t nodejs-api .<br>docker run -p 3000:3000 nodejs-api</pre><p>Visit <a href="http://localhost:3000/">http://localhost:3000</a> to confirm that the API is running inside the container.</p><h4>Step 3: Push Docker Image to a Container Registry</h4><p>At this point, your Docker image is ready, but we need to push it to a registry so it can be used in GKE. You have several options here:</p><p><strong>1. Google Container Registry (GCR) </strong>— This is Google’s native container registry, which works smoothly with GKE.<br> <strong>2. Docker Hub</strong> — If you’re already using Docker Hub, you can push your images there.<br> <strong>3. GitHub Container Registry</strong> — Another option is GitHub’s own container registry, which integrates well with GitHub Actions.</p><h4>Google Container Registry (GCR)</h4><p>To push the image to GCR, tag it:</p><pre>docker tag nodejs-api gcr.io/&lt;your-project-id&gt;/nodejs-api</pre><p>And then push it:</p><pre>docker push gcr.io/&lt;your-project-id&gt;/nodejs-api</pre><h4>Docker Hub</h4><p>If you’re using Docker Hub, first log in:</p><pre>docker login</pre><p>Then, tag the image:</p><pre>docker tag nodejs-api &lt;your-dockerhub-username&gt;/nodejs-api</pre><p>Push the image to Docker Hub:</p><pre>docker push &lt;your-dockerhub-username&gt;/nodejs-api</pre><h4>GitHub Container Registry</h4><p>To push to GitHub’s registry, you’ll first need to authenticate:</p><pre>docker login ghcr.io -u &lt;your-github-username&gt;</pre><p>Then, tag and push the image:</p><pre>docker tag nodejs-api ghcr.io/&lt;your-github-username&gt;/nodejs-api<br>docker push ghcr.io/&lt;your-github-username&gt;/nodejs-api</pre><h4>Step 4: Create Kubernetes Deployment and Service Files</h4><p>Now, let’s configure Kubernetes to deploy the containerized application. Create a <strong>k8s-deployment.yaml</strong> file:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br> name: nodejs-api<br>spec:<br> replicas: 3<br> selector:<br> matchLabels:<br> app: nodejs-api<br> template:<br> metadata:<br> labels:<br> app: nodejs-api<br> spec:<br> containers:<br> — name: nodejs-api<br> image: gcr.io/&lt;your-project-id&gt;/nodejs-api:latest<br> ports:<br> — containerPort: 3000<br> — -<br>apiVersion: v1<br>kind: Service<br>metadata:<br> name: nodejs-api-service<br>spec:<br> type: LoadBalancer<br> selector:<br> app: nodejs-api<br> ports:<br> — protocol: TCP<br> port: 80<br> targetPort: 3000</pre><p>Apply the deployment to your GKE cluster:</p><pre>kubectl apply -f k8s-deployment.yaml</pre><p>This will deploy 3 replicas of your application and expose them via a LoadBalancer service.</p><h4>Step 5: Set Up GitHub Actions for CI/CD</h4><p>Now it’s time to automate the build and deployment process using GitHub Actions. Every time you push to main, GitHub Actions will build the Docker image, push it to the registry, and deploy it to GKE.</p><p>Create a <strong>.github/workflows/deploy.yml</strong> file in your repository:</p><pre>name: CI/CD Pipeline<br>on:<br> push:<br> branches:<br> - main<br>jobs:<br> build:<br> runs-on: ubuntu-latest<br>steps:<br> - name: Checkout code<br> uses: actions/checkout@v3<br>- name: Set up Docker<br> uses: docker/setup-buildx-action@v3<br>- name: Log in to Google Cloud<br> uses: google-github-actions/auth@v1<br> with:<br> credentials_json: ${{ secrets.GCP_SA_KEY }}<br>- name: Configure gcloud CLI<br> run: gcloud config set project ${{ secrets.GCP_PROJECT }}<br>- name: Build and push Docker image<br> run: |<br> docker build -t gcr.io/${{ secrets.GCP_PROJECT }}/nodejs-api:latest .<br> docker push gcr.io/${{ secrets.GCP_PROJECT }}/nodejs-api:latest<br>deploy:<br> needs: build<br> runs-on: ubuntu-latest<br>steps:<br> - name: Checkout code<br> uses: actions/checkout@v3<br>- name: Log in to Google Cloud<br> uses: google-github-actions/auth@v1<br> with:<br> credentials_json: ${{ secrets.GCP_SA_KEY }}<br>- name: Deploy to GKE<br> run: |<br> kubectl apply -f k8s-deployment.yaml</pre><p>In GitHub, under <strong>Settings -&gt; Secrets</strong>, add the following:</p><p>• <strong>GCP_SA_KEY</strong>: Your Google Cloud service account JSON key.<br> • <strong>GCP_PROJECT</strong>: Your Google Cloud project ID.</p><p>Now, whenever you push to the main branch, the pipeline will automatically build and deploy your application to GKE.</p><h4>Production-Ready Essentials: Autoscaling, Health Checks, and Best Practices</h4><p>Now that we have an automated deployment pipeline, let’s get into making this a bit more production-ready. To be clear, we’re just covering the essentials here — you’ll still need to implement a lot more to have a fully robust production setup. For now, we’ll focus on autoscaling, health checks, and a few best practices.</p><h4>1. Autoscaling</h4><p>You don’t want your app to crash when it gets a spike in traffic. That’s where <strong>Horizontal Pod Autoscaling (HPA)</strong> comes in. HPA automatically adjusts the number of pods in your deployment based on CPU or memory usage.</p><p>First, enable autoscaling in your GKE cluster:</p><pre>gcloud container clusters update &lt;your-cluster-name&gt; — enable-autoscaling — min-nodes 1 — max-nodes 10</pre><p>Next, create a <strong>hpa.yaml</strong> file:</p><pre>apiVersion: autoscaling/v1<br>kind: HorizontalPodAutoscaler<br>metadata:<br> name: nodejs-api-hpa<br>spec:<br> scaleTargetRef:<br> apiVersion: apps/v1<br> kind: Deployment<br> name: nodejs-api<br> minReplicas: 3<br> maxReplicas: 10<br> targetCPUUtilizationPercentage: 80</pre><p>This tells Kubernetes to automatically scale the number of pods between 3 and 10 depending on CPU usage.</p><h4>2. Health Checks</h4><p>Adding liveness and readiness probes to your Kubernetes configuration ensures your app is healthy and only serving traffic when it’s ready.</p><p>Add these probes to your <strong>k8s-deployment.yaml</strong> file:</p><pre>livenessProbe:<br> httpGet:<br> path: /<br> port: 3000<br> initialDelaySeconds: 30<br> periodSeconds: 10<br>readinessProbe:<br> httpGet:<br> path: /<br> port: 3000<br> initialDelaySeconds: 5<br> periodSeconds: 5</pre><p>• Liveness probes check if your app is alive; if it fails, Kubernetes will restart the pod.<br> • Readiness probes check if your app is ready to receive traffic, ensuring that only healthy instances are used.</p><h4>3. Best Practices</h4><p>Here are a few best practices that will take you closer to a production setup:</p><p>• <strong>Resource Limits</strong>: Define CPU and memory limits for your pods to prevent one from hogging all the resources. Example:</p><pre>resources:<br> requests:<br> memory: “128Mi”<br> cpu: “500m”<br> limits:<br> memory: “512Mi”<br> cpu: “1000m”</pre><p>• <strong>Rolling Updates</strong>: Use Kubernetes’ built-in rolling update strategy to avoid downtime during deployments. Add this to your deployment:</p><pre>strategy:<br> type: RollingUpdate<br> rollingUpdate:<br> maxUnavailable: 1<br> maxSurge: 1</pre><h4>Conclusion</h4><p>We’ve gone from a simple Node.js API to an automated deployment pipeline on GKE using GitHub Actions. While this setup will work, it’s not fully production-ready — there’s still a lot more to think about like advanced monitoring, logging, secret management, and security hardening. But for now, you’ve got the foundation in place with autoscaling, health checks, and CI/CD. Take it from here, and continue building on this to fit your specific production needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55742479cab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Pagination with PostgreSQL Using Cursors]]></title>
            <link>https://medium.com/@ietienam/efficient-pagination-with-postgresql-using-cursors-83e827148118?source=rss-aed93ddf5f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/83e827148118</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Ini Etienam]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 00:37:24 GMT</pubDate>
            <atom:updated>2024-10-13T00:37:24.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="database cursor" src="https://cdn-images-1.medium.com/max/1024/0*-PRHr25_aVDDNORL" /><figcaption>Photo by <a href="https://unsplash.com/@umby?utm_source=medium&amp;utm_medium=referral">Umberto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Pagination</strong> is crucial for building scalable web applications, especially when displaying large datasets such as product listings. The most common approach is offset-based pagination, but it becomes inefficient with larger datasets. Instead, we can use <strong>cursor-based pagination</strong>, which is more efficient and scalable. This article explains how to implement pagination for a product listing page in Node.js with PostgreSQL using <strong>cursors</strong> while sorting products by their created_at timestamp.</p><p>We’ll cover important considerations, edge cases, and how to optimise performance.</p><p><strong><em>Why Use Cursor-Based Pagination Over Offset-Based Pagination?</em></strong></p><h4>Drawbacks of Offset-Based Pagination</h4><p><strong>Offset-based pagination</strong> works by using <strong><em>LIMIT</em></strong> and <strong><em>OFFSET</em></strong> in SQL queries like this:</p><pre>SELECT * FROM products ORDER BY created_at DESC LIMIT 20 OFFSET 40;</pre><p>While this method is simple, it leads to performance issues as your dataset grows. PostgreSQL must scan and skip rows before the offset value, so the larger the offset, the slower the query becomes. Additionally, inserting or deleting rows between paginated requests can cause skipped or duplicated results, leading to inconsistency.</p><h4>Benefits of Cursor-Based Pagination</h4><p><strong>Cursor-based pagination</strong> solves these issues by using a <strong>cursor</strong> (a reference point) to fetch the next set of results. Instead of skipping rows, it fetches rows based on the last result of the previous page, making it:</p><p>• <strong>Faster:</strong> It avoids scanning skipped rows.<br> • <strong>More Consistent:</strong> It prevents skipped or duplicated results, even when data is added or removed.<br> • <strong>Scalable:</strong> It handles large datasets efficiently.</p><p>For this example, we’ll use a <strong>compound cursor</strong> based on both the <strong><em>created_at</em></strong> timestamp and the <strong><em>id</em></strong> of the last product fetched.</p><h4>Step-by-Step Implementation of Cursor-Based Pagination</h4><h4>1. Setting Up the Project</h4><p>Start by creating a Node.js project and installing the PostgreSQL client (pg):</p><pre>npm init -y<br>npm install pg</pre><p>Set up a connection to your PostgreSQL database:</p><pre>const { Pool } = require(‘pg’);<br>// Set up PostgreSQL pool connection<br>const pool = new Pool({<br> user: &#39;your_username&#39;,<br> host: &#39;localhost&#39;,<br> database: &#39;your_database&#39;,<br> password: &#39;your_password&#39;,<br> port: 5432,<br>});</pre><h4>2. Create the Products Table</h4><p>We’ll assume you have a products table with columns id, name, price, and created_at:</p><pre>CREATE TABLE products (<br> id SERIAL PRIMARY KEY,<br> name VARCHAR(255),<br> price DECIMAL(10, 2),<br> created_at TIMESTAMPTZ DEFAULT NOW()<br>);</pre><p>— Insert some sample data</p><pre><br>INSERT INTO products (name, price)<br>SELECT ‘Product ‘ || i, (RANDOM() * 100)::DECIMAL(10,2)<br>FROM generate_series(1, 1000) i;</pre><p>This will serve as our dataset for the product listing page.</p><h4>3. Implementing Cursor-Based Pagination with a Compound Cursor</h4><p>To implement <strong>cursor-based pagination</strong>, we use both the <strong><em>created_at</em></strong> timestamp and the <strong><em>id</em></strong> of the last product fetched. This ensures pagination is stable and handles edge cases where multiple products have the same <strong><em>created_at</em></strong>.</p><p>Here’s the SQL query for paginating through products:</p><pre>SELECT * FROM products<br>WHERE (created_at &lt; $1 OR (created_at = $1 AND id &lt; $2))<br>ORDER BY created_at DESC, id DESC<br>LIMIT $3;</pre><p>In this query:</p><p>• $1 is the <strong><em>created_at</em></strong> value of the last product from the previous page.<br> • $2 is the <strong><em>id</em></strong> of the last product from the previous page.<br> • $3 is the number of products to fetch (e.g., 20).</p><p>For the first page, no cursor is passed, so we fetch the first 20 products ordered by created_at DESC and id DESC:</p><pre>SELECT * FROM products<br>ORDER BY created_at DESC, id DESC<br>LIMIT $1;</pre><h4>4. Node.js Implementation</h4><p>Now, let’s implement the Node.js function that handles pagination using a cursor:</p><pre>const getProductsWithCompoundCursor = async (limit, lastCreatedAt = null, lastId = null) =&gt; {<br> let query;<br> let params;<br>if (lastCreatedAt &amp;&amp; lastId) {<br> // For subsequent pages<br> query = `<br> SELECT * FROM products<br> WHERE (created_at &lt; $1 OR (created_at = $1 AND id &lt; $2))<br> ORDER BY created_at DESC, id DESC<br> LIMIT $3;<br> `;<br> params = [lastCreatedAt, lastId, limit];<br> } else {<br> // For the first page<br> query = `<br> SELECT * FROM products<br> ORDER BY created_at DESC, id DESC<br> LIMIT $1;<br> `;<br> params = [limit];<br> }<br>const result = await pool.query(query, params);<br> return result.rows;<br>};</pre><h4>Example Usage</h4><p>Here’s how to fetch the first page and subsequent pages using the function:</p><pre>const limit = 20; // Number of products per page<br>// Fetch the first page<br>getProductsWithCompoundCursor(limit).then(products =&gt; {<br> console.log(&#39;First page of products:&#39;, products);<br>// Fetch the next page using the last product&#39;s created_at and id as the cursor<br> if (products.length &gt; 0) {<br> const lastProduct = products[products.length - 1];<br> getProductsWithCompoundCursor(limit, lastProduct.created_at, lastProduct.id).then(nextPageProducts =&gt; {<br> console.log(&#39;Second page of products:&#39;, nextPageProducts);<br> });<br> }<br>});</pre><h4>Key Considerations</h4><h4>1. Handling Precision Issues with created_at</h4><p>The <strong><em>created_at</em></strong> field may have varying levels of precision, which could cause issues with pagination, especially when products have identical timestamps. To avoid this, ensure you’re using the same precision for <strong><em>created_at</em></strong> across the application. PostgreSQL handles this well with <strong><em>TIMESTAMPTZ</em></strong>.</p><h4>2. Handling Duplicate Timestamps</h4><p>Multiple products may share the same <strong><em>created_at</em></strong> value if they’re inserted simultaneously. This is where using <strong><em>id</em></strong> as part of the cursor helps: it ensures that even with the same timestamp, pagination will still work correctly because each product has a unique <strong><em>id</em></strong>.</p><p>The query:</p><pre>WHERE (created_at &lt; $1 OR (created_at = $1 AND id &lt; $2))</pre><p>ensures that if products have the same <strong><em>created_at</em></strong>, we still paginate correctly using <strong><em>id</em></strong>.</p><h4>3. Indexing for Better Performance</h4><p>Without proper indexing, the query could become slow as the dataset grows. Ensure you index both the <strong><em>created_at</em></strong> and <strong><em>id</em></strong> fields for efficient querying:</p><pre>CREATE INDEX idx_products_created_at ON products(created_at DESC, id DESC);</pre><p>This index will improve the performance of the <strong><em>ORDER BY</em></strong> and <strong><em>WHERE</em></strong> clauses in the pagination query.</p><h4>4. Handling NULL created_at Values</h4><p>If there are any rows with <strong><em>NULL</em></strong> values in the <strong><em>created_at</em></strong> column, pagination can break or produce incorrect results. To avoid this, ensure that the created_at field is <strong><em>NOT NULL</em></strong>:</p><pre>ALTER TABLE products ALTER COLUMN created_at SET NOT NULL;</pre><p>Alternatively, you can modify the query to exclude <strong><em>NULL</em></strong> values:</p><pre>SELECT * FROM products<br>WHERE created_at IS NOT NULL AND (created_at &lt; $1 OR (created_at = $1 AND id &lt; $2))<br>ORDER BY created_at DESC, id DESC<br>LIMIT $3;</pre><h4>Persisting the Cursor Across Requests</h4><p>To paginate across multiple requests, you need to persist the <strong>cursor</strong> values (<strong><em>created_at</em></strong> and <strong><em>id</em></strong>). This can be done using:</p><p><strong>1. URL Parameters:</strong> Pass the <strong><em>created_at</em></strong> and <strong><em>id</em></strong> as query parameters.<br><strong> 2. Session Storage:</strong> Store the <strong>cursor</strong> in the session or local storage.<br><strong>3. API Tokens:</strong> Use a token (e.g., a JWT or Base64-encoded string) to store the <strong>cursor</strong>.</p><p>Here’s an example of passing the <strong>cursor</strong> via URL parameters:</p><pre>app.get(‘/products’, async (req, res) =&gt; {<br> const { createdAt, id } = req.query;<br> const cursorCreatedAt = createdAt ? createdAt : null;<br> const cursorId = id ? parseInt(id, 10) : null;<br> <br> const products = await getProductsWithCompoundCursor(20, cursorCreatedAt, cursorId);<br>// Get the cursor for the next page (last product&#39;s created_at and id)<br> let nextCursorCreatedAt = null;<br> let nextCursorId = null;<br> <br> if (products.length &gt; 0) {<br> nextCursorCreatedAt = products[products.length - 1].created_at;<br> nextCursorId = products[products.length - 1].id;<br> }<br>res.json({<br> products,<br> nextCursor: { createdAt: nextCursorCreatedAt, id: nextCursorId }<br> });<br>});</pre><h4>Conclusion</h4><p>Using a <strong>compound cursor</strong> that combines both <strong><em>created_at</em></strong> and <strong><em>id</em></strong> is an efficient and reliable way to implement <strong>cursor-based pagination</strong> for a product listing page. This approach offers better performance and consistency compared to offset-based pagination, especially when dealing with large datasets.</p><h4>Key takeaways:</h4><p>• <strong>Compound cursor:</strong> Using both <strong><em>created_at</em></strong> and <strong><em>id</em></strong> ensures that pagination remains stable, even when products have identical timestamps.<br> • <strong>Indexing:</strong> Proper indexing on <strong><em>created_at</em></strong> and <strong><em>id</em></strong> improves query performance.<br> • <strong>Handle edge cases:</strong> Ensure <strong><em>created_at</em></strong> values are not <strong><em>NULL</em></strong> and handle any precision issues.</p><p>By implementing these best practices, you can create a scalable and efficient product listing page that offers a smooth user experience, even as your dataset grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83e827148118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Transactions with NestJs and RabbitMq]]></title>
            <link>https://medium.com/@ietienam/distributed-transactions-with-nestjs-and-rabbitmq-277d60d584c9?source=rss-aed93ddf5f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/277d60d584c9</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[distributed-transaction]]></category>
            <category><![CDATA[transactions]]></category>
            <dc:creator><![CDATA[Ini Etienam]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 14:03:53 GMT</pubDate>
            <atom:updated>2023-12-18T17:54:53.067Z</atom:updated>
            <content:encoded><![CDATA[<h4>Crafting robust distributed systems demands a smart approach. Here, we unravel how NestJS, a robust Node.js framework, teams up with RabbitMQ, an adept message broker, to sync transactions across multiple services.</h4><figure><img alt="Buy product transaction code" src="https://cdn-images-1.medium.com/max/1024/1*XyomigN3bVkjyheL8svSTQ.png" /></figure><p>Discover how NestJS’ structured design merges seamlessly with RabbitMQ’s messaging prowess to synchronize transactions among diverse microservices.</p><p>From fundamental concepts to practical implementation, this guide equips engineers to architect scalable, fault-tolerant systems. Explore how this powerful duo transforms backend engineering for seamless, distributed transactions.</p><p>What is a <strong><em>Distributed Transaction</em></strong>?</p><p>A distributed transaction refers to a process where multiple independent parts of a system need to work together as a single unit to perform a task or update data across different locations or services. It ensures that either all parts of the process are completed successfully or, if an error occurs in any part, the entire operation is rolled back to maintain consistency and integrity in the system. Essentially, it’s like coordinating several tasks spread across different places to guarantee they all happen correctly or none of them happen at all.</p><blockquote>A distributed transaction refers to a process where multiple independent parts of a system need to work together as a single unit to perform a task or update data across different locations or services.</blockquote><p>In this blog post, I’ll walk you through a practical implementation example of a distributed transaction system using NestJS and RabbitMQ within an inventory management scenario. Let’s dive into a simplified e-commerce setting where product listings, user purchases, and transactional operations are orchestrated across multiple microservices.</p><blockquote>The core aspect we’re exploring is how product availability, contingent on the product count, impacts the transactional flow.</blockquote><p><strong>Setting the Stage</strong></p><p>Imagine an e-commerce platform where product availability drives user transactions. Here, the availability of a product depends solely on its count – products with a count greater than 0 are up for grabs.</p><p>At the heart of this system lies NestJS, a robust microservices framework, and RabbitMQ, the linchpin for inter-service communication, crucial for orchestrating our distributed transactions.</p><p>We’ll dissect the intricacies of owners listing products and users initiating purchases, shedding light on how product count availability shapes the transactional orchestration across our microservices architecture.</p><p><strong>Product Listings and Availability Logic</strong></p><p>Owners populate the inventory with various products. Notably, only products boasting a count greater than 0 will be available for users to purchase.</p><p>Using the <em>repository pattern</em> with <strong>TypeOrm</strong>, here’s what our <strong>Product</strong> entity looks like</p><pre>import { Entity, Column, PrimaryGeneratedColumn } from &#39;typeorm&#39;;<br><br>@Entity()<br>export class Product {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  productName: string;<br><br>  @Column()<br>  count: number;<br><br>  @Column()<br>  price: string;<br>}</pre><p>On the <em>ProductService</em>, we have a <strong>getAvailableProducts</strong> method which calls the <strong>findAllInStock</strong> method in our <em>productRepository</em> file.</p><p>Here’s what the basic <strong>findAllInStock </strong>implementation looks like</p><pre>findAllInStock(): Promise&lt;Product[]&gt; {<br>    return this.productRepository.find({<br>      where: {<br>        count: MoreThan(0),<br>      },<br>    });<br>  }</pre><p>Here, we only list products with a count greater than 0.</p><p><strong>User Purchase Workflow</strong></p><p>When users express interest in buying a product, the system meticulously checks its availability, ensuring only products with an available count can be initiated for purchase.</p><p><strong>Transaction Flowchart</strong></p><p>Upon confirming a product’s availability, the system locks it to prevent parallel transactions. Within the transaction, we check if the product has enough in stock to be purchased. Once the transaction is committed, we emit an event which a payment service can listen to for making payments.</p><pre>async buyProduct(id: number, count: number): Promise&lt;void&gt; {<br>    const queryRunner = this.dataSource.createQueryRunner();<br><br>    await queryRunner.connect();<br>    await queryRunner.startTransaction();<br>    try {<br>      const product = await queryRunner.manager.findOneBy(Product, { id });<br><br>      if (product.count - count &gt;= 0) {<br>        product.count = product.count - count;<br>        await queryRunner.manager.save(product);<br>      }<br><br>      await queryRunner.commitTransaction();<br>      await this.productEventProducer.send({<br>        productId: product.id,<br>        price: product.price,<br>        count: product.count,<br>      });<br>    } catch (err) {<br>      // since we have errors lets rollback the changes we made<br>      await queryRunner.rollbackTransaction();<br>    } finally {<br>      // you need to release a queryRunner which was manually instantiated<br>      await queryRunner.release();<br>    }<br>  }</pre><p><strong>Payment Handling and Rollback Mechanism</strong></p><p>Successfully processed payments finalize the transaction. Conversely, payment failures prompt a rollback mechanism, reversing the transaction, restoring the product count, and reinstating it for future purchases.</p><p>Lets assume the service responsible for making payments failed for some reason. If this occurs, we need to update the product count back to its original state. One way we could do this is emit an event from payment service which we will consume within the inventory service to update the product count</p><pre>export class ProductEventConsumer implements OnModuleInit {<br>  private readonly logger = new Logger(ProductEventConsumer.name);<br>  private channel: amqp.Channel;<br><br>  constructor(private productRepository: ProductRepository) {}<br><br>  async onModuleInit() {<br>    const connection = await amqp.connect(<br>      &#39;amqps://&#39;,<br>    );<br>    this.channel = await connection.createChannel();<br>    await this.channel.assertQueue(&#39;update-product&#39;, { durable: true });<br>    await this.channel.bindQueue(&#39;update-product&#39;, &#39;payment-service&#39;, &#39;&#39;);<br>    await this.processUpdateProductCountEvent();<br>  }<br><br>  private async processUpdateProductCountEvent() {<br>    this.channel.consume(&#39;update-product&#39;, async (message) =&gt; {<br>      if (message) {<br>        let content: { productId: number; count: number };<br>        try {<br>          content = JSON.parse(message.content.toString());<br>          this.productRepository<br>            .updateProductCount(content.productId, content.count)<br>            .then(() =&gt; {<br>              this.channel.ack(message);<br>            });<br>        } catch (error) {<br>          this.logger.error(&#39;Invalid message format&#39;, error);<br>          this.channel.ack(message);<br>        }<br>      }<br>    });<br>  }<br>}</pre><pre>async updateProductCount(id: number, count: number): Promise&lt;void&gt; {<br>    const queryRunner = this.dataSource.createQueryRunner();<br><br>    await queryRunner.connect();<br>    await queryRunner.startTransaction();<br>    try {<br>      const product = await queryRunner.manager.findOneBy(Product, { id });<br>      product.count = product.count + count;<br>      await queryRunner.manager.save(product);<br><br>      await queryRunner.commitTransaction();<br>    } catch (err) {<br>      await queryRunner.rollbackTransaction();<br>    } finally {<br>      await queryRunner.release();<br>    }<br>  }</pre><p><strong>Event-Driven Backbone</strong></p><p>RabbitMQ seamlessly manages asynchronous communication between microservices, ensuring the smooth exchange of events throughout the transactional flow.</p><p>By showcasing the collaboration between NestJS and RabbitMQ, we emphasize the criticality of product availability driven by the product count in orchestrating distributed transactions. This example underscores the reliability and consistency achieved in an e-commerce ecosystem.</p><p><a href="https://github.com/ietienam/distributed-transactions-with-nestjs-and-rabbitmq"><strong>GitHub</strong></a></p><p><a href="https://linkedin.com/in/ietienam"><strong>LinkedIn</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=277d60d584c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a NestJs API Gateway with gRPC microservice]]></title>
            <link>https://medium.com/@ietienam/building-a-nestjs-api-gateway-with-grpc-microservice-35c900eba85e?source=rss-aed93ddf5f14------2</link>
            <guid isPermaLink="false">https://medium.com/p/35c900eba85e</guid>
            <category><![CDATA[micoservices]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Ini Etienam]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 17:48:50 GMT</pubDate>
            <atom:updated>2024-01-09T14:30:13.015Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a NestJS API Gateway with gRPC Microservice</h3><figure><img alt="Auth module connecting to gRPC service" src="https://cdn-images-1.medium.com/max/1024/1*jPhcl_6RHVIAJw4oZKNNYw.png" /></figure><p>Ever wondered how different technologies come together to create something awesome? Well, get ready for an adventure into the world of software development!</p><p>I will be sharing a high-level overview on how NestJs, gRPC, Docker and RabbitMq come together in a microservice architecture exposed through an API gateway.</p><p>To get the most out of this, you should be familiar with microservice architecture, gRPC, rabbitMQ, nestJs, typescript, mongodb, docker and event-driven architecture.</p><p>Lets start by defining some terms.</p><p><strong>NestJs: </strong>NestJS is a progressive Node.js framework utilizing TypeScript and architectural patterns inspired by Angular to efficiently build scalable and maintainable server-side applications.</p><p><strong>gRPC: </strong>gRPC is a high-performance, open-source Remote Procedure Call (RPC) framework developed by Google. It enables efficient communication between distributed systems by allowing applications written in different languages to interact with each other easily. It uses Protocol Buffers (protobuf) as the default serialization mechanism for data exchange and HTTP/2 as the underlying protocol, offering features like bi-directional streaming, authentication, and automatic code generation for multiple programming languages.</p><p><strong>Docker:</strong> Docker is a platform that simplifies the process of creating, deploying, and managing applications using containerization, enabling developers to package their applications and dependencies into portable containers that can run consistently across different environments.</p><p><strong>RabbitMq: </strong>RabbitMQ is an open-source message broker software that enables communication between distributed systems by facilitating the exchange of messages between various components or services in a flexible, reliable, and scalable manner using different messaging protocols like AMQP (Advanced Message Queuing Protocol) and others.</p><p><strong>API Gateway: </strong>An API gateway is a server that acts as a single entry point for multiple backend services or APIs. It manages, routes, and secures incoming client requests, often performing tasks like authentication, request routing, load balancing, and protocol translation to ensure smooth communication between clients and various backend services.</p><p><strong>Microservice: </strong>Microservices are a software architecture approach where an application is structured as a collection of loosely coupled, independently deployable services. Each service, or microservice, focuses on a specific business function and operates as a small, self-contained unit. They communicate via well-defined APIs, enabling flexibility, scalability, and easier maintenance compared to traditional monolithic architectures.</p><p><strong>Event-driven architecture:</strong> Event-driven architecture (EDA) is a software design approach where the generation, detection, and reaction to events are central to the way applications are structured and interconnected. It revolves around the production, detection, consumption, and reaction to events that occur within a system or between systems. Components within an event-driven architecture communicate asynchronously by producing or consuming events, allowing for loose coupling, scalability, and responsiveness in handling various operations and changes within a system.</p><p>Our final folder structure will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*zd6oXSLs8aZ-i7e7-bg1OA@2x.jpeg" /></figure><p>Each of these folders represents a separate repository.</p><ul><li><strong>service-protos </strong>is a repository that will contain our protobuf files. This service will act as our package published on GitHub registry. It will contain typescript generated from our protobuf files and we will use this package in our <strong>user-service</strong> and <strong>gateway</strong></li><li><strong>user-service </strong>will be our gRPC service that will contain logic for user signup. This service will publish an event after signup which the <strong>notification-service</strong> will consume. This service will use our <strong>service-protos</strong> package and will be published as a docker image to GitHub registry. This image will be used by the <strong>gateway</strong> to startup the service</li><li><strong>notification-service </strong>will consume events published to our <strong>RabbitMq </strong>cluster and perform appropriate actions</li><li><strong>gateway </strong>is our api gateway which will expose our rest endpoints. We will use our <strong>user-service</strong> image and <strong>service-protos </strong>package to process and initiate requests respectively.</li></ul><p>Github repository provided at the end.</p><h3>1. Creating a service-protos service</h3><p>This service will contain the proto files which the user-service and gateway will use to communicate with each other. Proto files are a blueprint that defines the methods allowed and structure of data sent and received through RPC calls.</p><p>Let us create our <em>user.proto</em> file. If you are coding along, this file should be in <em>src/proto/users</em></p><pre>syntax = &quot;proto3&quot;;<br><br>package user;<br><br>import &quot;google/protobuf/struct.proto&quot;;<br><br>message ServiceResponse {<br>    int32 statusCode = 1;<br>    string message = 2;<br>    google.protobuf.Struct data = 3;<br>}<br>  <br>message RegisterUserRequest {<br>    string firstName = 1;<br>    string lastName = 2;<br>    string email = 3;<br>    string phone = 4;<br>    string role = 5;<br>    string password = 6;<br>}<br>  <br>message RegisterUserResponse {<br>    ServiceResponse data = 1;<br>}<br><br>service UserService {<br>  rpc RegisterCustomer(RegisterUserRequest) returns (ServiceResponse);<br>}</pre><p>Above, we have 3 messages that describes the data structure for a <em>ServiceResponse</em>, <em>RegisterUserRequest</em> and <em>RegisterUserResponse</em> respectively. We also have an rpc method <em>RegisterCustomer</em>, which at the moment is the only method accepted in the user service.</p><p>Next, we need to generate typscript files from proto files and to do this, run the following command:</p><pre>npm install ts-proto typescript rimraf mkdirp -D</pre><pre>npm install protobufjs @grpc/grpc-js</pre><p>After installing the packages, create a build.sh file</p><pre>#!/bin/bash<br>protoc --plugin=$(npm root)/.bin/protoc-gen-ts_proto \<br> --ts_proto_out=dist \<br> --ts_proto_opt=outputServices=grpc-js \<br> --ts_proto_opt=esModuleInterop=true \<br> -I=src/ src/**/**/*.proto</pre><p>This script is responsible for taking `.proto` files located within the `src` directory (and its subdirectories) and generating TypeScript code using the `ts_proto` plugin.</p><p>Next, add this script to package.json</p><pre>&quot;build&quot;: &quot;rimraf dist &amp;&amp; mkdirp dist &amp;&amp; chmod +x ./build.sh &amp;&amp; ./build.sh &amp;&amp; tsc &amp;&amp; cp -r src/proto ./dist/src&quot;</pre><p>We want to bundle this into a package which can be used easily in any service by simply installing it via npm. We will be publishing this to github registry and to do this, create a <em>proto-npm-publish.yml</em> file with contents as shown below:</p><pre>name: Publish Package to GitHub Packages<br><br>on:<br>  push:<br>    branches:<br>      - main<br><br>jobs:<br>  publish:<br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: read<br>      packages: write<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v3<br><br>      - name: Set up Node.js<br>        uses: actions/setup-node@v3<br>        with:<br>          node-version: &#39;16.x&#39;<br>          registry-url: &#39;https://npm.pkg.github.com&#39;<br>          # Defaults to the user or organization that owns the workflow file<br>          scope: &#39;@ietienam&#39;<br><br>      - name: Install dependencies<br>        run: npm ci<br><br>      - name: Install Protoc<br>        uses: arduino/setup-protoc@v2<br><br>      - name: Generate TypeScript files from proto<br>        run: npm run build<br><br>      - name: Publish to GitHub Packages<br>        run: npm publish --registry=https://npm.pkg.github.com/<br>        env:<br>          NODE_AUTH_TOKEN: ${{ secrets.GH_TOKEN }}<br><br>      - name: Cleanup<br>        run: rm -f ~/.npmrc</pre><p>This will trigger the build and create a package any time we push to main. Make sure you have created secrets with the right permission or this will fail</p><h3>2. Creating a gRPC user service</h3><p>Create a nodejs project and install the package we created from service-protos by running the command:</p><p>Before running the command, create a .npmrc file to authenticate your request to github registry. Your .npmrc file should look like this.</p><pre>@ietienam:registry=<br>//npm.pkg.github.com/:_authToken=your-github-token</pre><pre>npm install @ietienam/service-protos@latest</pre><p>Create a database model for your user. In our case, we are using mongodb as shown below.</p><pre>import mongoose from &#39;mongoose&#39;;<br>import { Customer } from &quot;@ietienam/service-protos/dist/proto/users/user&quot;;<br><br>interface CustomerDto extends Customer {<br>  password: string,<br>  verifyToken: string,<br>  resetToken?: string,<br>  resetTokenExpires?: Date,<br>}<br><br>const customerSchema = new mongoose.Schema&lt;CustomerDto, CustomerDto&gt;(<br>  {<br>    firstName: {<br>      type: String,<br>      required: true,<br>      trim: true,<br>    },<br>    lastName: {<br>      type: String,<br>      required: true,<br>      trim: true,<br>    },<br>    email: {<br>      type: String,<br>      required: true,<br>      unique: true,<br>      trim: true,<br>      lowercase: true,<br>    },<br>    role: {<br>      type: String,<br>      enum: [&quot;CUSTOMER&quot;],<br>      required: true,<br>      default: &quot;CUSTOMER&quot;,<br>    },<br>    phone: {<br>      type: String,<br>      required: true,<br>      unique: true,<br>    },<br>    password: {<br>      type: String,<br>      required: [true, &#39;Please add a password&#39;],<br>      minlength: 6,<br>    },<br>    isVerified: {<br>      type: Boolean,<br>      required: true,<br>      default: false,<br>    },<br>    verifyToken: {<br>      type: String,<br>      required: true,<br>    },<br>    resetToken: String,<br>    resetTokenExpires: Date,<br>  },<br>  {<br>    toJSON: {<br>      virtuals: true,<br>    },<br>    toObject: {<br>      virtuals: true,<br>    },<br>    timestamps: true,<br>  },<br>);<br>const CustomerModel = mongoose.model(&#39;Customer&#39;, customerSchema);<br><br>export default CustomerModel;</pre><p>Create a service file that contains the registerCustomer logic as shown below</p><pre>// imports<br><br>const jwtService = new JwtService();<br><br>export const registerCustomer = async (<br>  call: ServerUnaryCall&lt;RegisterUserRequest, RegisterUserResponse&gt;,<br>  callback: sendUnaryData&lt;ServiceResponse&gt;<br>) =&gt; {<br>  try {<br>    const password = jwtService.encodePassword(call.request.password);<br>    const verifyTokens = generateVerifyToken();<br>    const payload = {<br>      ...call.request,<br>      password,<br>      verifyToken: verifyTokens.hashedVerifyToken,<br>    };<br><br>    const customer = await Customer.default.create(payload).then((data) =&gt; {<br>      return {<br>        id: data.id,<br>        firstName: data.firstName,<br>        lastName: data.lastName,<br>        email: data.email,<br>        role: data.role,<br>        phone: data.phone,<br>        isVerified: data.isVerified,<br>        createdAt: data.createdAt,<br>        updatedAt: data.updatedAt,<br>      };<br>    });<br><br>    const data: VerifyCustomerEventData = {<br>      id: customer.id,<br>      email: customer.email,<br>      name: customer.firstName,<br>      verifyToken: verifyTokens.verifyToken,<br>    };<br><br>    await eventPublisher.publishEvent&lt;VerifyCustomerEventData&gt;(<br>      EventTypes.VERIFY_CUSTOMER,<br>      data<br>    );<br><br>    return callback(null, responseHandler(customer));<br>  } catch (error) {<br>    // log error<br>    return callback(null, responseHandler(error));<br>  }<br>};<br><br>export const generateVerifyToken = () =&gt; {<br>  const verifyToken = crypto.randomBytes(32).toString(&quot;hex&quot;);<br>  return {<br>    verifyToken,<br>    hashedVerifyToken: crypto<br>      .createHash(&quot;sha256&quot;)<br>      .update(verifyToken)<br>      .digest(&quot;hex&quot;),<br>  };<br>};</pre><p>Create a docker file and docker-compose file</p><pre>FROM node:18-alpine<br><br>WORKDIR &quot;/app&quot;<br><br>COPY npmrc.sh package.json tsconfig.json ./<br><br>RUN chmod +x ./npmrc.sh &amp;&amp; sh npmrc.sh <br><br>RUN npm install npm@latest<br><br>RUN npm ci<br><br>COPY . .<br><br>CMD [ &quot;npm&quot;, &quot;run&quot;, &quot;start&quot; ]<br><br># Expose the gRPC port<br>EXPOSE 50051</pre><pre>version: &#39;3&#39;<br><br>services:<br>  app:<br>    container_name: user-service<br>    build: .<br>    restart: always<br>    env_file: .env<br>    expose:<br>      - ${USER_SERVICE_PORT}<br>    ports:<br>      - ${USER_SERVICE_PORT}:${USER_SERVICE_PORT}<br>    environment:<br>      - USER_SERVICE_DATABASE=${USER_SERVICE_DATABASE}<br>      - NODE_ENV=${NODE_ENV}<br>      - USER_SERVICE_PORT=${USER_SERVICE_PORT}<br>      - RABBITMQ_URL=${RABBITMQ_URL}<br>    networks:<br>      - backend<br>    command: npm run start<br>    volumes:<br>      - .:/app<br>      - /app/node_modules<br><br>volumes:<br>  app:<br>networks:<br>  backend:<br>    driver: bridge</pre><p>Your server.ts file should look like this</p><pre>// imports<br><br>export const eventPublisher = new EventPublisher();<br><br>async function start() {<br>  try {<br>    await mongoose<br>      .connect(config.mongoose.url)<br>      .then(async () =&gt; {<br>        await eventPublisher.connectToRabbitMQ();<br>      })<br>      .then(() =&gt; {<br>        const server = new Server();<br>        server.addService(UserServiceService, { ...userService });<br><br>        server.bindAsync(<br>          `0.0.0.0:${config.port}`,<br>          ServerCredentials.createInsecure(),<br>          (error, port) =&gt; {<br>            if (error) throw error;<br>            console.log(`gRPC server running on port ${port}`);<br>            server.start();<br>          }<br>        );<br>      });<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>start();</pre><p>Above, we initialize a connection to the database, and then to our rabbitmq server and then finally, we start our grpc server.</p><p>Now, we need to create an image each time we push to main so the gateway always uses the updated image. Below, we create a docker-image-publish.yml file with its contents</p><pre>#<br>name: Create and publish a Docker image<br><br># Configures this workflow to run every time a change is pushed to the branch called `main`.<br>on:<br>  push:<br>    branches: [&#39;main&#39;]<br><br># Defines two custom environment variables for the workflow. These are used for the Container registry domain, and a name for the Docker image that this workflow builds.<br>env:<br>  REGISTRY: ghcr.io<br>  IMAGE_NAME: ${{ github.repository }}<br><br># There is a single job in this workflow. It&#39;s configured to run on the latest available version of Ubuntu.<br>jobs:<br>  build-and-push-image:<br>    runs-on: ubuntu-latest<br>    # Sets the permissions granted to the `GH_TOKEN` for the actions in this job.<br>    permissions:<br>      contents: read<br>      packages: write<br>      # <br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v3<br>      # Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here.<br>      - name: Log in to the Container registry<br>        uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1<br>        with:<br>          registry: ${{ env.REGISTRY }}<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GH_TOKEN }}<br>      # This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` &quot;meta&quot; allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels.<br>      - name: Extract metadata (tags, labels) for Docker<br>        id: meta<br>        uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7<br>        with:<br>          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}<br>      # This step uses the `docker/build-push-action` action to build the image, based on your repository&#39;s `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages.<br>      # It uses the `context` parameter to define the build&#39;s context as the set of files located in the specified path. For more information, see &quot;[Usage](https://github.com/docker/build-push-action#usage)&quot; in the README of the `docker/build-push-action` repository.<br>      # It uses the `tags` and `labels` parameters to tag and label the image with the output from the &quot;meta&quot; step.<br>      - name: Build and push Docker image<br>        uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4<br>        with:<br>          context: .<br>          push: true<br>          tags: ${{ steps.meta.outputs.tags }}<br>          labels: ${{ steps.meta.outputs.labels }}</pre><p>In this section, we covered the key components required process rpc requests. These key components were the function that interacts with the database, using the built service-protos package and starting our rpc server.</p><h3>3. Creating a notification-service</h3><p>This service will consume events created in the user service within the register user functionality.</p><p>Create a nestjs project.</p><p>Inside your src directory, create two modules, consumer and producer. We will only focus on the consumer module for now.</p><p>Within the Consumer module, create a user service module which will be responsible for consuming events from Queues in the user domain.</p><p>Below, you will find what your user module should look like</p><pre>// imports<br><br>@Module({<br>  imports: [<br>    ClientsModule.register([<br>      {<br>        name: USER_SERVICE_EXCHANGE,<br>        transport: Transport.RMQ,<br>        options: {<br>          urls: [process.env.RABBITMQ_URL],<br>          queue: USER_SERVICE_QUEUE,<br>          noAck: false,<br>          prefetchCount: 100000,<br>          queueOptions: {<br>            durable: true,<br>          },<br>        },<br>      },<br>    ]),<br>    EmailModule,<br>  ],<br>  providers: [UserServiceService],<br>})<br>export class UserServiceModule {}</pre><p>Next, create a user service file within the user module. This file will contain the logic for the consumer and how different event types will and should be processed</p><pre>import { Inject, Injectable, Logger, OnModuleInit } from &#39;@nestjs/common&#39;;<br>import { ClientRMQ } from &#39;@nestjs/microservices&#39;;<br>import { USER_SERVICE_QUEUE, USER_SERVICE_EXCHANGE } from &#39;./constants&#39;;<br>import * as amqp from &#39;amqplib&#39;;<br>import { EventData, EventTypes } from &#39;../types&#39;;<br>import { EmailService } from &#39;../email/email.service&#39;;<br><br>@Injectable()<br>export class UserServiceService implements OnModuleInit {<br>  private readonly logger = new Logger(UserServiceService.name);<br>  private channel: amqp.Channel;<br><br>  @Inject(USER_SERVICE_EXCHANGE)<br>  private readonly client: ClientRMQ;<br><br>  constructor(private readonly emailService: EmailService) {}<br><br>  async onModuleInit() {<br>    const connection = await amqp.connect(process.env.RABBITMQ_URL);<br>    this.channel = await connection.createChannel();<br>    await this.channel.assertQueue(USER_SERVICE_QUEUE);<br>    await this.processEvents();<br>  }<br><br>  private async processEvents() {<br>    this.channel.consume(USER_SERVICE_QUEUE, async (message) =&gt; {<br>      if (message) {<br>        let content: EventData&lt;any&gt;;<br>        try {<br><br>          content = JSON.parse(message.content.toString());<br><br>          switch (content.eventType) {<br>            case EventTypes.VERIFY_CUSTOMER:<br>              await this.emailService<br>              .sendWelcomeCustomer(content.data)<br>              .then(() =&gt; {<br>                this.channel.ack(message);<br>              })<br>              .catch((error) =&gt; {<br>                this.logger.error(<br>                  &#39;Failed to send sendWelcomeCustomer Email&#39;,<br>                  error,<br>                );<br>              });<br>              break;<br>            default:<br>              break;<br>          }<br>        } catch (error) {<br>          this.logger.error(&#39;Invalid message format&#39;, error);<br>          this.channel.ack(message);<br>        }<br>      }<br>    });<br>  }<br>}</pre><p>Next, we create a docker file and compose file respectively which we will use to create an image for this service</p><pre>FROM node:18-alpine<br><br>WORKDIR &quot;/app&quot;<br><br>COPY npmrc.sh package.json tsconfig.json ./<br><br>RUN chmod +x ./npmrc.sh &amp;&amp; sh npmrc.sh <br><br>RUN npm install npm@latest<br><br>RUN npm ci<br><br>COPY . .<br><br>CMD [ &quot;npm&quot;, &quot;run&quot;, &quot;start&quot; ]<br><br>EXPOSE 3000</pre><pre>version: &#39;3&#39;<br><br>services:<br>  app:<br>    container_name: notification-service<br>    build: .<br>    restart: always<br>    env_file: .env<br>    expose:<br>      - ${NOTIFICATION_SERVICE_PORT}<br>    ports:<br>      - ${NOTIFICATION_SERVICE_PORT}:${NOTIFICATION_SERVICE_PORT}<br>    environment:<br>      - MAIL_HOST=${MAIL_HOST}<br>      - SMTP_USERNAME=${SMTP_USERNAME}<br>      - SMTP_PASSWORD=${SMTP_PASSWORD}<br>      - API_GATEWAY_URL=${API_GATEWAY_URL}<br>      - NOTIFICATION_SERVICE_PORT=${NOTIFICATION_SERVICE_PORT}<br>      - RABBITMQ_URL=${RABBITMQ_URL}<br>    networks:<br>      - backend<br>    command: npm run start<br>    volumes:<br>      - .:/app<br>      - /app/node_modules<br>volumes:<br>  app:<br>networks:<br>  backend:<br>    driver: bridge</pre><p>Finally, we create a github action to build an image each time we push to main</p><pre>#<br>name: Create and publish a Docker image<br><br># Configures this workflow to run every time a change is pushed to the branch called `main`.<br>on:<br>  push:<br>    branches: [&#39;main&#39;]<br><br># Defines two custom environment variables for the workflow. These are used for the Container registry domain, and a name for the Docker image that this workflow builds.<br>env:<br>  REGISTRY: ghcr.io<br>  IMAGE_NAME: ${{ github.repository }}<br><br># There is a single job in this workflow. It&#39;s configured to run on the latest available version of Ubuntu.<br>jobs:<br>  build-and-push-image:<br>    runs-on: ubuntu-latest<br>    # Sets the permissions granted to the `GH_TOKEN` for the actions in this job.<br>    permissions:<br>      contents: read<br>      packages: write<br>      # <br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v3<br>      # Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here.<br>      - name: Log in to the Container registry<br>        uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1<br>        with:<br>          registry: ${{ env.REGISTRY }}<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GH_TOKEN }}<br>      # This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` &quot;meta&quot; allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels.<br>      - name: Extract metadata (tags, labels) for Docker<br>        id: meta<br>        uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7<br>        with:<br>          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}<br>      # This step uses the `docker/build-push-action` action to build the image, based on your repository&#39;s `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages.<br>      # It uses the `context` parameter to define the build&#39;s context as the set of files located in the specified path. For more information, see &quot;[Usage](https://github.com/docker/build-push-action#usage)&quot; in the README of the `docker/build-push-action` repository.<br>      # It uses the `tags` and `labels` parameters to tag and label the image with the output from the &quot;meta&quot; step.<br>      - name: Build and push Docker image<br>        uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4<br>        with:<br>          context: .<br>          push: true<br>          tags: ${{ steps.meta.outputs.tags }}<br>          labels: ${{ steps.meta.outputs.labels }}</pre><p>Now, we have a notification service that listens to a queue and consumes events(sends an email)each time a user signs up</p><h3>4. API Gateway</h3><p>So far, we have a service-protos service which contains our proto files bundled into an npm package.</p><p>We have a user service which is a nodejs gRPC service that processes requests and emits an event.</p><p>We have a notification service which consumes events and sends an email after user signups.</p><p>With the exception of service-protos service, each service has been dockerized and is an image which we can use in the API Gateway.</p><p>Lets work our way around doing this.</p><p>Create a nestjs project.</p><p>In your package.json, your scripts should look like this</p><pre>&quot;scripts&quot;: {<br>    &quot;preinstall&quot;: &quot;chmod +x ./npmrc.sh &amp;&amp; sh npmrc.sh&quot;,<br>    &quot;build&quot;: &quot;nest build&quot;,<br>    &quot;format&quot;: &quot;prettier --write \&quot;src/**/*.ts\&quot; \&quot;test/**/*.ts\&quot;&quot;,<br>    &quot;start&quot;: &quot;nest start&quot;,<br>    &quot;start:dev&quot;: &quot;docker compose -f docker-compose-dev.yml up --build&quot;,<br>    &quot;dev&quot;: &quot;nest start --watch&quot;,<br>    &quot;start:debug&quot;: &quot;nest start --debug --watch&quot;,<br>    &quot;start:prod&quot;: &quot;node dist/main&quot;,<br>    &quot;lint&quot;: &quot;eslint \&quot;{src,apps,libs,test}/**/*.ts\&quot; --fix&quot;,<br>    &quot;test&quot;: &quot;jest&quot;,<br>    &quot;test:watch&quot;: &quot;jest --watch&quot;,<br>    &quot;test:cov&quot;: &quot;jest --coverage&quot;,<br>    &quot;test:debug&quot;: &quot;node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand&quot;,<br>    &quot;test:e2e&quot;: &quot;jest --config ./test/jest-e2e.json&quot;,<br>    &quot;proto:install&quot;: &quot;npm i @ietienam/service-protos@latest &amp;&amp; npm run proto:all&quot;,<br>    &quot;proto:all&quot;: &quot;npm run proto:user&quot;,<br>    &quot;proto:user&quot;: &quot;protoc --plugin=node_modules/.bin/protoc-gen-ts_proto.cmd -I=./node_modules/@ietienam/service-protos/dist/src/users --ts_proto_out=src/constants/ node_modules/@ietienam/service-protos/dist/src/users/user.proto --ts_proto_opt=nestJs=true --ts_proto_opt=fileSuffix=.pb&quot;,<br>  },</pre><p>Next, create a .npmrc file and its contents should look like this</p><pre>@ietienam:registry=https://npm.pkg.github.com<br>//npm.pkg.github.com/:_authToken=your-github-token</pre><p>Next, create a npmrc.sh file with the following contents</p><pre>#!/bin/bash<br><br># Check if .env file exists<br>if [ -f .env ]; then<br>    # Load environment variables from .env file<br>    source ./.env<br><br>    # Delete .npmrc file<br>    rm .npmrc<br><br>    # Update .npmrc file<br>    echo &quot;@ietienam:registry=https://npm.pkg.github.com&quot; &gt;&gt; .npmrc<br>    echo &quot;//npm.pkg.github.com/:_authToken=$GH_TOKEN&quot; &gt;&gt; .npmrc<br>else<br>    # Delete .npmrc file<br>    rm .npmrc<br><br>    # Update .npmrc file<br>    echo &quot;@ietienam:registry=https://npm.pkg.github.com&quot; &gt;&gt; .npmrc<br>    echo &quot;//npm.pkg.github.com/:_authToken=your-github-token&quot; &gt;&gt; .npmrc<br>fi</pre><p>These files are to authenticate requests to github registry when installing your service-protos package</p><p>Now install your service protos package. by running the command</p><pre>npm install @ietienam/service-protos@latest</pre><p>Next, run the command</p><pre>npm run proto:all</pre><p>The command above will extract the generate typescript files from your proto package and save it in your constant directory.</p><p>Next, create an auth module. This auth module should connect to your user service gRPC server. Below, you will find an implementation</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ClientsModule, Transport } from &#39;@nestjs/microservices&#39;;<br>import { AuthController } from &#39;./auth.controller&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br>import { USER_SERVICE_NAME, USER_PACKAGE_NAME } from &#39;../../constants/user.pb&#39;;<br>import { CacheModule } from &#39;@nestjs/cache-manager&#39;;<br>import { CacheService } from &#39;src/services/cache.service&#39;;<br><br>@Module({<br>  imports: [<br>    CacheModule.register(),<br>    ClientsModule.register([<br>      {<br>        name: USER_SERVICE_NAME,<br>        transport: Transport.GRPC,<br>        options: {<br>          url: `${process.env.USER_SERVICE_HOST}:${process.env.USER_SERVICE_PORT}`,<br>          package: USER_PACKAGE_NAME,<br>          protoPath:<br>            &#39;node_modules/@ietienam/service-protos/dist/src/users/user.proto&#39;,<br>        },<br>      },<br>    ]),<br>  ],<br>  controllers: [AuthController],<br>  providers: [AuthService, CacheService],<br>  exports: [AuthService],<br>})<br>export class AuthModule {}</pre><p>In your auth service file, create a register customer method which calls your user service gRPC client. It should also pass data your gRPC client expects as defined in your proto file. Below you will find an example</p><pre>import { Inject, Injectable, OnModuleInit } from &#39;@nestjs/common&#39;;<br>import { ClientGrpc } from &#39;@nestjs/microservices&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import {<br>  UserServiceClient,<br>  USER_SERVICE_NAME,<br>  RegisterCustomerRequest,<br>  ServiceResponse,<br>} from &#39;../../constants/user.pb&#39;;<br>import { CacheService } from &#39;src/services/cache.service&#39;;<br><br>@Injectable()<br>export class AuthService implements OnModuleInit {<br>  constructor(private readonly cacheService: CacheService) {}<br><br>  private userService: UserServiceClient;<br><br>  @Inject(USER_SERVICE_NAME)<br>  private readonly client: ClientGrpc;<br><br>  public onModuleInit(): void {<br>    this.userService =<br>      this.client.getService&lt;UserServiceClient&gt;(USER_SERVICE_NAME);<br>  }<br><br>  public async registerCustomer(<br>    request: RegisterCustomerRequest,<br>  ): Promise&lt;Observable&lt;ServiceResponse&gt;&gt; {<br>    return this.userService.registerCustomer(request);<br>  }<br>}</pre><p>Next, we create an auth controller which exposes the registerCustomer rpc call as a rest endpoint</p><pre>// imports<br>@Module({<br>  imports: [<br>    CacheModule.register(),<br>    ClientsModule.register([<br>      {<br>        name: USER_SERVICE_NAME,<br>        transport: Transport.GRPC,<br>        options: {<br>          url: `${process.env.USER_SERVICE_HOST}:${process.env.USER_SERVICE_PORT}`,<br>          package: USER_PACKAGE_NAME,<br>          protoPath:<br>            &#39;node_modules/@ietienam/service-protos/dist/src/users/user.proto&#39;,<br>        },<br>      },<br>    ]),<br>  ],<br>  controllers: [AuthController],<br>  providers: [AuthService, CacheService],<br>  exports: [AuthService],<br>})<br>export class AuthModule {}</pre><p>Finally, we create a docker file and compose file respectively. Our compose file will reference the images we of user-service and notification service we created and built previously on github.</p><pre>FROM node:18-alpine<br><br>WORKDIR &quot;/app&quot;<br><br>COPY npmrc.sh package*.json tsconfig.json ./<br><br>RUN chmod +x ./npmrc.sh &amp;&amp; sh npmrc.sh <br><br>RUN npm install npm@latest<br><br>RUN npm ci<br><br>COPY . .<br><br>CMD [ &quot;npm&quot;, &quot;run&quot;, &quot;start&quot; ]<br><br>EXPOSE 3000</pre><pre>version: &#39;3&#39;<br><br>services:<br>  user-service:<br>    container_name: user-service<br>    image: ghcr.io/dineqr/user-service:main<br>    restart: always<br>    env_file: .env<br>    expose:<br>      - ${USER_SERVICE_PORT}<br>    ports:<br>      - ${USER_SERVICE_PORT}:${USER_SERVICE_PORT}<br>    environment:<br>      - USER_SERVICE_DATABASE=${USER_SERVICE_DATABASE}<br>      - NODE_ENV=${NODE_ENV}<br>      - USER_SERVICE_PORT=${USER_SERVICE_PORT}<br>    networks:<br>      - backend<br>    command: npm run start<br>    volumes:<br>      - .:/user-service<br>      - /user-service/node_modules<br>  notification-service:<br>    container_name: notification-service<br>    image: ghcr.io/dineqr/notification-service:main<br>    restart: always<br>    env_file: .env<br>    expose:<br>      - ${NOTIFICATION_SERVICE_PORT}<br>    ports:<br>      - ${NOTIFICATION_SERVICE_PORT}:${NOTIFICATION_SERVICE_PORT}<br>    environment:<br>      - MAIL_HOST=${MAIL_HOST}<br>      - SMTP_USERNAME=${SMTP_USERNAME}<br>      - SMTP_PASSWORD=${SMTP_PASSWORD}<br>      - API_GATEWAY_URL=${API_GATEWAY_URL}<br>      - NOTIFICATION_SERVICE_PORT=${NOTIFICATION_SERVICE_PORT}<br>      - RABBITMQ_URL=${RABBITMQ_URL}<br>    networks:<br>      - backend<br>    command: npm run start<br>    volumes:<br>      - .:/notification-service<br>      - /notification-service/node_modules<br>  app:<br>    container_name: app<br>    build: .<br>    depends_on:<br>      - user-service<br>    restart: always<br>    env_file: .env<br>    expose:<br>      - ${API_GATEWAY_PORT}<br>    ports:<br>      - ${API_GATEWAY_PORT}:${API_GATEWAY_PORT}<br>    environment:<br>      - API_GATEWAY_PORT=${API_GATEWAY_PORT}<br>    networks:<br>      - backend<br>    command: npm run start<br>    volumes:<br>      - .:/app<br>      - /app/node_modules<br><br>volumes:<br>  user-service:<br>  notification-service:<br>  app:<br>networks:<br>  backend:<br>    driver: bridge</pre><p>This is what we need to expose our dockerized gRPC microservice to our rest gateway.</p><p>Building a gRPC microservice exposed through a REST endpoint on an API gateway, coupled with event emission to RabbitMQ for consumption by a notification service, offers several advantages:</p><ul><li><strong>Efficient Communication</strong>: gRPC allows for high-performance, bidirectional communication between services, optimizing data transfer using Protocol Buffers. By exposing a REST endpoint on an API gateway, it accommodates clients still reliant on REST-based communication while leveraging gRPC’s efficiency internally.</li><li><strong>Flexibility and Compatibility</strong>: Integrating gRPC services with an API gateway as an image enables seamless compatibility between different communication protocols (gRPC and REST). It provides flexibility for clients utilizing either technology and allows for easy deployment and scaling using containerized images.</li><li><strong>Decoupled Microservices</strong>: By emitting events to RabbitMQ, the gRPC service becomes decoupled from the consumers (like the notification service). This decoupling fosters scalability, as services can independently evolve and scale based on their specific needs without tightly coupling to each other.</li><li><strong>Asynchronous Communication</strong>: Leveraging RabbitMQ for event-driven communication allows services to communicate asynchronously. This asynchronous nature enhances system resilience, enabling services to operate independently without waiting for immediate responses, thus improving overall system responsiveness.</li><li><strong>Scalability and Fault Isolation</strong>: With the decoupling of services and the asynchronous nature of communication, it becomes easier to scale different parts of the system independently. Fault isolation is improved as issues in one service are less likely to affect others, contributing to system stability.</li><li><strong>Technology Agnosticism and Interoperability</strong>: This setup allows for the utilization of different technologies and programming languages across services. gRPC, REST, RabbitMQ, and the notification service can be developed and maintained using different stacks or languages, providing interoperability across the system.</li><li><strong>Reliable Event Handling</strong>: Utilizing RabbitMQ for event distribution ensures reliable message delivery and event handling. This guarantees that events emitted by the gRPC service are received and processed by the notification service, promoting data consistency and reliability in the system.</li></ul><p>In essence, this architecture combines the benefits of efficient communication through gRPC, flexibility through REST, decoupled and scalable microservices, asynchronous event-driven communication, and reliable event handling, contributing to a more robust, scalable, and adaptable system architecture.</p><p>Moving forward, we could of course make our gateway an image and deploy that on AWS or alternately, each of the individual dockerized services we created, we could deploy them individually and use the server uri on our gateway. This is one of many ways to go about this</p><p>If you have any questions, you can reach out to me.</p><p>Github: <a href="https://github.com/ietienam/nestjs-gateway-with-grpc-microservice">https://github.com/ietienam/nestjs-gateway-with-grpc-microservice</a></p><p>LinkedIn: <a href="https://linkedin.com/in/ietienam">https://linkedin.com/in/ietienam</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35c900eba85e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>