<?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 Raheel Butt on Medium]]></title>
        <description><![CDATA[Stories by Raheel Butt on Medium]]></description>
        <link>https://medium.com/@buttraheel6?source=rss-316436f83399------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oYpWagIO_lpP2TV0E8gDUg.jpeg</url>
            <title>Stories by Raheel Butt on Medium</title>
            <link>https://medium.com/@buttraheel6?source=rss-316436f83399------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:15:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@buttraheel6/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[Syncing GitHub Repositories Across Accounts Automatically — The Right Way]]></title>
            <link>https://medium.com/@buttraheel6/syncing-github-repositories-across-accounts-automatically-the-right-way-c3c7ddba686b?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3c7ddba686b</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[relationships]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 08:23:03 GMT</pubDate>
            <atom:updated>2026-07-20T10:35:59.525Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem</h3><p>Cross-account repository sync comes up more often than you’d think:</p><ul><li>You maintain a <strong>private development repo</strong> and need to push polished releases into a <strong>separate public or client-facing repo</strong></li><li>You work across <strong>multiple GitHub accounts</strong> and want changes in one to flow into the other automatically</li><li>You deliver code into a <strong>repository you don’t own</strong>, and need the commits to appear under that account’s identity</li><li>You want to <strong>keep certain files private</strong> — internal configs, tooling, CI workflows — and sync only the deliverable code</li></ul><p>GitHub has mirroring, forks, and submodules — but none of them quite solve this. Mirrors copy everything including history and refs. Forks are tied to the same origin. Submodules add coupling. And none of them let you filter which files sync or control how commits appear on the receiving end.</p><p>So we built a GitHub Action that does exactly this.</p><h3>What the Automation Does</h3><p>A single workflow file in your <strong>source repo</strong> handles everything:</p><ul><li>On every push to main or dev, it detects which commits haven&#39;t been synced yet</li><li>It replays those commits — in order — into the <strong>target repo</strong>, applying only the files you want</li><li>Commits land in the target repo under a <strong>configurable author identity</strong>, with the original timestamps preserved</li><li>A lightweight <strong>tracking ref</strong> in the source repo remembers where the last sync ended, so only new commits are applied on each run</li></ul><p>No third-party services. No external state. Just git and a YAML file.</p><h3>The Tracking Ref: Stateless Incremental Sync</h3><p>The core challenge with incremental sync is knowing which commits have already been sent. We solve this with a <strong>tracking ref</strong> stored directly in the source repo:</p><pre>refs/sync-target/main   ← SHA of the last synced commit on main<br>refs/sync-target/dev    ← same, for dev</pre><p>On each run:</p><pre>LAST=$(git ls-remote origin &quot;refs/sync-target/$BRANCH&quot; | awk &#39;{print $1}&#39;)</pre><pre>if [[ -z &quot;$LAST&quot; ]]; then<br>  git log --reverse --format=&quot;%H&quot; HEAD &gt; /tmp/new_commits.txt      # first run: full history<br>else<br>  git log --reverse --format=&quot;%H&quot; &quot;$LAST..HEAD&quot; &gt; /tmp/new_commits.txt  # incremental<br>fi</pre><p>After a successful sync, the ref is advanced to the current HEAD:</p><pre>git push origin &quot;HEAD:refs/sync-target/$BRANCH&quot;</pre><p>This is self-contained — the source repo tracks its own sync state. No databases, no config files, no third-party services required.</p><h3>Filtering Files: Blacklist with .gitignore Syntax</h3><p>Rather than specifying which paths <em>to</em> sync (a whitelist that breaks every time you add a new folder), the workflow uses a <strong>blacklist</strong>: you define which paths to <em>exclude</em>, and everything else syncs automatically.</p><p>The exclusion patterns are stored as a repository variable (CLIENT_NOT_SYNC_PATHS) and follow standard .gitignore syntax — globs, **, trailing slashes, !negation — so there&#39;s nothing new to learn.</p><p>Example:</p><pre>.github/        ← don&#39;t expose your CI workflows in the target repo<br>internal/       ← private configs, tooling, notes<br>*.local         ← any environment-specific files</pre><p>We implement this using git check-ignore against a temporary git repo seeded with these patterns. This gives us the full gitignore engine with no custom parsing:</p><pre>mkdir -p /tmp/gitignore-matcher<br>git -C /tmp/gitignore-matcher init -q<br>printf &#39;%s\n&#39; &quot;$CLIENT_NOT_SYNC_PATHS&quot; &gt; /tmp/gitignore-matcher/.gitignore</pre><pre>is_excluded() {<br>  git -C /tmp/gitignore-matcher check-ignore -q &quot;$1&quot; 2&gt;/dev/null<br>}</pre><p>For each commit, every changed file is run through is_excluded(). Files that pass are copied into the target repo; files that don&#39;t are ignored. If a commit only touches excluded files, it&#39;s skipped entirely — no empty commits land in the target.</p><h3>Replaying Commits With Controlled Identity and Timestamps</h3><p>For each commit that passes the filter, the workflow copies the changed files into a clone of the target repo, then commits them with a configurable identity while preserving the original timestamps:</p><pre># Capture metadata from the source commit<br>git log -1 --format=&quot;%B&quot; &quot;$COMMIT&quot; &gt; /tmp/commit_msg.txt<br>AUTHOR_DATE=$(git log -1 --format=&quot;%aI&quot; &quot;$COMMIT&quot;)<br>COMMITTER_DATE=$(git log -1 --format=&quot;%cI&quot; &quot;$COMMIT&quot;)</pre><pre># Commit into the target repo with the desired identity<br>cd /tmp/target-repo<br>git add -A<br>GIT_AUTHOR_NAME=&quot;$TARGET_AUTHOR_NAME&quot;       \<br>GIT_AUTHOR_EMAIL=&quot;$TARGET_AUTHOR_EMAIL&quot;     \<br>GIT_AUTHOR_DATE=&quot;$AUTHOR_DATE&quot;              \<br>GIT_COMMITTER_NAME=&quot;$TARGET_AUTHOR_NAME&quot;    \<br>GIT_COMMITTER_EMAIL=&quot;$TARGET_AUTHOR_EMAIL&quot;  \<br>GIT_COMMITTER_DATE=&quot;$COMMITTER_DATE&quot;        \<br>git commit -F /tmp/commit_msg.txt</pre><p>The commit message is preserved exactly. Timestamps match the originals. The target repo builds a coherent, readable history that reflects when the work was actually done.</p><h3>Authentication: No Footprint on the Target Repo</h3><p>The most common approach for pushing to another repo — adding a <strong>deploy key</strong> — works, but deploy keys are visible in the target repo’s Settings → Deploy keys. Anyone with admin access to that repo can see them.</p><p>A cleaner approach: register the SSH key at the <strong>GitHub account level</strong> instead.</p><pre>ssh-keygen -t ed25519 -C &quot;repo-sync&quot; -f ./sync_key -N &quot;&quot;<br># sync_key     → store as a secret in the source repo<br># sync_key.pub → add to the target GitHub account at github.com/settings/keys</pre><p>Account-level SSH keys live under the user’s personal settings, not under any repository. They grant push access to repos the account owns, but they are invisible from any repo’s Settings page.</p><p>In the workflow, a dedicated SSH Host alias ensures the right key is always selected:</p><pre>- name: Setup SSH<br>  env:<br>    DEPLOY_KEY: ${{ secrets.TARGET_SSH_KEY }}<br>  run: |<br>    mkdir -p ~/.ssh<br>    printf &#39;%s\n&#39; &quot;$DEPLOY_KEY&quot; &gt; ~/.ssh/sync_key<br>    chmod 600 ~/.ssh/sync_key<br>    ssh-keyscan github.com &gt;&gt; ~/.ssh/known_hosts<br>    cat &gt;&gt; ~/.ssh/config &lt;&lt;&#39;EOF&#39;<br>    Host github-target<br>      HostName github.com<br>      User git<br>      IdentityFile ~/.ssh/sync_key<br>      IdentitiesOnly yes<br>    EOF</pre><p>Then clone using the alias:</p><pre>CLONE_URL=&quot;${TARGET_REPO_SSH_URL/github.com/github-target}&quot;<br>git clone &quot;$CLONE_URL&quot; /tmp/target-repo</pre><h3>Edge Cases Worth Knowing About</h3><h3>First sync on a repo that already has commits</h3><p>The first-sync path uses git checkout --orphan to start the target branch from a clean slate. But git clone automatically checks out the default branch, so attempting git checkout --orphan main immediately after cloning fails:</p><pre>fatal: a branch named &#39;main&#39; already exists</pre><p>Fix: detach HEAD first so git lets you delete and recreate the branch.</p><pre>git checkout --detach HEAD 2&gt;/dev/null || true<br>git branch -D &quot;$BRANCH&quot; 2&gt;/dev/null || true<br>git checkout --orphan &quot;$BRANCH&quot;<br>git rm -rf . 2&gt;/dev/null || true</pre><p>The || true handles the edge case of a completely empty target repo where there&#39;s no HEAD to detach to.</p><h3>Commit content already present in the target repo</h3><p>If a commit was manually applied to the target repo before the sync caught up — a hotfix pushed directly, for example — the action will try to apply the same changes, find nothing to stage, and git commit will exit with code 1, failing the run.</p><p>Fix: check for staged changes before committing.</p><pre>git add -A<br>if git diff --cached --quiet; then<br>  echo &quot;Skipped $COMMIT (content already present in target repo)&quot;<br>  continue<br>fi<br># proceed with commit...</pre><p>Any subsequent commits in the same push still apply normally.</p><h3>How the Full Flow Looks</h3><pre>Push to source repo (main or dev)<br>        │<br>        ▼<br>Read tracking ref<br>  ├── ref exists  → collect commits since last sync<br>  └── no ref      → collect full commit history (first run)<br>        │<br>        ▼<br>For each commit:<br>  ├── Get all changed files<br>  ├── Filter out excluded paths (gitignore patterns)<br>  ├── Skip commit if nothing remains after filtering<br>  ├── Copy/delete files in target repo clone<br>  ├── Check if anything actually changed (git diff --cached)<br>  ├── Skip if content already present<br>  └── Commit with target identity + original timestamps<br>        │<br>        ▼<br>Push target repo clone → target repo<br>        │<br>        ▼<br>Advance tracking ref in source repo</pre><h3>Configuration</h3><h3>Secrets (source repo)</h3><p>Secret Value TARGET_SSH_KEY Private SSH key TARGET_REPO_SSH_URL git@github.com:target-account/repo.git TARGET_AUTHOR_NAME Name to use on target repo commits TARGET_AUTHOR_EMAIL Email to use on target repo commits</p><h3>Variable (source repo)</h3><p>Variable Value CLIENT_NOT_SYNC_PATHS Newline-separated exclusion patterns (.gitignore syntax)</p><h3>Verifying the Sync</h3><pre>git clone git@github.com:target-account/repo.git<br>cd repo<br>git log --oneline       # commits should reflect your source repo history<br>git log --format=&quot;%an &lt;%ae&gt;&quot; | sort -u  # only the target identity should appear</pre><h3>When to Use This</h3><p>This pattern works well when you need:</p><ul><li><strong>Filtered delivery</strong> — sync only specific directories or file types to the target</li><li><strong>Identity normalisation</strong> — commits in the target repo should appear under a specific account</li><li><strong>Incremental, non-destructive sync</strong> — only new commits are applied, existing target history is preserved</li><li><strong>Zero configuration on the target repo</strong> — no deploy keys, no webhooks, nothing added to the target repo’s settings</li></ul><p>It’s a single YAML file, uses only built-in git commands and actions/checkout, and adds no runtime dependencies.</p><p>The full workflow, sample project structure, and test scenarios covering all the edge cases above are available <a href="https://github.com/raheelsoft/git-bridge">on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3c7ddba686b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Polling Your APIs: Use Server-Sent Events (SSE) Instead]]></title>
            <link>https://medium.com/@buttraheel6/stop-polling-your-apis-use-server-sent-events-sse-instead-91d9d3a0bdab?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/91d9d3a0bdab</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 14:47:30 GMT</pubDate>
            <atom:updated>2026-03-09T14:47:30.045Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications often need <strong>real-time updates</strong> — payment status, order tracking, notifications, live dashboards, etc.</p><p>The most common approach developers use is <strong>API polling</strong>.</p><p>But polling is inefficient, expensive, and unnecessary in many cases.</p><p>A better solution in many scenarios is <strong>Server-Sent Events (SSE)</strong>.</p><p>Let’s explore what SSE is, how it works, and when you should use it.</p><h3>The Problem With Polling</h3><p>A typical polling flow looks like this:</p><ol><li>User performs an action (e.g., payment).</li><li>Frontend repeatedly calls an API every few seconds.</li><li>Backend checks status.</li><li>If status changes, response is updated.</li></ol><p>Example polling code (Client):</p><pre>setInterval(async () =&gt; {<br>  const res = await fetch(&quot;/api/status&quot;);<br>  const data = await res.json();<br>  if (data.status === &quot;completed&quot;) {<br>    console.log(&quot;Payment completed&quot;);<br>  }<br>}, 3000);</pre><h3>Problems with polling</h3><p>• Unnecessary API requests<br>• Increased server load<br>• Higher infrastructure cost<br>• Delayed updates<br>• Poor scalability</p><p>If you have <strong>10 APIs polling every 5 seconds</strong>, your system quickly becomes overloaded.</p><h3>What is Server-Sent Events (SSE)?</h3><p><strong>Server-Sent Events</strong> allow the <strong>server to push updates to the client over a single persistent HTTP connection</strong>.</p><p>Instead of the client repeatedly asking:</p><blockquote><em>“Has anything changed?”</em></blockquote><p>The server simply <strong>notifies the client when something changes</strong>.</p><p>SSE works using the <strong>EventSource API in browsers</strong>.</p><h3>How SSE Works</h3><p>The connection flow is simple:</p><ol><li>Client opens a persistent connection.</li><li>Server keeps the connection open.</li><li>When new data is available, the server pushes the event.</li></ol><pre>Client  ────────connect───────▶ Server<br>Client  ◀──────event update──── Server<br>Client  ◀──────event update──── Server<br>Client  ◀──────event update──── Server<br>Client  ◀─────────close──────── Server</pre><p>The connection remains open until closed.</p><h3>Simple SSE Example</h3><h4>Server (Node.js / Express)</h4><pre>app.get(&quot;/events&quot;, (req, res) =&gt; {<br>  res.setHeader(&quot;Content-Type&quot;, &quot;text/event-stream&quot;);<br>  res.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;);<br>  res.setHeader(&quot;Connection&quot;, &quot;keep-alive&quot;);<br>  setInterval(() =&gt; {<br>    res.write(`data: ${JSON.stringify({ time: new Date() })}\n\n`);<br>  }, 2000);<br>});</pre><h3>Client (Browser)</h3><pre>const eventSource = new EventSource(&quot;/events&quot;);<br>eventSource.onmessage = (event) =&gt; {<br>  const data = JSON.parse(event.data);<br>  console.log(&quot;New update:&quot;, data);<br>};</pre><p>Now the <strong>server pushes updates automatically</strong>.</p><p>No polling needed.</p><h3>Real-World Use Cases</h3><blockquote>SSE is perfect for:</blockquote><h4>Payment status updates</h4><p>Stripe / PayPal confirmation pages.</p><h4>Order tracking</h4><p>Live delivery updates.</p><h4>Notifications</h4><p>Activity alerts in web apps.</p><h4>Live dashboards</h4><p>Monitoring tools or analytics.</p><h4>Logs streaming</h4><p>DevOps dashboards.</p><h3>SSE vs WebSockets</h3><p>Developers often compare SSE with <strong>WebSockets</strong>.</p><pre><strong>Feature</strong>           <strong>SSE</strong>                       <strong>WebSockets</strong><br><strong>Direction </strong>        Server → Client           Bidirectional<br><strong>Protocol  </strong>        HTTP                      WS<br><strong>Complexity </strong>       Simple                    Complex<br><strong>Auto reconnect</strong>    Yes                       Manual<br><strong>Best for </strong>         Updates/notifications     Chat, multiplayer</pre><p>Use <strong>SSE when you only need server updates</strong>.</p><p>Use <strong>WebSockets when both sides need to communicate continuously</strong>.</p><h3>SSE vs Polling</h3><pre><strong>Feature        Polling        SSE</strong><br><strong>Requests</strong>       Many           One<br><strong>Latency</strong>        High           Low<br><strong>Server Load</strong>    High           Low<br><strong>Real-time</strong>      No             Yes</pre><p>SSE is <strong>far more efficient</strong>.</p><h3>Example Architecture</h3><p>Consider a payment system:</p><pre>User pays → Stripe<br>            ↓<br>Webhook received<br>            ↓<br>Event sent to queue<br>            ↓<br>Worker processes payment<br>            ↓<br>SSE pushes update to client</pre><p>Instead of polling <strong>10 APIs</strong>, the frontend simply listens for events.</p><h3>When NOT to Use SSE</h3><p>SSE is not ideal when:</p><p>• You need <strong>client → server real-time communication</strong><br>• You are building <strong>chat applications</strong><br>• You need <strong>binary data streaming</strong></p><p>In those cases, <strong>WebSockets</strong> are better.</p><h3>Important Limitations</h3><p>1️⃣ Browser connection limits<br>2️⃣ Works only over HTTP/HTTPS<br>3️⃣ Some load balancers close idle connections</p><p>These issues can usually be solved with <strong>heartbeat messages</strong>.</p><h3>Final Thoughts</h3><p>Polling is often the <strong>default solution</strong>, but not always the best one.</p><p>If your application only needs <strong>server-to-client updates</strong>, <strong>Server-Sent Events provide a lightweight and scalable alternative</strong>.</p><p>With <strong>fewer requests, lower latency, and simpler architecture</strong>, SSE can dramatically improve real-time features in modern applications.</p><p>If you’re building <strong>real-time dashboards, notifications, or payment status pages</strong>, consider replacing polling with SSE.</p><p>Your servers — and your users — will thank you.</p><p><strong>Quick fact:</strong> the animated responses you see in ChatGPT and many other AI tools aren’t actually animations. They’re powered by Server-Sent Events (SSE), a protocol that streams data from the server to the client in real time. As the server sends chunks of the response, the UI renders them progressively, creating that “typing” effect.</p><p>I’ve put together a small demo to show how it works. Repo link below :point_down:</p><p><strong>Repo Link:</strong> <a href="https://github.com/buttraheel6pro/server-sent-event-demo">https://github.com/buttraheel6pro/server-sent-event-demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91d9d3a0bdab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[As Developers, We Build APIs Every Day — But Do We Know What an API Is?]]></title>
            <link>https://medium.com/@buttraheel6/as-developers-we-build-apis-every-day-but-do-we-know-what-an-api-is-d34f455c72c8?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/d34f455c72c8</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 07:21:37 GMT</pubDate>
            <atom:updated>2024-10-08T07:21:37.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>As Developers, We Build APIs Every Day — But Do We Know What an API Is?</h3><p>As developers, we often throw around terms like API (Application Programming Interface) in our day-to-day conversations. We use them all the time to connect systems, build integrations, and design features. But let’s take a step back for a second — <strong>do we know what an API is and how it works</strong>? Sure, we’ve built hundreds of them, but understanding the power behind an API can help us write better, more efficient, and scalable code.</p><h3>What Exactly Is an API?</h3><p>In the simplest terms, an <strong>API</strong> is like a bridge — a powerful tool that lets different systems communicate and share data or functionality. It enables applications to work together without needing to know how the other one works internally. APIs are the reason your mobile apps talk to the cloud, your browser pulls data from web services, and why systems can be modular and scalable.</p><p>Think of APIs as the engine under the hood, quietly and efficiently driving the interactions behind modern software. They’re what makes today’s interconnected digital world possible.</p><h3>How Do APIs Work?</h3><p><strong>Client-Server Communication:</strong></p><ul><li>In an API-driven system, the <strong>client</strong> (often a mobile app, web app, or another service) sends a request to the <strong>server</strong>, asking it to perform some action (e.g., fetch data, create a record, delete a file).</li><li>The server processes this request and responds with the requested data or a status message indicating whether the operation succeeded or failed.</li></ul><p><strong>Components of an API Request:</strong></p><ul><li><strong>Endpoint</strong>: The specific URL or URI where the client sends its request (e.g., <a href="https://api.example.com/users).">https://api.example.com/users).</a></li><li><strong>HTTP Method</strong>: Defines the type of operation the client wants to perform:</li><li><strong><em>GET</em></strong><em>: Fetch data (e.g., retrieve user details).</em></li><li><strong><em>POST</em></strong><em>: Send new data (e.g., create a new user).</em></li><li><strong><em>PUT/PATCH</em></strong><em>: Update existing data.</em></li><li><strong><em>DELETE</em></strong><em>: Remove data.</em></li><li><strong>Headers</strong>: Metadata passed with the request (e.g., authorization tokens, content type).</li><li><strong>Body</strong>: Optional data sent with some requests (e.g., sending user information for a new user creation).</li><li><strong>Response</strong>: After processing the request, the server sends back a response, usually in JSON or XML format, containing the requested data or status information.</li></ul><h3>Types of APIs:</h3><p><strong>REST (Representational State Transfer) APIs</strong>:</p><ul><li><strong>REST</strong> is the most common architectural style for APIs, using standard HTTP methods (GET, POST, PUT, DELETE).</li><li>It is designed around resources (like users, and products) and uses URLs to interact with those resources.</li><li><strong>Stateless</strong>: Each request from a client to the server must contain all the information the server needs to fulfill that request (no session/state on the server).</li></ul><p><strong>Example:</strong></p><ul><li><strong>GET </strong><strong>/users/123</strong>: Fetch the user with ID 123.</li><li><strong>POST </strong><strong>/users</strong>: Create a new user.</li></ul><p><strong>SOAP (Simple Object Access Protocol) APIs</strong>:</p><ul><li><strong>SOAP</strong> is a protocol for exchanging structured information in web services using XML.</li><li>It is more rigid and formal than REST, providing built-in error handling and security features.</li><li>It is often used in enterprise environments where transactional reliability is important (e.g., financial systems).</li></ul><p><strong>GraphQL</strong>:</p><ul><li>Unlike REST, which exposes multiple endpoints, <strong>GraphQL</strong> provides a single endpoint, and clients can specify exactly the data they need in a query-like format.</li><li>It reduces over-fetching or under-fetching of data and gives clients greater control over the shape of the response.</li></ul><p><strong>Example:</strong></p><ul><li>Query: { user(id: &quot;123&quot;) { name, email } }</li><li>Response: { &quot;user&quot;: { &quot;name&quot;: &quot;John&quot;, &quot;email&quot;: &quot;john@example.com&quot; } }</li></ul><ol><li><strong>gRPC (Google Remote Procedure Call)</strong>:</li></ol><ul><li><strong>gRPC</strong> is a high-performance framework that uses <strong>Protocol Buffers</strong> (a binary serialization format) and is ideal for inter-service communication in microservices.</li><li>It supports streaming and is highly efficient for real-time systems.</li></ul><p><strong>Operating System APIs</strong>:</p><ul><li>These APIs allow applications to interact with the underlying operating system’s functions, such as file management, memory handling, or networking.</li></ul><p><strong>Library APIs</strong>:</p><ul><li>These are APIs provided by software libraries or frameworks to enable developers to reuse specific functionality, like a machine learning library (e.g., TensorFlow API).</li></ul><h3>Key API Concepts:</h3><p><strong>Endpoints and Routes</strong>:</p><ul><li>An endpoint refers to a specific route in an API where the client sends a request to interact with a resource.</li><li>Example: https://api.example.com/products is an endpoint for interacting with a product resource in an e-commerce system.</li></ul><p><strong>API Authentication</strong>:</p><ul><li>APIs often require clients to authenticate before accessing the data or performing actions. Common authentication methods include:</li><li><strong>API Keys</strong>: A simple key is provided in the request header.</li><li><strong>OAuth</strong>: A more secure method that uses access tokens to grant permission.</li><li><strong>JWT (JSON Web Token)</strong>: Encoded tokens used for stateless authentication.</li><li><strong>Basic Authentication</strong>: Simple username and password base64-encoded in the request header.</li></ul><p><strong>Versioning</strong>:</p><ul><li>Developers often release new versions as APIs evolve to introduce new features or fix bugs while ensuring backward compatibility.</li><li>Example: https://api.example.com/v1/products and https://api.example.com/v2/products represent different versions of the same API.</li></ul><p><strong>Rate Limiting</strong>:</p><ul><li>APIs usually implement rate limiting to prevent overuse or abuse, limiting the number of requests a client can make within a specified timeframe (e.g., 100 requests per minute).</li><li>This helps maintain performance and fairness across users.</li></ul><p><strong>Status Codes</strong>:</p><ul><li>HTTP status codes indicate the result of an API request:</li><li><strong>200 OK</strong>: Successful request.</li><li><strong>201 Created</strong>: Resource successfully created.</li><li><strong>400 Bad Request</strong>: The request is invalid or malformed.</li><li><strong>401 Unauthorized</strong>: Authentication is required or failed.</li><li><strong>404 Not Found</strong>: The requested resource does not exist.</li><li><strong>500 Internal Server Error</strong>: The server encountered an issue.</li></ul><h3>API Use Cases:</h3><p><strong>Social Media Integration</strong>:</p><ul><li>Apps like Twitter and Facebook expose APIs to allow third-party applications to interact with their platforms, such as posting status updates or retrieving user data.</li></ul><p><strong>Payment Gateways</strong>:</p><ul><li>APIs from payment processors like Stripe or PayPal allow businesses to integrate online payment capabilities into their applications.</li></ul><p><strong>Cloud Services</strong>:</p><ul><li>Cloud platforms like AWS, Google Cloud, and Azure provide APIs to allow developers to manage their cloud infrastructure programmatically, such as launching new servers or scaling resources.</li></ul><p><strong>IoT (Internet of Things)</strong>:</p><ul><li>APIs connect IoT devices with applications. For example, a smart thermostat might use an API to send temperature data to a cloud service.</li></ul><p><strong>AI and Machine Learning</strong>:</p><ul><li>APIs enable developers to integrate AI models into their applications, such as using OpenAI’s GPT-3 API to add natural language processing capabilities.</li></ul><h3>Advantages of APIs:</h3><ol><li><strong>Interoperability</strong>: APIs allow different systems to communicate, making it possible to connect services, apps, and platforms across different ecosystems.</li><li><strong>Automation</strong>: Tasks that traditionally require manual input can be automated via APIs, such as syncing data between systems or updating records automatically.</li><li><strong>Reusability</strong>: Developers can leverage APIs to reuse functionality across multiple applications, saving time and effort in development.</li><li><strong>Modularity and Scalability</strong>: APIs promote modularity in software design, allowing individual services to evolve independently, which is essential for microservices and cloud architectures.</li></ol><h3>Challenges and Cons of APIs:</h3><ol><li><strong>Security</strong>: APIs, if not properly secured, can be vulnerable to attacks like data breaches, unauthorized access, or injection attacks. This requires strong encryption, validation, and authentication mechanisms.</li><li><strong>Versioning Complexity</strong>: As APIs evolve, managing multiple versions can be difficult, especially when maintaining backward compatibility for older clients.</li><li><strong>Latency</strong>: API calls introduce network latency, especially when interacting with external services. Slow APIs can lead to a poor user experience.</li><li><strong>Dependency on External Services</strong>: When an API depends on an external service (like a third-party API), outages or changes in that service can disrupt your application.</li></ol><h3>Conclusion:</h3><p>APIs are essential for enabling communication between systems, facilitating everything from integrating social media platforms to automating cloud infrastructure. They enable modularity, automation, and interoperability, helping developers build more scalable, flexible, and maintainable applications. However, they also introduce complexities around security, performance, and version management that need to be carefully managed to ensure efficient and secure communication between systems.</p><p>That is all for this post. I’m excited to see you in the other posts soon.</p><p>If you found this blog post useful then <strong>clap</strong>, <strong>comment</strong>, and <strong>follow.</strong></p><p>🤝 <strong>Let’s</strong> c<strong><em>onnect on LinkedIn: </em></strong><a href="https://www.linkedin.com/in/raheel-butt-82142a143/"><strong><em>Raheel Butt</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d34f455c72c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Strengthen Your API Security with HMAC Signatures in NestJs]]></title>
            <link>https://medium.com/@buttraheel6/strengthen-your-api-security-with-hmac-signatures-in-nestjs-52217ef9368c?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/52217ef9368c</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 08:41:02 GMT</pubDate>
            <atom:updated>2024-09-01T13:31:19.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*EhDz79ebKQEjepmxKKZ37A.png" /><figcaption>nest-security</figcaption></figure><p><em>API security is crucial because it protects our data and systems from unauthorized access and attacks. It ensures that our services are reliable and trustworthy for our users.</em></p><p><em>🔍 Curious about strengthening our API’s defenses? Let’s explore effective strategies together to safeguard our API endpoints and ensure they remain resilient against potential threats.</em></p><p><strong>Note:</strong> Numerous methods exist, let’s explore one.</p><p>🔐 Introducing HMAC Signatures for Robust API Security!<br>Harness the power of HMAC (Hash-based Message Authentication Code) signatures to shield your endpoints from unauthorized access and tampering. This approach guarantees the integrity and authenticity of incoming requests, bolstering your API’s overall security posture.</p><blockquote><strong>Key Concept</strong></blockquote><ol><li><strong>Generate a shared secret key</strong>: The server stores and manages client keys (encrypted) in the database. The client uses a decrypted key for generating signatures.</li><li><strong>Generate a signature at the client side</strong>: The client generates a signature using a cryptographic hash (e.g., HMAC) of a message, which includes the URL, request body, nonce, and timestamp, with a shared secret key.</li><li><strong>Include signature in client request headers</strong>: The client sends the signature in the x-signature header, along with a timestamp (x-timestamp), nonce (x-request-nonce), and client ID (x-client-id).</li><li><strong>Retrieve signature at the server</strong>: The server extracts the signature and related headers (timestamp, nonce, client ID) from the incoming request.</li><li><strong>Generate server-side signature</strong>: The server recreates the message and generates a signature using the same algorithm and the shared secret key (retrieved from its config service).</li><li><strong>Validate request</strong>:</li></ol><ul><li>Verify timestamp is within a valid time window.</li><li>Check nonce uniqueness to prevent replay attacks.</li><li>Compare the signatures generated by the client and server. If they match, the client is authorized; otherwise, it is not.</li><li>If the signature is missing or invalid, the server rejects the request.</li></ul><p>Here’s a step-by-step guide to implementing HMAC signatures to secure your APIs.</p><h4>First, we need a secret</h4><blockquote><strong>Using OpenSSL (Linux/macOS/Windows with Git Bash)</strong><br>You can use OpenSSL to generate a random hexadecimal string</blockquote><blockquote>SHARED_SECRET_KEY in .env file</blockquote><pre>openssl rand -hex 32</pre><p>This command will output a 64-character (32 bytes random hexadecimal string.</p><h4><strong><em>Front-end Code</em></strong></h4><blockquote>utils/axios-middleware.js</blockquote><pre>import axios from &quot;axios&quot;;<br>import { generateHmac } from &quot;@/utils/request-signature&quot;;<br><br>const instance = axios.create({<br>  baseURL: process.env.NEXT_PUBLIC_APP_URL,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>  },<br>});<br><br>instance.interceptors.request.use(config =&gt; {<br>  const body = config.data || {};<br>  const url = config?.url;<br>  const nonce = uuid.v4();<br>  const timestamp = new Date()?.getTime();<br><br>  const messageParams = {url, body, nonce, timestamp};<br>  const message = JSON.stringify(messageParams);<br><br>  config.headers[&#39;x-signature&#39;] = generateHmac(message);<br>  config.headers[&#39;x-request-nonce&#39;] = nonce;<br>  config.headers[&#39;x-timestamp&#39;] = timestamp;<br>  config.headers[&#39;x-client-id&#39;] = process.env.SIGNATURE_CLIENT_ID;  <br><br>  return config;<br>});<br><br>// rest of interceptors</pre><blockquote>utils/request-signature.js</blockquote><pre>import CryptoJS from &#39;crypto-js&#39;;<br><br>export const generateHmac = message =&gt; {<br>  let hash_generated;<br><br>  if (process.env.ENCRYPTION_ALGORITHM === &#39;sha256&#39;) {<br>    hash_generated = CryptoJS.HmacSHA256(message, process.env.SHARED_SECRET_KEY).toString(<br>      CryptoJS.enc.Hex,<br>    );<br>  } else if (process.env.ENCRYPTION_ALGORITHM === &#39;sha512&#39;) {<br>    hash_generated = CryptoJS.HmacSHA512(message, process.env.SHARED_SECRET_KEY).toString(<br>      CryptoJS.enc.Hex,<br>    );<br>  } else {<br>    throw new Error(&#39;Unsupported encryption algorithm&#39;);<br>  }<br><br>  return hash_generated;<br>};</pre><h4><strong><em>Back-end Code</em></strong></h4><blockquote>RequestSignatureGuard.guard.ts</blockquote><pre>import { CanActivate, ExecutionContext, Injectable } from &#39;@nestjs/common&#39;;<br>import * as crypto from &#39;crypto&#39;;<br>import { Request } from &#39;express&#39;;<br>import { MessageParams } from &#39;../types/global.types&#39;;<br>import { AppHelperService } from &#39;../helpers/app.helper&#39;;<br>import { Config } from &#39;../routes/v1/config/entities/config.entity&#39;;<br>import { ConfigService } from &#39;../routes/v1/config/config.service&#39;;<br>import { ConfigEnum } from &#39;../enums/config.enum&#39;;<br>import { RequestNonceService } from &#39;../routes/v1/request-nonce/request-nonce.service&#39;;<br>import { RequestNonce } from &#39;../routes/v1/request-nonce/entities/request-nonce.entity&#39;;<br>import { CreateRequestNonceDto } from &#39;../routes/v1/request-nonce/dto/create-request-nonce.dto&#39;;<br><br>@Injectable()<br>export class RequestSignatureGuard implements CanActivate {<br>  constructor(<br>    private readonly configService: ConfigService,<br>    private readonly requestNonceService: RequestNonceService,<br>  ) {}<br>  private readonly encryptionAlgorithm: string = process.env.ENCRYPTION_ALGORITHM;<br><br>  async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {<br>    const request: Request = context.switchToHttp().getRequest();<br><br>    const signatureBasedAuth: boolean = await this.configService.validateConfigValue({<br>      key: ConfigEnum.SIGNATURE_BASED_AUTH,<br>    } as Partial&lt;Config&gt;);<br><br>    if (!signatureBasedAuth) {<br>      return true;<br>    }<br><br>    const timestamp: number = +request?.headers?.[&#39;x-timestamp&#39;];<br>    const signature: string | undefined = request?.headers?.[&#39;x-signature&#39;] as string;<br>    const nonce: string = request?.headers?.[&#39;x-request-nonce&#39;] as string;<br>    const clientId: string = request?.headers?.[&#39;x-client-id&#39;] as string;<br><br>    if (!signature || !clientId || !nonce || !timestamp) {<br>      return false;<br>    }<br><br>    const isValidTimestamp: boolean = await this.validateTimestamp(timestamp);<br><br>    if (!isValidTimestamp) {<br>      return false;<br>    }<br><br>    const validNonce: boolean = await this.verifyNonce(nonce, request);<br><br>    if (!validNonce) {<br>      return false;<br>    }<br><br>    const messageParams: MessageParams = {<br>      url: request?.originalUrl,<br>      body: request?.body,<br>      nonce,<br>      timestamp,<br>    } as MessageParams;<br><br>    const message: string = JSON.stringify(messageParams);<br><br>    const clientKey: string = await this.getClientKey(clientId);<br><br>    return this.validateSignature(message, signature, clientKey);<br>  }<br><br>  private async getClientKey(clientId: string): Promise&lt;string&gt; {<br>    const clientInfo: Config = await this.configService.findOneByProp({ key: clientId } as Partial&lt;Config&gt;);<br><br>    if (!clientInfo) return &#39;&#39;;<br><br>    const keyInformation = JSON.parse(clientInfo?.value);<br><br>    return AppHelperService.decrypt(keyInformation?.clientKey);<br>  }<br><br>  private async validateTimestamp(timestamp: number): Promise&lt;boolean&gt; {<br>    if (!timestamp) {<br>      return false;<br>    }<br><br>    const config: Config = await this.configService.findOneByProp({ key: ConfigEnum.REQUEST_SIGNATURE_EXPIRY } as Partial&lt;Config&gt;);<br><br>    return AppHelperService.isWithinMinutesAfter(timestamp, parseInt(config.value, 10));<br>  }<br><br>  private async verifyNonce(nonce: string, req: Request): Promise&lt;boolean&gt; {<br>    const prevReqWithSameNonce: RequestNonce = await this.requestNonceService.findOneByProp({<br>      nonce,<br>      requestMethod: req?.method,<br>      requestUrl: req?.originalUrl,<br>    } as Partial&lt;RequestNonce&gt;);<br><br>    if (!prevReqWithSameNonce) {<br>      await this.requestNonceService.create({<br>        nonce,<br>        requestMethod: req?.method,<br>        requestUrl: req?.originalUrl,<br>      } as CreateRequestNonceDto);<br>    }<br><br>    return !prevReqWithSameNonce;<br>  }<br><br>  private validateSignature(message: string, clientSignature: string, secret: string): boolean {<br>    const signature: string = crypto.createHmac(this.encryptionAlgorithm, secret).update(message).digest(&#39;hex&#39;);<br><br>    return signature === clientSignature;<br>  }<br>}</pre><blockquote><em>config.service.ts</em></blockquote><pre>  async validateConfigValue(props: Partial&lt;Config&gt;): Promise&lt;boolean&gt; {<br>    try {<br>      const config: Config = await this.findOneByProp(props);<br><br>      return config.value === &#39;true&#39;;<br>    } catch (error) {<br>      if (error instanceof Exception) {<br>        throw error;<br>      }<br><br>      throw new UnhandledException(error?.message);<br>    }<br>  }<br><br>  async findOneByProp(props: Partial&lt;Config&gt;): Promise&lt;Config&gt; {<br>    try {<br>      const config: Config = await this.configRepository.findOneByProp(props);<br><br>      if (config) {<br>        return config;<br>      }<br><br>      throw new NotFoundException(ExceptionMessageConstant.CONFIG_NOT_FOUND);<br>    } catch (error) {<br>      if (error instanceof Exception) {<br>        throw error;<br>      }<br><br>      throw new UnhandledException(error?.message);<br>    }<br>  }</pre><blockquote><em>config.enum.ts</em></blockquote><pre>export enum ConfigEnum {<br>  SIGNATURE_BASED_AUTH = &#39;signature_based_auth&#39;,<br>  REQUEST_SIGNATURE_EXPIRY = &#39;request_signature_expiry&#39;,<br>}</pre><blockquote><em>request-nonce.service.ts</em></blockquote><pre>  async findOneByProp(props: Partial&lt;RequestNonce&gt;, options?: FindOneOptions&lt;RequestNonce&gt;): Promise&lt;RequestNonce&gt; {<br>    try {<br>      return await this.requestNonceRepository.findOneByProp(props, options);<br>    } catch (error) {<br>      throw new UnhandledException(error?.message);<br>    }<br>  }<br><br> async create(body: CreateRequestNonceDto): Promise&lt;void&gt; {<br>    try {<br>      const requestNonce: RequestNonce = this.requestNonceRepository.create(body);<br><br>      await this.entityManager.transaction(async (transactionManager: EntityManager): Promise&lt;void&gt; =&gt; {<br>        await this.requestNonceRepository.save(requestNonce, transactionManager);<br>      });<br>    } catch (error) {<br>      throw new UnhandledException(error?.message);<br>    }<br>  }</pre><blockquote><em>app.helper.ts</em></blockquote><pre>import { v4 as uuidv4 } from &#39;uuid&#39;;<br>import crypto, { randomBytes } from &#39;crypto&#39;;<br><br>export class AppHelperService {<br><br>   static generateUUID(): string {<br>      return uuidv4();<br>    }<br><br>  static encrypt(text: string): string {<br>    const iv: string = crypto.randomBytes(8).toString(&#39;hex&#39;);<br>    const cipher: crypto.Cipher = crypto.createCipheriv(algorithm, key, iv);<br>    let encrypted: string = cipher.update(text, &#39;utf8&#39;, &#39;hex&#39;);<br>    encrypted += cipher.final(&#39;hex&#39;);<br><br>    return `${iv}:${encrypted}`;<br>  }<br><br>  static decrypt(text: string): string {<br>    const textParts: string[] = text.split(&#39;:&#39;);<br>    const iv: string = textParts?.[0];<br>    const encryptedText: string = textParts?.[1];<br><br>    const decipher: crypto.Decipher = crypto.createDecipheriv(algorithm, key, iv);<br>    let decrypted: string = decipher.update(encryptedText, &#39;hex&#39;, &#39;utf8&#39;);<br><br>    decrypted += decipher.final(&#39;utf8&#39;);<br><br>    return decrypted;<br>  }<br><br>  private static minutesToMilliseconds(minutes: number): number {<br>    return minutes * 60 * 1000;<br>  }<br><br>  static isWithinMinutesAfter(timestamp: number, minutes: number): boolean {<br>    const now: number = new Date().getTime();<br><br>    return now - timestamp &lt; AppHelperService.minutesToMilliseconds(minutes);<br>  }<br>}</pre><blockquote><em>seed.service.ts</em></blockquote><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { SeederModule } from &#39;./seeder.module&#39;;<br>import { SeederService } from &#39;./seeder.service&#39;;<br>import { INestApplicationContext } from &#39;@nestjs/common&#39;;<br>import { RequestClientData } from &#39;./data/request-client.data&#39;;<br>import { randomBytes } from &#39;crypto&#39;;<br><br>// move below code into a separate file like &quot;request-client.data.ts&quot;<br>const RequestClientData: RequestClientTypes[] = [<br>  {<br>    clientName: CLIENT_NAME_1,<br>    clientId: AppHelperService.generateUUID(),<br>    clientKey: randomBytes(32).toString(&#39;hex&#39;),<br>  },<br>] as RequestClientTypes[];<br><br>async function runSeeder(): Promise&lt;void&gt; {<br>  const appContext: INestApplicationContext = await NestFactory.createApplicationContext(SeederModule);<br>  const seeder: SeederService = appContext.get(SeederService);<br><br>  await seeder.addClientKeys(RequestClientData);<br><br>  console.log(&#39;seeder endpoint...&#39;);<br>}<br><br>runSeeder()<br>  .then(() =&gt; process.exit(0))<br>  .catch((error: Error) =&gt; {<br>    console.error(error);<br>    process.exit(1);<br>  });</pre><blockquote><em>seeder.service.ts</em></blockquote><pre>export class SeederService {<br>  constructor(<br>    private readonly configRepository: ConfigRepository,<br> ) {}<br>  <br><br>type RequestClientTypes = { clientName: RequestClientsEnum; clientId: string; clientKey: string };<br><br>async addClientKeys(requestClientData: RequestClientTypes[]): Promise&lt;void&gt; {<br>    console.log(&#39;...Client Keys start...&#39;);<br><br>    const newClientIds: unknown[] = [];<br><br>    for (const client of requestClientData) {<br>      const existingClient: Config = await this.configRepository.findOne(client.clientName);<br><br>      if (!existingClient) {<br>        newClientIds.push(client);<br><br>        const value: string = JSON.stringify({<br>          clientName: client?.clientName,<br>          clientKey: AppHelperService.encrypt(client?.clientKey),<br>        });<br><br>        await this.configRepository.save({<br>          key: client?.clientId,<br>          value,<br>          description: `Request Signature data for ${client?.clientName}`,<br>        } as Partial&lt;Config&gt;);<br>      }<br>    }<br><br>    if (newClientIds?.length) {<br>      // share Ids with client, i.e. Through Email Or Add into a file.<br>    }<br><br>    console.log(&#39;...Client Keys Added...&#39;);<br>  }<br><br>}</pre><blockquote>app.module.ts</blockquote><blockquote>app.module.ts</blockquote><pre>providers: [<br>   // rest of code <br>   {<br>      provide: APP_GUARD,<br>      useClass: RequestSignatureGuard,<br>    },<br>]</pre><blockquote>main.ts</blockquote><pre>const config: Omit&lt;OpenAPIObject, &#39;paths&#39;&gt; = new DocumentBuilder()   <br>  <br>  // rest of Swagger configs<br>  config.addGlobalParameters({<br>      in: &#39;header&#39;,<br>      required: true,<br>      name: &#39;x-signature&#39;,<br>      schema: {<br>        example: &#39;x-signature&#39;,<br>      },<br>    })</pre><p>That’s All, We protect our APIs. 🙌</p><p><em>With this setup, we ensure that our API endpoints are protected by HMAC signatures, adding an extra layer of security to our application. This method is particularly useful for securing public endpoints that do not require authentication but still need protection against tampering and unauthorized access. But in my implementation, I implement it for all APIs.</em></p><p><strong><em>P.S. </em></strong><em>crypto is part of NodeJs. You can use another library to make it more secure</em><strong><em>.</em></strong></p><p><strong><em>P.S. </em></strong><em>SHARED_SECRET_KEY will be the same and shared by </em><em>Front-end and </em><em>Back-end.</em></p><p><strong><em>P.S.</em></strong><em> </em><em>Front-end and </em><em>Back-end should use the same encryption algorithm e.g. </em><em>sha256.</em></p><p><strong><em>P.S.</em></strong><em> You can add more parameters in the signature message to make it more secure along with </em><em>url and </em><em>body in the above example.</em></p><p><em>If you want to protect public routes only, remove </em><em>ReuqestSignatureGuard.guard.ts from </em><em>app.module.ts and replace </em><em>NoAuth.guard.ts with the below code.</em>NoAuth.guard.ts</p><pre>import { SetMetadata, applyDecorators, UseGuards } from &#39;@nestjs/common&#39;;<br>import { RequestSignatureGuard } from &#39;../guards/request-signature.guard&#39;;<br>export const NO_AUTH_KEY: string = &#39;no-auth&#39;;<br><br>export const NoAuth = () =&gt; {<br>  return applyDecorators(<br>    SetMetadata(NO_AUTH_KEY, true),<br>    UseGuards(RequestSignatureGuard),<br>  );<br>};</pre><p><strong>Note:</strong> This is not the replacement of JWT. It&#39;s just an extra layer of security on your APIs. <em>Feel free to share your thoughts and suggestions. </em>😃</p><p>That is all for this post. I’m excited to see you in the other posts soon.</p><p>If you found this blog post useful then <strong>clap</strong>, <strong>comment</strong>, and <strong>follow.</strong></p><p>🤝 <strong>Let’s</strong> c<strong><em>onnect on LinkedIn: </em></strong><a href="https://www.linkedin.com/in/raheel-butt-82142a143/"><strong><em>Raheel Butt</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52217ef9368c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under Development API Downtime]]></title>
            <link>https://medium.com/@buttraheel6/under-development-api-downtime-2f21acfa09fb?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f21acfa09fb</guid>
            <category><![CDATA[pm2]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Sat, 29 Jun 2024 15:14:09 GMT</pubDate>
            <atom:updated>2024-06-29T15:22:52.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*ZInX7YJQ9LeLf0aWpQPi3A.png" /><figcaption>PM2</figcaption></figure><p><em>I came across an interesting problem we often face as developers: “</em><strong><em>Under Development API Downtime</em></strong><em>” 😱</em></p><p><em>Intriguing title, right? 😵Let’s dive in and tackle this issue together.</em></p><p>When we develop an application simultaneously with the Front-end, QA, and Backend teams, sharing the ngrok, we often encounter this problem:</p><blockquote><strong>Case 1:</strong> The Front-end dev needs more time to develop a screen or component using the existing API created by the Backend dev.</blockquote><blockquote><strong>Case 2:</strong> The QA team is automating existing screens.</blockquote><blockquote><strong>Issue: </strong>Meanwhile, the Backend dev is working on new APIs for future use. When the Backend dev saves changes, the server restarts or the backend dev stuck with an error which take time to resolve, causing delays for the Front-end dev and QA team.</blockquote><p>Note: This challenge can lead to missed deadlines.:exploding_head:</p><blockquote><strong>Simple Solution:</strong> Some Backend devs keep a copy of their codebase and run backend servers on different ports, sharing the non-developing environment’s ngrok with other teams while they work on the new codebase.</blockquote><p>However, this approach has trade-offs:</p><ol><li>Extra space for the codebase copy.</li></ol><p>2. Backend devs need to manually update the copies with new APIs, when ready.</p><p>There are several solutions, each with its pros and cons. Today, I propose one of these solutions.</p><blockquote><strong>My Proposed Solution: PM2</strong></blockquote><p>Use PM2 (a process manager for Node.js) to run your Node.js/NestJS application in cluster mode. This can help reduce downtime when the server restarts.</p><h4>1. Install PM2 globally:</h4><pre>npm install -g pm2</pre><p><strong>2. Using Ecosystem File for PM2:</strong></p><p>a. If you want to run only one cluster then use the following command</p><pre>pm2 start path/to/your/dist/main.js - name &quot;&lt;name_your_server&gt;&quot;</pre><p>b. If you want to run more than one cluster then use the following code snippet.</p><p>Create an ecosystem.config.js file to define different environments and ports.</p><pre>const scriptPath = &#39;path/to/your/dist/main.js&#39;;<br><br>module.exports = {<br>  apps: [<br>    {<br>      name: &#39;app-dev&#39;,<br>      script: scriptPath,<br>      env: {<br>        NODE_ENV: &#39;development&#39;,<br>        PORT: 3000,<br>      },<br>    },<br>    {<br>      name: &#39;app-qa&#39;,<br>      script: scriptPath,<br>      env: {<br>        NODE_ENV: &#39;qa&#39;,<br>        PORT: 3001,<br>      },<br>    },<br>  ],<br>};</pre><p><strong>3. Start PM2 using the Ecosystem Configuration:</strong></p><pre>pm2 start ecosystem.config.js</pre><p><strong>4. Verify Running Applications:</strong></p><pre>pm2 list</pre><p><strong>5. Check Running Application Logs:</strong></p><pre>pm2 logs &lt;PM2_process_id_name&gt;</pre><p><strong>6. Updating the old PM2 dist with the new dist:</strong></p><pre>pm2 reload all</pre><p>That’s it! Issue resolved. Now you can share the ngrok with different teams without delays. 🙌</p><p><strong><em>P.S. Don’t forget to add ecosystem.config.js to your .gitignore file if you create this file in your codebase.</em></strong></p><p><strong><em>P.S. You don’t need to build your codebase to serve it with PM2. Use the existing dist folder in your codebase directory when running the server.</em></strong></p><p><strong><em>P.S. PM2 will not automatically stop your clusters, even if you restart your machine. This is unusual, so please stop them manually using the following command:</em></strong></p><pre>pm2 stop all<br><br>OR<br><br>pm2 stop &lt;process_id_name&gt;<br><br>OR<br><br>pm2 delete all<br><br>OR<br><br>pm2 delete &lt;process_id_name&gt;</pre><p>Otherwise, your machine may experience slowness, and you may not understand the reason. 😅</p><p>That is all for this post. I’m excited to see you in the other posts soon.</p><p>If you found this blog post useful then <strong>clap</strong>, <strong>comment</strong>, and <strong>follow.</strong></p><p>🤝 <strong>Let’s</strong> c<strong><em>onnect on LinkedIn: </em></strong><a href="https://www.linkedin.com/in/raheel-butt-82142a143/"><strong><em>Raheel Butt</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f21acfa09fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Messaging System: Kafka vs RabbitMQ]]></title>
            <link>https://medium.com/@buttraheel6/choosing-the-right-messaging-system-kafka-vs-rabbitmq-2bf9654bb6ec?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bf9654bb6ec</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Wed, 08 May 2024 03:55:21 GMT</pubDate>
            <atom:updated>2024-05-08T03:55:21.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*UQ-iw_xzRyrdOnfMs9kdUw.jpeg" /><figcaption>Kafka vs RabbitMQ</figcaption></figure><p>In the realm of modern software architecture, messaging systems play a crucial role in enabling reliable communication between various components of a distributed system. Among the plethora of messaging solutions available, Kafka and RabbitMQ stand out as two popular choices, each with its own strengths and ideal use cases. In this article, we’ll dive into the intricacies of Kafka and RabbitMQ, compare their features, and discuss when to choose one over the other.</p><blockquote><strong>Understanding Kafka and RabbitMQ:</strong></blockquote><p><a href="https://medium.com/@buttraheel6/understanding-apache-kafka-a-deep-dive-into-its-architecture-9fed765507a3"><strong>Kafka:</strong></a></p><p>Apache Kafka, initially developed by LinkedIn, has gained widespread adoption as a high-throughput distributed messaging system. It is designed to handle massive streams of data with low latency, making it particularly suitable for use cases involving real-time event streaming. Kafka’s architecture is based on topics and partitions, allowing for horizontal scalability across multiple nodes.</p><p><a href="https://medium.com/@buttraheel6/unlocking-the-power-of-rabbitmq-a-comprehensive-guide-to-message-queuing-632d4aab6261"><strong>RabbitMQ:</strong></a></p><p>On the other hand, RabbitMQ is an open-source message broker that implements the Advanced Message Queuing Protocol (AMQP). Developed using the Erlang programming language, RabbitMQ prioritizes ease of use and reliability. It supports various messaging protocols, including AMQP, MQTT, and STOMP, making it versatile for integration with different systems and technologies.</p><blockquote><strong>Comparing Kafka and RabbitMQ:</strong></blockquote><p><strong><em>Performance:</em></strong></p><p>Kafka excels in scenarios that demand high throughput and low latency. Its <a href="https://medium.com/@buttraheel6/understanding-distributed-systems-advantages-and-challenges-5242c19c1f44"><strong>distributed</strong></a> nature enables it to handle millions of messages per second across multiple partitions. RabbitMQ, while reliable, may not match Kafka’s performance in high-volume streaming environments.</p><p><strong><em>Scalability:</em></strong></p><p>Kafka’s distributed architecture allows for seamless scalability by adding more nodes to the cluster. It automatically rebalances partitions and distributes the load across available brokers. RabbitMQ supports clustering for scalability but might require more manual intervention compared to Kafka’s automated scaling capabilities.</p><p><strong><em>Message Persistence:</em></strong></p><p>Kafka retains messages for a configurable period, offering robust data persistence for scenarios requiring long-term data retention and replayability. RabbitMQ also provides message persistence options but may not be as robust as Kafka’s disk-based storage mechanism.</p><p><strong><em>Use Cases:</em></strong></p><p>Kafka is well-suited for use cases involving real-time event streaming, such as log aggregation, telemetry data processing, and monitoring. Its ability to handle high throughput and fault tolerance makes it ideal for building event-driven architectures. RabbitMQ, on the other hand, shines in simpler messaging scenarios where ease of use and reliability are paramount. It is suitable for point-to-point communication, publish-subscribe patterns, and integration with diverse systems.</p><p><strong>When to Use What:</strong></p><p>When deciding between Kafka and RabbitMQ, consider the specific requirements of your use case:</p><ul><li>Choose Kafka when you need high throughput, low latency, and fault tolerance, especially for real-time event streaming architectures.</li><li>Choose RabbitMQ when simplicity, reliability, and ease of integration are top priorities, and the messaging volume is moderate.</li></ul><p>In summary, both Kafka and RabbitMQ are powerful messaging systems with distinct strengths and use cases. By understanding the nuances of each solution and evaluating your requirements, you can make an informed decision that best suits your application’s needs.</p><p><strong>Conclusion:</strong></p><p><em>Choosing the right messaging system is crucial for building scalable and resilient distributed systems. Kafka and RabbitMQ offer unique features and capabilities, catering to different use cases and scenarios. Whether you prioritize performance, reliability, or ease of use, a messaging solution exists to meet your needs. By weighing the trade-offs and considering your specific requirements, you can confidently select the most suitable option for your application.</em></p><p><strong>Call to Action:</strong></p><p>Have you used Kafka or RabbitMQ in your projects? Share your experiences and insights in the comments below! If you have any questions or need further clarification, feel free to reach out.</p><p>That is all for this post, Kafka vs RabbitMQ. I’m excited to see you in the other posts with the following topics.</p><ol><li><a href="https://medium.com/@buttraheel6/simplifying-kafka-setup-with-docker-a-step-by-step-guide-940714ff7f58"><strong>Installation of Apache Kafka and Zookeeper.</strong></a></li><li><a href="https://medium.com/@buttraheel6/integrating-kafka-with-node-js-building-real-time-applications-ac875d51bf95"><strong>Implementation of Apache Kafka in Node.js</strong></a></li><li><a href="https://medium.com/@buttraheel6/simplifying-rabbitmq-setup-with-docker-a-step-by-step-guide-9698dc9ea4ff"><strong>Installation of RabbitMQ.</strong></a></li><li><a href="https://medium.com/@buttraheel6/integrating-rabbitmq-with-node-js-building-real-time-applications-fa94135bada3"><strong>Implementation of RabbitMQ in Node.js</strong></a></li><li>Many more….</li></ol><p>If you found this blog post useful then <strong>clap</strong>, <strong>comment</strong>, and <strong>follow.</strong></p><p>🤝 <strong>Let’s</strong> c<strong><em>onnect on LinkedIn: </em></strong><a href="https://www.linkedin.com/in/raheel-butt-82142a143/"><strong><em>Raheel Butt</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bf9654bb6ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating RabbitMQ with Node.js: Building Real-time Applications]]></title>
            <link>https://medium.com/@buttraheel6/integrating-rabbitmq-with-node-js-building-real-time-applications-fa94135bada3?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa94135bada3</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Tue, 07 May 2024 11:27:23 GMT</pubDate>
            <atom:updated>2024-05-09T07:02:28.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*d_P1kpEcCnJaa3pF5igDVg.png" /><figcaption>node-rabbitMQ-docker</figcaption></figure><p>In today’s fast-paced world, time is everything. Real-time data streaming has become incredibly important for modern applications. Just imagine being able to process large volumes of data instantly, gaining valuable insights in the blink of an eye! Thanks to powerful tools like RabbitMQ and frameworks like Node.js, developers can now build robust applications that handle real-time data seamlessly.</p><p>RabbitMQ allows applications to send and receive real-time data feeds, while Node.js offers exceptional performance and scalability, making them a perfect pair. The possibilities are truly limitless, opening doors for innovation like never before. Get ready for an exciting journey into the world of real-time data streaming with RabbitMQ and Node.js!</p><p>By the end of this tutorial, you’ll have a solid understanding of how to harness the power of RabbitMQ and Node.js to create real-time data streaming applications that cater to the needs of modern users. Let’s dive in!</p><blockquote><strong><em>Prerequisites: </em></strong><em>Before we dive into the exciting world of real-time data streaming with </em><a href="https://medium.com/@buttraheel6/unlocking-the-power-of-rabbitmq-a-comprehensive-guide-to-message-queuing-632d4aab6261"><strong><em>RabbitMQ</em></strong></a><a href="https://medium.com/@buttraheel6/simplifying-kafka-setup-with-docker-a-step-by-step-guide-940714ff7f58"><strong><em> </em></strong></a><em>and </em><a href="https://nodejs.org/"><strong><em>Node.js</em></strong></a><em>, let’s make sure you have everything set up on your environment.</em></blockquote><p><strong>Project Setup:</strong></p><p>To start, we have to initialize a node project.</p><pre>npm init --yes</pre><p>where — — yes will set the default template values.</p><p>Now, we have to install dependencies to implement the RabbitMQ.</p><pre>npm i amqplib</pre><p>and yes, that’s the only dependency we need to run on servers.</p><p>In the package.json file, we would write one script.</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;node index.js&quot;<br> }</pre><p>After creating the project, design this directory structure in src folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*57m0Tzi2Fk-9liIFT88ZSA.png" /><figcaption>directory structure</figcaption></figure><p><strong>Constants.js — </strong>src/constant.js</p><pre>const YOUR_USERNAME=&#39;REPLACE_WITH_YOUR_USERNAME&#39;<br>const YOUR_PASSWORD=&#39;REPLACE_WITH_YOUR_PASSWORD&#39;<br><br>export const CONNECTION_STRING = `amqp://${YOUR_USERNAME}:${YOUR_PASSWORD}@localhost:5672/`;<br><br>// Define queue properties and configurations<br>export const QUEUE_OPTIONS = {<br>    durable: true, // Make the queue durable<br>    exclusive: false, // Not exclusive<br>    autoDelete: false, // Don&#39;t auto-delete the queue<br>    arguments: {<br>        &#39;x-message-ttl&#39;: 30000, // Message TTL of 30 seconds<br>        &#39;x-max-length&#39;: 1000, // Maximum queue length of 1000 messages<br>    },<br>};<br><br>export const ACKNOWLEGMENT = {noAck: false};</pre><p><strong>Config.js — s</strong>rc/config.js</p><pre>// Established connection to the RabbitMQ<br><br>import amqp from &#39;amqplib&#39;;<br>import {CONNECTION_STRING} from &quot;./constants.js&quot;;<br><br>const connectToRabbitMQ = async () =&gt; {<br>    try {<br>        const connection = await amqp.connect(CONNECTION_STRING);<br>        const channel = await connection.createChannel();<br><br>        return {connection, channel}<br>    } catch (error) {<br>        console.error(&#39;Error connecting to RabbitMQ:&#39;, error);<br>    }<br>}<br><br>export default connectToRabbitMQ</pre><p><strong>index.js —</strong> src/modules/create_queue/index.js</p><pre>// Create a queue with a specified name<br><br>import connectToRabbitMQ from &#39;../config.js&#39;;<br>import {QUEUE_OPTIONS} from &quot;../constants.js&quot;;<br><br>const createQueue = async (queueName) =&gt; {<br>    try {<br>        const {connection, channel} = await connectToRabbitMQ();<br><br>        await channel.assertQueue(queueName, QUEUE_OPTIONS);<br>        console.log(&#39;Queue created successfully.&#39;);<br><br>        return {connection,channel}<br>    } catch (error) {<br>        console.error(&#39;Error creating queue:&#39;, error);<br>    }<br>}<br><br>export default createQueue</pre><p><strong>index.js — </strong>src/modules/creating_exchange<strong>/</strong>index.js</p><pre>import {QUEUE_OPTIONS} from &quot;../../constants.js&quot;;<br><br>const declareExchange = async (channel, exchangeType, exchangeName) =&gt; {<br>    try {<br>        await channel.assertExchange(exchangeName, exchangeType, QUEUE_OPTIONS);<br>        console.log(`${exchangeName} exchange declared....`);<br>    } catch (error) {<br>        console.error(`Error declaring ${exchangeName} exchange:`, error);<br>    }<br>}<br><br>export default declareExchange</pre><p><strong>index.js</strong> — src/modules/bind_queue_with_exchange/index.js</p><pre>import {QUEUE_OPTIONS} from &quot;../../constants.js&quot;;<br><br>const bindQueueWithExchange = async (channel, queueName, exchangeName,queueOptions=QUEUE_OPTIONS) =&gt; {<br>    try {<br>        await channel.assertQueue(queueName, queueOptions);<br>        await channel.bindQueue(queueName, exchangeName, &#39;&#39;);<br>        console.log(&#39;Queue declared and bound to exchange:&#39;, queueName);<br>    } catch (error) {<br>        console.error(&#39;Error declaring and binding queue:&#39;, error);<br>    }<br>}<br><br>export default bindQueueWithExchange</pre><p>Now, we are going to create the core implementation for asserting messages into queues <strong>(Producers)</strong> without exchange and with exchanges i.e. Direct, Topic, Fanout.</p><p><strong>index.js — </strong>src/modules/message_consumer/index.js</p><pre>import {ACKNOWLEGMENT} from &quot;../../constants.js&quot;;<br><br>const consumer =<br>    async (queueName, channel, exchangeName = &#39;&#39;) =&gt; {<br>        try {<br>            await channel.consume(queueName, (message) =&gt; {<br>                if (message) {<br>                    console.log(`Message consumed from queue ${queueName}:`, message.content.toString());<br><br>                    channel.ack(message)<br>                } else {<br>                    console.error(&#39;Something went wrong. Try again!&#39;)<br>                }<br>            }, ACKNOWLEGMENT);<br><br>            if (exchangeName) {<br>                console.log(&#39;Consumer started for exchange:&#39;, exchangeName);<br>            }<br>        } catch (error) {<br>            console.error(&#39;Error consuming message:&#39;, error);<br>        }<br>    }<br><br>export default consumer</pre><blockquote><strong>Creating Queues: Without Exchanges:</strong></blockquote><p><strong>without_exchange.js — </strong>src/modules/queue_asserting/without_exchange.js</p><pre>import createQueue from &quot;../create_queue/index.js&quot;;<br><br>const sendMessageToQueueWithoutExchange = async (channel, message) =&gt; {<br>    try {<br>        const queueName = &#39;queue_without_exchange&#39;<br>        await createQueue(channel, queueName);<br><br>        await channel.sendToQueue(queueName, Buffer.from(JSON.stringify({content: message})));<br>        console.log(`Sent ${message}`);<br>    } catch (error) {<br>        console.error(&#39;An error occurred:&#39;, error);<br>    }<br>}<br><br>export default sendMessageToQueueWithoutExchange</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_MRoih6dQncEBsWVyVxcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVzd8OhiMQIcYFtM68hcrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8yPaf5gz2El_ahHcU7L8A.png" /></figure><blockquote><strong>Creating Queues: With Exchanges:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoAG-7IhLaXShPJG-g9kvA.png" /></figure><ol><li><strong>Create a queue with direct exchange:</strong></li></ol><p>In the direct technique, one queue (e.g. queue A) is bonded/subscribed with the exchange and the producer will publish the message on that exchange only once and the queue (queue A) which is bound with this exchange will receive the messages.</p><p><strong>direct_exchange.js — </strong>src/modules/queue_asserting/direct_exchange.js</p><pre>import declareExchange from &quot;../creating_exchange/index.js&quot;;<br>import bindQueueWithExchange from &quot;../bind_queue_with_exchange/index.js&quot;;<br><br>const sendMessageToQueueWithDirectExchange = async (channel, message) =&gt; {<br>    try {<br>        const exchangeName = &#39;my_direct_exchange&#39;;<br>        const queueName = &#39;my_direct_queue&#39;<br><br>        // Declare the direct exchange<br>        await declareExchange(channel, &#39;direct&#39;, exchangeName)<br>        await bindQueueWithExchange(channel, queueName, exchangeName, {durable: true})<br><br>        // Publish the message to the direct exchange with the routing key<br>        await channel.sendToQueue(queueName, Buffer.from(JSON.stringify({content: message})));<br>        console.log(`Message sent to exchange &#39;${exchangeName} and ${queueName}&#39; : ${message}`);<br>    } catch (error) {<br>        console.error(&#39;Error setting up direct exchange:&#39;, error);<br>    }<br>}<br><br>export default sendMessageToQueueWithDirectExchange;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gbNDhdn3SivLkT2Uf4jOpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMMWH9H5dM0Vh_2_ZzaHuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwgNg-jwAFXkGWdnAu-LYw.png" /></figure><p><strong>2. Create a queue with topic exchange:</strong></p><p>In the topic technique, multiple queues (e.g. queues A, B, Not C) are bonded/subscribed with the exchange by a routing pattern/key and the producer will publish the message on that exchange only once and the queues (queue A, B, Not C) which are bound with this exchange will receive the messages.</p><p><strong>topic_exchange.js — </strong>src/modules/queue_asserting/topic_exchange.js</p><pre>import declareExchange from &quot;../creating_exchange/index.js&quot;;<br>import bindQueueWithExchange from &quot;../bind_queue_with_exchange/index.js&quot;;<br>import {QUEUE_OPTIONS} from &quot;../../constants.js&quot;;<br><br>const sendMessageToQueueWithTopicExchange = async (channel, message) =&gt; {<br>    try {<br>        const queueName = &#39;my_topic_queue&#39;;<br>        const exchangeName = &#39;my_topic_exchange&#39;;<br>        const routingKey = &#39;topic.routing.key&#39;;<br><br>        // Declare the topic exchange<br>        await declareExchange(channel, &#39;topic&#39;, exchangeName)<br>        await bindQueueWithExchange(channel, queueName, exchangeName,QUEUE_OPTIONS , routingKey)<br><br>        // Publish the message to the topic exchange with the routing key<br>        const res = await channel.sendToQueue(queueName, Buffer.from(JSON.stringify({content: message})));<br>        if (res) {<br>            console.log(`Message sent to exchange &#39;${exchangeName}&#39; with routing key &#39;${routingKey}&#39;: ${message}`);<br>        } else {<br>            console.error(&#39;Something went wrong. Try again!&#39;)<br>        }<br>    } catch (error) {<br>        console.error(&#39;Error setting up topic exchange:&#39;, error);<br>    }<br>}<br><br>export default sendMessageToQueueWithTopicExchange;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsrmqjuGkTw5NlULtM-7Aw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e030pb6upDv88dnHN22eVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEOnff2Gtj2HT9AE4yo9wQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdG_nvidMHdBW_GrF_IOWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edLsUJUbF6K4dTEQYBcfsA.png" /></figure><p><strong>3. Create a queue with fanout exchange:</strong></p><p>In the fanout technique, multiple queues (e.g. queues A, B) are bound/subscribed with the exchange, and the producer will publish the message on that exchange only once and the queues (queues A, B) which are bound with this exchange will receive the messages.</p><p><strong>fanout_exchange.js — </strong>src/modules/queue_asserting/fanout_exchange.js</p><pre>import declareExchange from &quot;../creating_exchange/index.js&quot;;<br>import bindQueueWithExchange from &quot;../bind_queue_with_exchange/index.js&quot;;<br><br>const sendMessageToQueueWithFanoutExchange = async (channel, message1, message2) =&gt; {<br>    try {<br>        const firstQueueName = &#39;first_fanout_exchange_queue&#39;;<br>        const secondQueueName = &#39;second_fanout_exchange_queue&#39;;<br>        const exchangeName = &#39;fanout_exchange&#39;<br><br>        await declareExchange(channel, &#39;fanout&#39;, exchangeName)<br>        await bindQueueWithExchange(channel, firstQueueName, exchangeName, {durable: true})<br>        await bindQueueWithExchange(channel, secondQueueName, exchangeName, {durable: true})<br><br>        await channel.sendToQueue(firstQueueName, Buffer.from(JSON.stringify({content: message1})));<br>        await channel.sendToQueue(secondQueueName, Buffer.from(JSON.stringify({content: message2})));<br><br>        console.log(`Sent ${message1}`);<br>        console.log(`Sent ${message2}`);<br>    } catch (error) {<br>        console.error(&#39;An error occurred:&#39;, error);<br>    }<br>}<br><br>export default sendMessageToQueueWithFanoutExchange</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fHPYcype6x_1MvK37WUGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMrdl63C13MPZlda-sg6PQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pV6aU3IIHu6s3TPq-p2Xmg.png" /></figure><p><strong>index.js — </strong>index.js <strong>(Usage):</strong></p><p><strong>Message Consumption/Acknowledgment:</strong></p><p>Message acknowledgments in message queues are like confirmations sent by consumers to the server, saying, “Yes, I received and processed this message.” This acknowledgment process is crucial for ensuring that messages are reliably handled.</p><p>In the provided code, the setting { noAck: false } means that after a consumer processes a message, it must explicitly send an acknowledgment to the server. This is important because it ensures that messages are only removed from the queue after they have been successfully processed.</p><p>If noAck were set to true, the server would remove messages from the queue immediately after delivering them, without waiting for confirmation from the consumer. This configuration is useful for scenarios where speed is more important than ensuring every message is processed.</p><p>So, with { noAck: false }, we must send acknowledgments to the server channel.ack(message) to confirm successful processing. If we don&#39;t acknowledge messages, they will remain in the queue, potentially causing issues with message duplication or queue congestion.</p><ol><li><strong>Consume messages from a queue without exchange:</strong></li></ol><p><strong>without_exchange.js — s</strong>rc/modules/queue_consumption/without_exchange.js</p><pre>import consumer from &quot;../message_consumer/index.js&quot;;<br><br>const consumeMessageFromQueueWithDirectExchange = async (channel) =&gt; {<br>    try {<br>        const exchangeName = &#39;my_direct_exchange&#39;;<br>        const queueName = &#39;my_direct_queue&#39;<br><br>        await consumer(queueName, channel, exchangeName)<br>    } catch (error) {<br>        console.error(&#39;Error consuming message:&#39;, error);<br>    }<br>}<br><br>export default consumeMessageFromQueueWithDirectExchange</pre><p><strong>2. Consume messages from a queue with direct exchange:</strong></p><p><strong>direct_exchange.js — s</strong>rc/modules/queue_consumption/direct_exchange.js</p><pre>import consumer from &quot;../message_consumer/index.js&quot;;<br><br>const consumeMessageFromQueueWithDirectExchange = async (channel) =&gt; {<br>    try {<br>        const exchangeName = &#39;my_direct_exchange&#39;;<br>        const queueName = &#39;my_direct_queue&#39;<br><br>        await consumer(queueName, channel, exchangeName)<br>    } catch (error) {<br>        console.error(&#39;Error consuming message:&#39;, error);<br>    }<br>}<br><br>export default consumeMessageFromQueueWithDirectExchange</pre><p>3. <strong>Consume messages from a queue with the topic exchange:</strong></p><p><strong>topic_exchange.js — s</strong>rc/modules/queue_consumption/topic_exchange.js</p><pre>import consumer from &quot;../message_consumer/index.js&quot;;<br><br>const consumeMessageFromQueueWithTopicExchange = async (channel) =&gt; {<br>    try {<br>        const queueName = &#39;my_topic_queue&#39;;<br>        const exchangeName = &#39;my_topic_exchange&#39;;<br><br>        await consumer(queueName, channel, exchangeName)<br>    } catch (error) {<br>        console.error(&#39;Error consuming message:&#39;, error);<br>    }<br>}<br><br>export default consumeMessageFromQueueWithTopicExchange</pre><p>4. <strong>Consume messages from a queue with the fanout exchange:</strong></p><p><strong>fanout_exchange.js — s</strong>rc/modules/queue_consumption/fanout_exchange.js</p><pre>import consumer from &quot;../message_consumer/index.js&quot;;<br><br>const consumeMessageFromQueueWithFanoutExchange = async (channel) =&gt; {<br>    try {<br>        const firstQueueName = &#39;first_fanout_exchange_queue&#39;;<br>        const secondQueueName = &#39;second_fanout_exchange_queue&#39;;<br>        const exchangeName = &#39;fanout_exchange&#39;<br><br>        await consumer(firstQueueName, channel, exchangeName)<br>        await consumer(secondQueueName, channel, exchangeName)<br>    } catch (error) {<br>        console.error(&#39;Error consuming message:&#39;, error);<br>    }<br>}<br><br>export default consumeMessageFromQueueWithFanoutExchange</pre><p><strong>index.js —</strong> src/modules/consumers/index.js <strong>(Usage):</strong></p><pre>import consumeMessageFromQueueWithoutExchange from &quot;../queue_consumption/without_exchange.js&quot;;<br>import consumeMessageFromQueueWithDirectExchange from &quot;../queue_consumption/direct_exchange.js&quot;;<br>import consumeMessageFromQueueWithTopicExchange from &quot;../queue_consumption/topic_exchange.js&quot;;<br>import consumeMessageFromQueueWithFanoutExchange from &quot;../queue_consumption/fanout_exchange.js&quot;;<br><br>const messageConsumers = async (channel) =&gt; {<br>    try {<br>        // consume message from queue without any exchange<br>        await consumeMessageFromQueueWithoutExchange(channel)<br><br>        // create queue and send message with direct exchange<br>        await consumeMessageFromQueueWithDirectExchange(channel);<br><br>        // create queue and send message with topic exchange<br>        await consumeMessageFromQueueWithTopicExchange(channel);<br><br>        // create queues and send message with fanout exchange<br>        await consumeMessageFromQueueWithFanoutExchange(channel)<br><br>    } catch (error) {<br>        console.error(&#39;An error occurred:&#39;, error);<br>    }<br>}<br><br>export default messageConsumers</pre><p><strong>index.js (Usage):</strong></p><pre>import connectToRabbitMQ from &quot;./src/config.js&quot;;<br><br>import express from &quot;express&quot;;<br>import bodyParser from &quot;body-parser&quot;;<br>import sendMessageWithoutExchange from &quot;./src/modules/controllers/without_exchange_controller.js&quot;;<br>import sendMessageWithDirectExchange from &quot;./src/modules/controllers/direct_exchange_controller.js&quot;;<br>import sendMessageWithTopicExchange from &quot;./src/modules/controllers/topic_exchange_controller.js&quot;;<br>import sendMessageWithFanoutExchange from &quot;./src/modules/controllers/fanout_exchange_controller.js&quot;;<br>import messageConsumers from &quot;./src/modules/consumers/index.js&quot;;<br><br>const app = express();<br>const jsonParser = bodyParser.json();<br><br>const {channel} = await connectToRabbitMQ();<br><br><br>app.get(&quot;&quot;, (req, res, next) =&gt; {<br>    console.log(&#39;Hello to Node Express and RabbitMQ&#39;)<br>    return res.send(&#39;&lt;h1&gt;Hello to Node Express and RabbitMQ&lt;/h1&gt;&#39;)<br>});<br><br>app.post(&quot;/api/without_exchange&quot;, jsonParser, sendMessageWithoutExchange(channel));<br>app.post(&quot;/api/direct_exchange&quot;, jsonParser, sendMessageWithDirectExchange(channel));<br>app.post(&quot;/api/topic_exchange&quot;, jsonParser, sendMessageWithTopicExchange(channel));<br>app.post(&quot;/api/fanout_exchange&quot;, jsonParser, sendMessageWithFanoutExchange(channel));<br><br>await messageConsumers(channel)<br><br>app.listen(8080, () =&gt; {<br>    console.log(`Server is running on port 8080.`);<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3u4BDxEg-SLg-0rkCCGdZw.png" /></figure><p>To explore the full code, visit the <a href="https://github.com/raheelsoft/node-rabbitmq-docker"><strong>node-rabbitmq-docker</strong></a> repository. Follow me on GitHub for additional insightful content and updates.</p><p>Conclusion:</p><p><em>In this tutorial, we’ve explored how to integrate RabbitMQ with Node.js to build real-time applications. We’ve learned how to create a RabbitMQ producer to send messages and create a RabbitMQ consumer to receive messages. With RabbitMQ and Node.js, developers can build scalable, fault-tolerant, and real-time applications that process data streams efficiently.</em></p><p>That is all for this post, Apache Kafka is quite an extensive topic to cover in a single post, and I’m excited to see you in my other couple of posts with the following topics.</p><ol><li><a href="https://medium.com/@buttraheel6/understanding-apache-kafka-a-deep-dive-into-its-architecture-9fed765507a3"><strong>Kafka</strong></a> <a href="https://medium.com/@buttraheel6/choosing-the-right-messaging-system-kafka-vs-rabbitmq-2bf9654bb6ec"><strong>vs</strong></a> <a href="https://medium.com/@buttraheel6/unlocking-the-power-of-rabbitmq-a-comprehensive-guide-to-message-queuing-632d4aab6261"><strong>RebitMQ</strong></a></li></ol><p>If you found this blog post useful then <strong>clap</strong>, <strong>comment</strong>, and <strong>follow.</strong></p><p>🤝 <strong>Let’s</strong> c<strong><em>onnect on LinkedIn: </em></strong><a href="https://www.linkedin.com/in/raheel-butt-82142a143/"><strong><em>Raheel Butt</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa94135bada3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying RabbitMQ Setup with Docker: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@buttraheel6/simplifying-rabbitmq-setup-with-docker-a-step-by-step-guide-9698dc9ea4ff?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/9698dc9ea4ff</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Tue, 07 May 2024 02:16:58 GMT</pubDate>
            <atom:updated>2024-05-08T03:56:34.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*qMd22ixsyCeh3JJ8FX3SMQ.jpeg" /><figcaption>RabbitMQ</figcaption></figure><p><a href="https://medium.com/@buttraheel6/unlocking-the-power-of-rabbitmq-a-comprehensive-guide-to-message-queuing-632d4aab6261"><strong>RabbitMQ</strong></a> is a message broker, that facilitates seamless communication among various applications or services. Its functionalities include enabling asynchronous communication between microservices, distributing the workload across multiple workers, and ensuring reliable message delivery within intricate distributed systems. On the other hand, Docker offers a platform for packaging, distributing, and executing applications within containers. Docker Compose, a complementary tool, streamlines the definition and execution of multi-container Docker applications.</p><p>Leveraging Docker Compose for RabbitMQ deployment streamlines the process of launching a RabbitMQ instance rapidly and efficiently, abstracting away concerns regarding underlying infrastructure. It further simplifies the scaling of the RabbitMQ instance and the management of application configurations. This step-by-step guide will walk you through installing RabbitMQ using Docker Compose.</p><p><strong>Prerequisites:</strong></p><p>Before we begin, ensure you have Docker installed on your machine. If not, you can download and install Docker from the official website: <a href="https://www.docker.com/"><strong>Docker</strong></a>.</p><p><strong>Step 1: Setting up Docker Compose:</strong></p><p>Docker Compose is a tool for defining and running multi-container Docker applications. It allows you to manage complex setups with ease. If you haven’t already installed Docker Compose, follow the instructions <a href="https://docs.docker.com/compose/"><strong>here</strong></a> to install it.</p><p><strong>Step 2: Writing the Docker Compose File:</strong></p><p>We’ll start by creating a docker-compose.yml file to define our RabbitMQ setup. Below is a sample configuration that includes RabbitMQ and Management plugin:</p><pre>version: &#39;3&#39;<br><br>services:<br>  rabbitmq:<br>    image: rabbitmq:management<br>    container_name: rabbitmq<br>    environment:<br>      - RABBITMQ_DEFAULT_USER=YOUR_USERNAME<br>      - RABBITMQ_DEFAULT_PASS=YOUR_PASSWORD<br>    ports:<br>      - &quot;5672:5672&quot;<br>      - &quot;15672:15672&quot;<br><br>networks:<br>  default:<br>    driver: bridge</pre><p><strong>In this configuration:</strong></p><ul><li>version: &#39;3&#39;: This specifies the version of the Docker Compose file format that we are using.</li><li>services: This section defines the RabbitMQ service that we want to deploy. In this case, we are using the official RabbitMQ Docker image with the management plugin enabled.</li><li>image: rabbitmq:management: This specifies the <a href="https://hub.docker.com/_/rabbitmq?ref=christian-schou.dk"><strong>RabbitMQ Docker image</strong></a><strong> </strong>we want to use.</li><li>container_name: rabbitmq: This assigns a name to the RabbitMQ container.</li><li>environment: This section sets environment variables for the RabbitMQ container. In this example, we are setting the default username and password to &quot;guest&quot;. Note that this is not recommended for production environments.</li><li>ports: This section maps the ports used by RabbitMQ to the corresponding ports on the host machine. In this case, we are mapping the port 5672 for AMQP communication and the port 15672 for the RabbitMQ management interface.</li><li>networks: This section specifies the network settings for the RabbitMQ container. In this example, we are using the default Docker bridge network.</li></ul><p><strong>Step 3: Starting RabbitMQ and Management plugin:</strong></p><p>To start RabbitMQ and Management plugin, navigate to the directory containing your docker-compose.yml file and run the following command:</p><pre>docker-compose up -d</pre><p>This command will pull the necessary Docker images (if not already available) and start the RabbitMQ and Management plugin containers in the background.</p><p><strong>Step 4: Verifying Installation:</strong></p><p>Once the containers are up and running, you can verify the installation by accessing the RabbitMQ Management UI in your web browser. Navigate to http://localhost:15672 view the Management dashboard. From here, you can monitor RabbitMQ connections, channels, exchanges, queues, and streams in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJrhauy4sfoWMqfn0FgRbw.png" /><figcaption>RabbitMQ Management UI</figcaption></figure><p><strong>Conclusion:</strong></p><p><em>By leveraging Docker and Docker Compose, you can streamline the installation and management of RabbitMQ, making it easier to develop, test, and deploy RabbitMQ-based applications. The </em><em>docker-compose.yml file provided in this guide serves as a starting point for building more complex RabbitMQ setups tailored to your specific requirements.</em></p><p>That is all for this post, RabbitMQ is quite an extensive topic to cover in a single post, and I’m excited to see you in the next couple of posts with the following topics.</p><ol><li><a href="https://medium.com/@buttraheel6/integrating-rabbitmq-with-node-js-building-real-time-applications-fa94135bada3"><strong>Implementation of RabbitMQ in Node.js</strong></a></li><li><a href="https://medium.com/@buttraheel6/unlocking-the-power-of-rabbitmq-a-comprehensive-guide-to-message-queuing-632d4aab6261"><strong>RebitMQ</strong></a> <a href="https://medium.com/@buttraheel6/choosing-the-right-messaging-system-kafka-vs-rabbitmq-2bf9654bb6ec"><strong>vs</strong></a> <a href="https://medium.com/@buttraheel6/understanding-apache-kafka-a-deep-dive-into-its-architecture-9fed765507a3"><strong>Kafka</strong></a></li><li>Many more….</li></ol><p>If you found this blog post useful then <strong>clap</strong>, <strong>comment</strong>, and <strong>follow.</strong></p><p>🤝 <strong>Let’s</strong> c<strong><em>onnect on LinkedIn: </em></strong><a href="https://www.linkedin.com/in/raheel-butt-82142a143/"><strong><em>Raheel Butt</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9698dc9ea4ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of RabbitMQ: A Comprehensive Guide to Message Queuing]]></title>
            <link>https://medium.com/@buttraheel6/unlocking-the-power-of-rabbitmq-a-comprehensive-guide-to-message-queuing-632d4aab6261?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/632d4aab6261</guid>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[flexibility]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Mon, 06 May 2024 22:46:13 GMT</pubDate>
            <atom:updated>2024-05-08T03:56:07.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoAG-7IhLaXShPJG-g9kvA.png" /><figcaption>RabbitMQ</figcaption></figure><p>In today’s interconnected world, where real-time communication and data exchange are crucial, <a href="https://medium.com/@buttraheel6/exploring-message-streaming-architectures-a-guide-to-pub-sub-queues-0e2de63ccb9b"><strong>messaging queues</strong></a> play a pivotal role in ensuring seamless interaction between various components of a system. One such powerful messaging queue is RabbitMQ. In this comprehensive guide, we’ll delve into the world of RabbitMQ, exploring its necessity, introduction, types, benefits, components, and alternatives.</p><blockquote><strong>The Necessity of Messaging Queues:</strong></blockquote><p>Before delving into RabbitMQ specifically, let’s understand why messaging queues are essential in modern software architecture. Messaging queues facilitate asynchronous communication between different parts of a system, enabling decoupling, scalability, and fault tolerance. They act as intermediaries, ensuring that messages are safely stored and delivered even when systems are temporarily unavailable or overloaded. This asynchronous communication pattern is fundamental to building robust, distributed systems.</p><blockquote><strong>What is RabbitMQ? </strong>RabbitMQ is an open-source message broker that implements the Advanced Message Queuing Protocol (AMQP). Developed using the Erlang programming language, RabbitMQ provides a robust messaging solution for both synchronous and asynchronous communication scenarios. It acts as a mediator between producers (applications that send messages) and consumers (applications that receive messages), ensuring reliable delivery and efficient message routing.</blockquote><blockquote><strong>Key components of RabbitMQ:</strong></blockquote><ol><li><strong>Broker:</strong> The RabbitMQ broker is the core component responsible for receiving, routing, and delivering messages between producers and consumers. It acts as a messaging intermediary, ensuring that messages are correctly routed from publishers to queues and from queues to consumers. The broker manages connections, exchanges, queues, and message delivery.</li><li><strong>Exchange:</strong> Exchanges receive messages from producers and are responsible for routing these messages to one or more queues based on predefined rules. Exchanges determine the message routing logic, such as direct, fanout, topic, or headers-based routing. RabbitMQ supports multiple types of exchanges to accommodate various routing scenarios and messaging patterns.</li><li><strong>Queue:</strong> Queues are buffers that hold messages until they are consumed by consumers. When a message is published to an exchange, the exchange routes the message to one or more queues based on bindings and routing rules. Consumers retrieve messages from queues in a first-in-first-out (FIFO) manner, ensuring that messages are processed in the order they were received.</li><li><strong>Binding:</strong> Bindings establish a relationship between exchanges and queues, specifying how messages should be routed from exchanges to queues. Bindings define routing rules based on criteria such as routing keys or message headers. Each queue can be bound to one or more exchanges, allowing for flexible message routing and distribution.</li><li><strong>Connection:</strong> Connections represent network connections established between clients (producers and consumers) and the RabbitMQ broker. Connections handle the communication protocol between clients and the broker, allowing clients to publish messages, consume messages, and manage resources within the messaging system.</li><li><strong>Channel:</strong> Channels provide a virtual connection within a connection, allowing multiple operations to be performed concurrently over a single network connection. Channels enable efficient message multiplexing and resource management, reducing the overhead associated with establishing and maintaining multiple network connections.</li></ol><blockquote><strong>Exchanges:</strong></blockquote><p>There are several types of exchanges in RabbitMQ, each with its own routing strategy:</p><ol><li><strong>Direct Exchange:</strong> Direct exchanges route messages to queues based on a routing key specified by the producer. The routing key is compared with the routing keys specified in the bindings between the exchange and queues, and the message is routed to the queue with a matching key.</li><li><strong>Fanout Exchange:</strong> Fanout exchanges route messages to all bound queues, regardless of the routing key. They are useful for broadcasting messages to multiple consumers or distributing workloads across multiple consumers without any routing criteria.</li><li><strong>Topic Exchange:</strong> Topic exchanges route messages to queues based on wildcard patterns in the routing key. They use wildcard characters (* and #) to match routing keys, allowing for dynamic and flexible routing based on message attributes.</li><li><strong>Headers Exchange:</strong> Headers exchanges route messages based on message headers rather than routing keys. Producers can specify arbitrary headers in messages, and consumers can bind queues to the exchange with header-based criteria.</li></ol><p>By selecting the appropriate type of exchange and configuring bindings between exchanges and queues, developers can implement sophisticated routing strategies tailored to their application’s requirements.</p><blockquote><strong>Benefits of RabbitMQ:</strong></blockquote><p>RabbitMQ offers a plethora of benefits, making it a preferred choice for building distributed systems:</p><ol><li><strong>Reliability:</strong> RabbitMQ ensures message reliability through message acknowledgments. When a consumer receives and processes a message, it sends an acknowledgment (ack) back to RabbitMQ. If RabbitMQ doesn’t receive an acknowledgment within a specified time frame, it assumes that the message was not processed successfully and redelivers it to another consumer or re-queues it for later processing. This mechanism ensures that messages are not lost even in the presence of network failures or consumer crashes.</li><li><strong>Scalability:</strong> RabbitMQ achieves scalability through features like message clustering and publisher confirms. Message clustering allows multiple RabbitMQ nodes to work together as a single logical broker, distributing the message load across multiple nodes and providing horizontal scalability. Publisher confirms enable publishers to receive acknowledgments from RabbitMQ after a message is successfully routed to an exchange, ensuring that messages are not lost even during periods of high message throughput.</li><li><strong>Flexibility:</strong> RabbitMQ offers flexibility through support for multiple messaging protocols, including AMQP (Advanced Message Queuing Protocol), MQTT (Message Queuing Telemetry Transport), and STOMP (Simple Text Oriented Messaging Protocol). This allows developers to choose the protocol that best fits their use case and enables seamless integration with different components of the system.</li><li><strong>Durability:</strong> RabbitMQ ensures message durability through message persistence. Messages can be configured to be persistent, meaning they are written to disk before being acknowledged by RabbitMQ. This ensures that messages are not lost even in the event of a broker restart or crash, providing data integrity and reliability.</li><li><strong>Monitoring and Management: </strong>RabbitMQ provides comprehensive monitoring and management tools, including a web-based management interface and command-line tools. Administrators can monitor various aspects of the RabbitMQ broker, including queues, connections, message rates, and resource utilization. This visibility into the system’s health and performance enables administrators to identify and address issues proactively, ensuring the reliability and availability of the messaging infrastructure.</li></ol><p><strong>Conclusion:</strong></p><p><em>RabbitMQ stands as a robust messaging solution, offering reliability, scalability, and flexibility for building distributed systems. By understanding its necessity, introduction, types, benefits, components, and alternatives, developers can make informed decisions when designing messaging architectures for their applications. Whether it’s ensuring real-time communication between microservices or implementing event-driven architectures, RabbitMQ continues to play a vital role in modern software development.</em></p><p>That is all for this post, RabbitMQ is quite an extensive topic to cover in a single post, and I’m excited to see you in the next couple of posts with the following topics.</p><ol><li><a href="https://medium.com/@buttraheel6/simplifying-rabbitmq-setup-with-docker-a-step-by-step-guide-9698dc9ea4ff"><strong>Installation of RabbitMQ.</strong></a></li><li><a href="https://medium.com/@buttraheel6/integrating-rabbitmq-with-node-js-building-real-time-applications-fa94135bada3"><strong>Implementation of RabbitMQ in Node.js</strong></a></li><li>RebitMQ <a href="https://medium.com/@buttraheel6/choosing-the-right-messaging-system-kafka-vs-rabbitmq-2bf9654bb6ec"><strong>vs</strong></a> <a href="https://medium.com/@buttraheel6/understanding-apache-kafka-a-deep-dive-into-its-architecture-9fed765507a3"><strong>Kafka</strong></a></li><li>Many more….</li></ol><p>If you found this blog post useful then <strong>clap</strong>, <strong>comment</strong>, and <strong>follow.</strong></p><p>🤝 <strong>Let’s</strong> c<strong><em>onnect on LinkedIn: </em></strong><a href="https://www.linkedin.com/in/raheel-butt-82142a143/"><strong><em>Raheel Butt</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=632d4aab6261" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Kafka with Node.js: Building Real-time Applications]]></title>
            <link>https://medium.com/@buttraheel6/integrating-kafka-with-node-js-building-real-time-applications-ac875d51bf95?source=rss-316436f83399------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac875d51bf95</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Raheel Butt]]></dc:creator>
            <pubDate>Mon, 06 May 2024 01:41:00 GMT</pubDate>
            <atom:updated>2024-05-08T03:59:42.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AA2qmUk9Em_NImsujsKyCQ.png" /><figcaption>Kafka with Node.js</figcaption></figure><p>In today’s fast-paced world, time is everything. Real-time data streaming has become incredibly important for modern applications. Just imagine being able to process large volumes of data instantly, gaining valuable insights in the blink of an eye! Thanks to powerful tools like Apache Kafka and frameworks like Node.js, developers can now build robust applications that handle real-time data seamlessly.</p><p>Kafka allows applications to send and receive real-time data feeds, while Node.js offers exceptional performance and scalability, making them a perfect pair. The possibilities are truly limitless, opening doors for innovation like never before. Get ready for an exciting journey into the world of real-time data streaming with Kafka and Node.js!</p><p>By the end of this tutorial, you’ll have a solid understanding of how to harness the power of Kafka and Node.js to create real-time data streaming applications that cater to the needs of modern users. Let’s dive in!</p><blockquote><strong>Prerequisites: </strong>Before we dive into the exciting world of real-time data streaming with <a href="https://medium.com/@buttraheel6/simplifying-kafka-setup-with-docker-a-step-by-step-guide-940714ff7f58"><strong>Kafka </strong></a>and <a href="https://nodejs.org/"><strong>Node.js</strong></a>, let’s make sure you have everything set up on your environment.</blockquote><p><strong>Project Setup:</strong></p><p>To start, we have to initialize a node project.</p><pre>npm init --yes</pre><p>where — — yes will set the default template values.</p><p>Now, we have to install dependencies to implement the Kafka.</p><pre>npm i body-parser express kafkajs nodemon</pre><p>and yes, that’s the only dependency we need to run on servers.</p><p>Now, we would create two different server files named producer.js and consumer.js.</p><p>Before that, In the package.json file, we would write one script.</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;node index.js&quot;<br> }</pre><p><strong>Constants.js</strong></p><pre>export const TOPIC_NAME = &quot;my-topic&quot;<br>export const GROUP_ID = &quot;test-group&quot;<br>export const CLIENT_ID = &quot;nodejs-kafka&quot;<br>export const BROKERS = [&quot;localhost:9092&quot;]</pre><p><strong>Config.js</strong></p><pre>import {Kafka} from &quot;kafkajs&quot;;<br>import {BROKERS, CLIENT_ID} from &quot;./constants.js&quot;;<br><br>const kafkaConfig = {<br>    clientId: CLIENT_ID,<br>    brokers: BROKERS,<br>};<br><br>const kafka = new Kafka(kafkaConfig);<br><br>export default kafka;</pre><p><strong>Producer.js</strong></p><pre>import kafka from &quot;./config.js&quot;;<br><br>class KafkaProducer {<br>    constructor() {<br>        this.producer = kafka.producer();<br>    }<br><br>    async produce(topic, messages) {<br>        try {<br>            await this.producer.connect();<br>            await this.producer.send({<br>                topic: topic,<br>                messages: messages,<br>            });<br>        } catch (error) {<br>            console.error(error);<br>        } finally {<br>            await this.producer.disconnect();<br>        }<br>    }<br>}<br><br>export default KafkaProducer;</pre><p>Consumer.js</p><pre>import kafka from &quot;./config.js&quot;;<br><br>class KafkaConsumer {<br>    constructor(groupId) {<br>        this.consumer = kafka.consumer({groupId});<br>    }<br><br>    async consume(topic, callback) {<br>        try {<br>            await this.consumer.connect();<br>            await this.consumer.subscribe({topic, fromBeginning: true});<br>            await this.consumer.run({<br>                eachMessage: async ({topic, partition, message}) =&gt; {<br>                    const value = message.value.toString();<br>                    callback(topic, partition, value);<br>                },<br>            });<br>        } catch (error) {<br>            console.error(error);<br>        }<br>    }<br>}<br><br>export default KafkaConsumer;</pre><p><strong>fromBeginning:</strong> is set to true, which means that whenever we start consuming messages from a specific topic, we want to consume all the messages the topic has from the beginning. Otherwise, it will start consuming the messages produced after running our consumer server.</p><p>Controller.js</p><pre>import KafkaProducer from &quot;./producer.js&quot;;<br>import {TOPIC_NAME} from &quot;./constants.js&quot;;<br><br>const sendMessageToKafka = async (req, res) =&gt; {<br>    try {<br>        const {message} = req.body;<br>        const kafkaProducer = new KafkaProducer();<br>        const messages = [{key: &quot;key1&quot;, value: message}];<br>        kafkaProducer.produce(TOPIC_NAME, messages);<br><br>        res.status(200).json({<br>            status: &quot;Ok!&quot;,<br>            message: &quot;Message successfully send!&quot;,<br>        });<br>    } catch (error) {<br>        console.log(error);<br>    }<br>};<br><br>const constrollers = {sendMessageToKafka};<br><br>export default constrollers;</pre><p>Index.js</p><pre>import express from &quot;express&quot;;<br>import bodyParser from &quot;body-parser&quot;;<br>import constrollers from &quot;./controller.js&quot;;<br>import KafkaConsumer from &quot;./consumer.js&quot;;<br>import {GROUP_ID, TOPIC_NAME} from &quot;./constants.js&quot;;<br><br>const app = express();<br>const jsonParser = bodyParser.json();<br><br>app.get(&quot;&quot;, (req, res, next) =&gt; {<br>    console.log(&#39;Hello to Node Express and Kafkajs&#39;)<br>    return res.send(&#39;&lt;h1&gt;Hello to Node Express and Kafkajs&lt;/h1&gt;&#39;)<br>});<br><br>app.post(&quot;/api/send&quot;, jsonParser, constrollers.sendMessageToKafka);<br><br>// consume from topic &quot;test-topic&quot;<br>const kafkaConsumer = new KafkaConsumer(GROUP_ID);<br>kafkaConsumer.consume(TOPIC_NAME, (topic, partition,value) =&gt; {<br>    console.log(&quot;Topic: &quot;,topic,&quot;Partition&quot;, partition)<br>    console.log(&quot;📨 Receive message: &quot;,  value);<br>});<br><br>app.listen(8080, () =&gt; {<br>    console.log(`Server is running on port 8080.`);<br>});</pre><p>To interact with Kafka and test our producer and consumer functionality, we’ll use Postman.</p><blockquote><strong>NOTE:</strong> Make sure your Kafka server and Node.js application are up and running. If not, start them using Docker Compose or any other method you prefer.</blockquote><p>To run the Node.js application run the following command.</p><pre>npm start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfvUz_ar0nbuQ2pQaHbGPw.png" /><figcaption>Postman</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBmHPDxWSkVamtq3yW6c3Q.png" /><figcaption>Output</figcaption></figure><p>To explore the full code, visit the <a href="https://github.com/raheelsoft/node-kafka-docker"><strong>node-kafka-docker</strong></a><strong> </strong>repository. Follow me on <a href="https://github.com/raheelsoft"><strong>GitHub</strong></a> for additional insightful content and updates.</p><p><strong>Conclusion:</strong></p><p><em>In this tutorial, we’ve explored how to integrate Kafka with Node.js to build real-time applications. We’ve learned how to create a Kafka producer to send messages and create a Kafka consumer to receive messages. With Kafka and Node.js, developers can build scalable, fault-tolerant, and real-time applications that process data streams efficiently.</em></p><p>That is all for this post, Apache Kafka is quite an extensive topic to cover in a single post, and I’m excited to see you in my other couple of posts with the following topics.</p><ol><li><a href="https://medium.com/@buttraheel6/simplifying-kafka-setup-with-docker-a-step-by-step-guide-940714ff7f58"><strong>Installation of Apache Kafka and Zookeeper.</strong></a></li><li><a href="https://medium.com/@buttraheel6/understanding-apache-kafka-a-deep-dive-into-its-architecture-9fed765507a3"><strong>Kafka</strong></a> <a href="https://medium.com/@buttraheel6/choosing-the-right-messaging-system-kafka-vs-rabbitmq-2bf9654bb6ec"><strong>vs</strong></a> <a href="https://medium.com/@buttraheel6/unlocking-the-power-of-rabbitmq-a-comprehensive-guide-to-message-queuing-632d4aab6261"><strong>RebitMQ</strong></a></li><li>Many more….</li></ol><p>If you found this blog post useful then <strong>clap</strong>, <strong>comment</strong>, and <strong>follow.</strong></p><p>🤝 <strong>Let’s</strong> c<strong><em>onnect on LinkedIn: </em></strong><a href="https://www.linkedin.com/in/raheel-butt-82142a143/"><strong><em>Raheel Butt</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac875d51bf95" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>