<?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 Elijah Echekwu on Medium]]></title>
        <description><![CDATA[Stories by Elijah Echekwu on Medium]]></description>
        <link>https://medium.com/@elijahechekwu?source=rss-ee32146b770a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*85rkLNAJify95TvutxPrFg.jpeg</url>
            <title>Stories by Elijah Echekwu on Medium</title>
            <link>https://medium.com/@elijahechekwu?source=rss-ee32146b770a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:51:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elijahechekwu/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[Panic in Go]]></title>
            <link>https://medium.com/@elijahechekwu/panic-in-go-0e37fbd018ae?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e37fbd018ae</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 08:37:02 GMT</pubDate>
            <atom:updated>2025-08-11T08:37:02.110Z</atom:updated>
            <content:encoded><![CDATA[<p>Go Panic Explained: From crash to Recovery</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*RbIUua4ckuC4mlPANXP9ug.png" /><figcaption>panic in Go</figcaption></figure><h4>Exceptions</h4><p>In programming languages, an exception is an event that occurs during the execution of a program, disrupting the normal flow of instructions. It signifies an unexpected or exceptional condition that the program encounters and cannot be handles through it regular logic.</p><p>When an exception occurs, the normal sequential execution of the program is interrupted and if not handled early might cause the program to crash.</p><p>In many programming languages, when an exception occurs, an “exception object” is created. This object typically contains information about the error, such as it type, descriptive message, and the state of the program at the time of the error (e.g, a stack trace)</p><p>In JavaScript, The throw statement generates an exception that penetrates the call stack, it begins by stopping the execution of the current function, and if not caught and handled (In a catch block) , it becomes an “Unhandled exception” . It propagates and when it reaches the global execution context (i.e the top level of your JavaScript environment) it causes the program to stop and terminate.</p><h4>Stack Unwinding</h4><p>Stack unwinding is a process associated with exception handling. It is the process of removing function call frames from the function call stack during runtime. It happens when an exception/ error (In the case of Go panic or JavaScript throw exception) occurs.</p><p>As the runtime unwind the stack, (and if there is no handler for the exception) moving from one function to the previous one, it calls the destruction of all automatic (local) objects that were constructed within those frames. i.e., ensuring proper resource cleanup (releasing memory, closing file-handlers) and preventing resource leaks. <br><em>Destructors are called in the reverse order of object construction</em></p><ul><li>The runtime pops (remove) stack frame one by one until it finds somewhere to handle the error. if the entire stack is unwound without finding a suitable handler, the program terminates.</li><li>While unwinding: (examples)<br>- JavaScript runtime: Runs any finally block in each frame before popping it.<br>- Go’s runtime: Runs any deferred function in each frame before popping it.</li></ul><pre>// Example - JS<br><br>function A() {<br>  try {<br>    B()<br>  } finally {<br>    console.log(&quot;A Done&quot;);<br>  }<br>}<br><br>function B() {<br>  try {<br>    throw new Error(&quot;Unhandled Error in B&quot;)<br>  } finally {<br>    console.log(&quot;B Done&quot;);<br>  }<br><br>A();<br><br>// OUTPUT - running all finally block, while unwinding the stack<br>B Done<br>A Done<br>Uncaught Error: Unhandled Error in B</pre><h3>Panic in Go</h3><p>In Go, panic is a built-in mechanism that interrupts the normal execution of a program (just like throw, but built-in ). It indicates that the program has reached an unrecoverable state i.e it cannot continue in any meaningful way.</p><ul><li>Panic is not like returning an error, it’s not something that can be automatically caught like exceptions in JS/ Python (i.e using the throw statement to indicate an error that can be caught and handled in a catch block).</li><li>Panic is a runtime event that stops normal program execution</li></ul><h4>Causes of panic</h4><ul><li>Explicitly calling the panic function ( panic ( ) ):<br>This is intentionally done to trigger a panic (causing the program to stop) and passing an arbitrary message (often an error message) to be printed.</li><li>Implicitly by runtime errors: The go runtime can trigger panic in situations like,<br>- Nil pointer dereference<br>- Out-of-bound array or slices access<br>- Sending to a closed channel</li></ul><h4>Deferred functions</h4><p>A function defined using the defer keyword guarantees it execution just before the surrounding function returns or panics</p><pre>func doSomething() {<br>  defer func() {<br>    fmt.Println(&quot;I would always be printed before doSometing returns&quot;)<br>  }()<br><br>  fmt.Println(&quot;The Beginning of doSomething&quot;)<br>}<br><br>doSomething()<br><br>// OUTPUT<br>The beginning of doSomething<br>I would always be printed before doSomething returns</pre><h4>Recover</h4><p>Recover is a builtin-function used to regain control over a panicking go routine and prevents the program from crashing. Recover is only effective inside deferred functions. This ensures that if there is a panic</p><pre>// Example without recover<br>package main<br><br>import &quot;fmt&quot;<br><br>func doSomethingThatMightPanic () {<br>  panic(&quot;Hey, panicking rignt now in doSomethingThatMightPanic&quot;)<br>}<br><br>func main () {<br>  fmt.Println(&quot;Beginning of main function&quot;)<br>  doSomethingThatMightPanic()<br>  fmt.Println(&quot;End of main function&quot;)<br>}<br><br>// Output<br>Beginning of main function<br>panic: Hey, panicking rignt now in doSomethingThatMightPanic<br><br>goroutine 1 [running]:<br>main.doSomethingThatMightPanic(...)<br>        /home/k5/dev/Go learning/test/main.go:6<br>main.main()<br>        /home/k5/dev/Go learning/test/main.go:11 +0x5a<br>exit status 2<br></pre><h4>Behaviour of Panic</h4><p>When a panic occurs, the following happens</p><ol><li>The current function stops running immediately</li><li>Go starts unwinding the stack</li></ol><p>(a) If there is no recover() call in a deferred function during the unwind:</p><ul><li>The Go runtime keeps popping stack frames (beginning with the current function and moving to the caller function)</li><li>Running all defer statement, it finds in each stack frame.</li><li>When the stack is empty ( it reaches the top-level main go routine), the runtime prints the panic message + stack traces and terminates the program.</li></ul><p>(b) if there is recover ()call in a deferred function (i.e to handle panics) , it stops the panic, returns the caller and continue the program execution.</p><pre>// Example -With defer + recover <br><br>package main<br><br>import &quot;fmt&quot;<br><br>func doSomethingThatMightPanicButWillRecover () {<br>  defer func ()  {<br> if r := recover(); r !=nil{<br>  fmt.Println(&quot;Recovered from: &quot;, r)<br> }<br>  }()<br>  panic(&quot;Hey, panicking rignt now in doSomethingThatMightPanicButWillRecover&quot;)<br>}<br><br>func main () {<br>  fmt.Println(&quot;Beginning of main function&quot;)<br>  doSomethingThatMightPanicButWillRecover()<br>  fmt.Println(&quot;Continuing execution of main function&quot;)<br>  fmt.Println(&quot;End of main function&quot;)<br>}<br><br>// OUTPUT<br>Beginning of main function<br>Recovered from:  Hey, panicking rignt now in doSomethingThatMightPanicButWillRecover<br>Continuing execution of main function<br>End of main function</pre><h4>Key Takeaways</h4><ul><li>Panic can be intentionally called for truly unrecoverable errors. I.e, Stop a web server from running if database fails to connect.</li><li>Use defer + recover in controlled boundaries to prevent your application from crashing unexpectedly.</li></ul><p><em>Know when to crash, Know when to recover — and your go code will survive anything.</em></p><p>Thanks for reading. Elijah :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e37fbd018ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matching Identity Records with the Dice Coefficient: A Practical Implementation]]></title>
            <link>https://medium.com/@elijahechekwu/matching-identity-records-with-the-dice-coefficient-a-practical-implementation-f9bf2e0c4ac3?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9bf2e0c4ac3</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[identity-management]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 06:26:23 GMT</pubDate>
            <atom:updated>2025-07-23T06:26:23.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*mZYec9rDwScNcwNHee205w.png" /><figcaption>Dice coefficient</figcaption></figure><p>A Few days ago, I started working on a project that required verifying a user’s identity information within my application against data from various Identity platform (I.e NIMC, BVN etc).</p><p>In many applications where user identity verification is essential — especially before allowing access to sensitive and restricted features — this process becomes crucial. Typically, the information a user provides during signup (such as their full name (first and last) and date of birth) is matched against records from government agencies to confirm their identity.</p><p>At first glance, this seems like a straightforward task: simply compare the user’s first and last name with those retrieved from official identity platforms. Sounds easy, right?</p><h3>Painful Realizations</h3><p>One of the first challenges I ran into was <strong>name inconsistency</strong> across platforms. A user’s name might not appear exactly the same in every system, which makes direct string comparison unreliable.</p><h4>🧩 Sample 1 — Inconsistency Due to Swapped Order</h4><p><strong>User A — App Data</strong></p><ul><li>First Name: <strong>John</strong></li><li>Last Name: <strong>Obinna</strong></li></ul><p><strong>User A — NIN Record</strong></p><ul><li>First Name: <strong>Obinna</strong></li><li>Last Name: <strong>John</strong></li></ul><p>This kind of mismatch happens when platforms differ in how they store or label name components.</p><h4>📝 Sample 2 — Inconsistency Due to Typos or Variants</h4><p><strong>User B — App Data</strong></p><ul><li>First Name: <strong>Oladimeji</strong></li><li>Last Name: <strong>Olalekan</strong></li></ul><p><strong>User B — BVN Record</strong></p><ul><li>First Name: <strong>Oladimejia</strong></li><li>Last Name: <strong>Olalekan</strong></li></ul><p>Here, a minor spelling variation (“<strong>Oladimeji</strong>” vs “<strong>Oladimejia</strong>”) can break a naïve equality check, even though it’s clearly the same person.</p><h4>🧩 Sample 3 — Inconsistency Due to Missing Middle Name</h4><p><strong>User C — App Data</strong></p><ul><li>First Name: <strong>Aisha</strong></li><li>Last Name: <strong>Mohammed</strong></li></ul><p><strong>User C — NIMC Record</strong></p><ul><li>First Name: <strong>Aisha Mohammed</strong></li><li>Last Name: <em>(empty)</em></li></ul><p>Some government systems store both first and last names as a single string in the “first name” field, or omit the last name entirely (<em>Although, this is rare</em>). This makes field-to-field mapping unreliable.</p><h4>🧩 Sample 4 — Inconsistency Due to Abbreviations</h4><p><strong>User D — App Data</strong></p><ul><li>First Name: <strong>Chukwudi</strong></li><li>Last Name: <strong>Okafor</strong></li></ul><p><strong>User D — BVN Record</strong></p><ul><li>First Name: <strong>C.</strong></li><li>Last Name: <strong>Okafor</strong></li></ul><p>Here, a user may have registered one identity using a full name and another using initials.</p><h3>🔻 The Problem</h3><p>As seen in the examples above, direct string comparison fails in all cases. Even matching individual fields like first name and last name separately doesn’t help. Relying on exact matches assumes the data is consistent across platforms — which it rarely is.</p><p>This approach is brittle and not robust enough to handle the real-world nuances of identity verification across different systems. Typos, name ordering, abbreviations, missing fields, and formatting differences make direct comparisons unreliable and prone to false negatives.</p><h3>🔍 How I Approached the Problem</h3><p>After Identifying that exact string comparisons wouldn’t cut it, I needed a more flexible way to compare user names — one that tolerates minor differences while still detecting strong similarity. I reached out to a friend and got a head start on a package in npm, (string similarity). Before this, I had considered a few options:</p><ul><li><strong>Manual rules</strong>: Strip spaces, lowercase everything, reorder fields, etc.<br> ➤ This helped, but only slightly. It still failed on typos or partial matches.</li><li><strong>Levenshtein Distance</strong>: Measures the number of edits between two strings.<br> ➤ It’s effective, but not ideal for short strings like names, where even a small typo leads to a high score.</li></ul><p>Eventually, I found a sweet spot with the <strong>Dice Coefficient</strong> — a string similarity algorithm that compares how many bigrams (2-letter pairs) two strings have in common. It’s lightweight, performant, and works well for fuzzy matching where names are slightly inconsistent.</p><p>So I decided to implement the Dice Coefficient to measure similarity between the user’s provided name and the one from an identity provider. If the similarity score passes a certain threshold (e.g. 0.85), I treat it as a match.</p><h3>What is Dice Coefficient</h3><p>The Dice Coefficient (also known as the Sørensen–Dice index) is a statistical metric used to measure the similarity between two sets or sequences. It’s commonly employed in image analysis, natural language processing, and other fields to assess the degree of overlap between two sets of data.</p><p>In my use case, it’s a simple string similarity algorithm used to compare two sequences (strings — sequence of characters) based on how many common <strong>bigrams</strong> they share.</p><p>A <strong>bigram</strong> is just a pair of consecutive letters. For example, the name &quot;John&quot; has these bigrams:<br> → &quot;Jo&quot;, &quot;oh&quot;, &quot;hn&quot;</p><p>The Dice coefficient can be found by the formula below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*Ongs3Slhjc6PihFsGRSnyA.png" /><figcaption>Dice coefficient formula</figcaption></figure><p>Where: Dice ( X, Y)</p><ul><li>X and Y are the sets of bigrams from each string.</li><li>|X ∩ Y| is the number of matching bigrams.</li><li>|X| + |Y| is the total number of bigrams in both strings.</li></ul><p>It returns a score between <strong>0</strong> (no similarity) and <strong>1</strong> (perfect match).</p><h4>Example: Comparing Names</h4><p>Let’s compare:</p><ul><li>&quot;Obinna&quot; → Bigrams: [&quot;Ob&quot;, &quot;bi&quot;, &quot;in&quot;, &quot;nn&quot;, &quot;na&quot;]</li><li>&quot;Obina&quot; → Bigrams: [&quot;Ob&quot;, &quot;bi&quot;, &quot;in&quot;, &quot;na&quot;]</li></ul><p>They share 4 bigrams.</p><pre>Dice = (2 × 4) / (5 + 4) = 8 / 9 ≈ 0.89</pre><p>Even though the names are not identical, a Dice score of <strong>0.89</strong> indicates high similarity — good enough for fuzzy identity matching.</p><h4>Trade Offs</h4><p>In my use case, I wanted the verification of users to be flexible enough to accommodate the inconsistencies in their name across verification, and also to ensure strictness, This algorithm is combined with other bio-metric data such as date of birth and unique Government ID number to give a robust verification.</p><p>Some of the downside to this approach would be:</p><ul><li><strong>Needs Tuning</strong>: Choosing the right similarity threshold (e.g. ≥ 0.85) is critical — too strict misses matches, too loose admits incorrect ones.</li><li><strong>False Positives</strong> : Short names like &quot;Ali&quot; vs &quot;Aliu&quot; may produce high similarity despite being different individuals.</li><li><strong>No Semantic Understanding</strong> : &quot;Jon&quot; vs &quot;Jonathan&quot; may score low despite being the same person. Doesn’t account for common nicknames, abbreviations, or cultural name patterns.</li><li>Treats all mismatches equally; doesn’t distinguish between a typo in a name and a completely different person.</li></ul><p>Although, most of this can be worked around by combining multiple validation like ID number, Date of Birth etc.</p><p><em>I experimented with a few thresholds and settled on 0.85 as a good trade-off between false positives and false negatives.</em></p><p>Here is a snippet of the code</p><pre>package verification<br><br>import &quot;strings&quot;<br><br><br>func NormalizeName(name string) string {<br> str := strings.Fields(name)<br> return strings.ToLower(strings.TrimSpace(strings.Join(str, &quot; &quot;)))<br>}<br><br>func generateBigrams(str string) []string {<br><br> str = strings.ReplaceAll(str, &quot; &quot;, &quot;&quot;)<br> var bigrams []string<br><br> for i := 0; i &lt; len(str)-1; i++ {<br>  bigrams = append(bigrams, str[i:i+2])<br> }<br> return bigrams<br>}<br><br>func diceCoefficient (str1, str2 string) float64 {<br> str1Bigram := generateBigrams(str1)<br> str2Bigram := generateBigrams(str2)<br><br> if len(str1Bigram) == 0 || len(str2Bigram) == 0 {<br>  return 0<br> }<br><br> intersection := 0<br><br> matches := make([]bool, len(str2Bigram))<br><br> for _, s1bigram := range(str1Bigram) {<br>  for index, s2bigram := range(str2Bigram) {<br>   if !matches[index] &amp;&amp; s1bigram == s2bigram {<br>    intersection ++<br>    matches[index] = true <br>    break<br>   }<br>  }<br> }<br> return  float64( 2 * intersection) / float64( len(str1Bigram) + len(str2Bigram) )<br>}<br><br>func GetVerificationScore(bvnName, ninName, accName string) VerificationResult {<br> scoreBVN := diceCoefficient(bvnName, accName)<br> scoreNIN := diceCoefficient(ninName, accName)<br><br> finalScore := (scoreBVN + scoreNIN) / 2<br><br> return VerificationResult{<br>  ScoreBVN: scoreBVN,<br>  ScoreNIN: scoreNIN,<br>  FinalScore: finalScore,<br>  Matched: finalScore &gt;= 0.85,<br> }<br>}</pre><p>I built a go module that implements dice coefficient. Check it out <a href="https://github.com/Elijah57/dice-coeff">Here</a></p><p>Thanks for reading. Cheers !!</p><p><em>Remember code is craft, Keep refining and until next time. </em><strong><em>Code</em></strong><em> . </em><strong><em>Test</em></strong><em> . </em><strong><em>Reflect</em></strong><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9bf2e0c4ac3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ I Accidentally Leaked My Portainer API Key… Without Realizing It]]></title>
            <link>https://medium.com/@elijahechekwu/i-accidentally-leaked-my-portainer-api-key-without-realizing-it-e159cf099984?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e159cf099984</guid>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Mon, 26 May 2025 18:41:17 GMT</pubDate>
            <atom:updated>2025-05-26T18:41:17.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJfSLmHEkGrkV7QUr8ivWw.png" /><figcaption>API KEY Leaked</figcaption></figure><p>So here’s something that made my jaw drop this week: I discovered my <strong>Portainer admin API key</strong> was being sent along with requests to a totally different app I was building — all thanks to the way browsers handle cookies.</p><blockquote>Browsers attach <strong>cookies to requests based on domain</strong>, not port. This is per the <a href="https://datatracker.ietf.org/doc/html/rfc6265">HTTP cookie spec (RFC 6265)</a>, and it’s consistent across all modern browsers.</blockquote><p>And get this: it wasn’t a bug. It was <strong>completely expected behavior</strong>. Just… nobody talks about it enough (more like, I’m just discovering this).</p><p>Let me walk you through what happened — and why <strong>you should 100% double-check how your apps are deployed if you’re using the same domain for everything.</strong></p><h3>🔍 The Setup: Just Another Dev Stack</h3><p>I was working on a Go web app on my local machine, running at http://localhost:8080. At the same time, I had <a href="https://www.portainer.io/">Portainer</a> (my Docker UI) running at http://localhost:9000 — nothing fancy.</p><p>Pretty common, right? Backend on 8080, admin tools on 9000. Everything under localhost.</p><p>I log into Portainer, do my thing. Then, I head back to my Go app and hit a /health route just to test my server.</p><p>All good — status 200, everything fine.</p><p>But I decided to inspect the request in Chrome’s <strong>Network tab</strong>, and… boom 💥</p><p>There it was. In the Request Headers:</p><pre>Cookie: portainer_api_key=eyJhbGciOiJI...</pre><p>Wait. <strong>WHAT?</strong></p><p>Why the hell is my Portainer JWT showing up in requests to my Go app?</p><h3>🍪 The Cookie Problem You Didn’t Know You Had</h3><p>Here’s what I learned the hard way: <strong>cookies are scoped by domain, not by port</strong>.</p><p>So if Portainer sets a cookie like this:</p><pre>Set-Cookie: portainer_api_key=...; Domain=localhost; Path=/</pre><p>Then <strong>every request to anything on </strong><strong>localhost will include that cookie</strong>, whether it’s port 8080, 3000, 9000, whatever.</p><p>That means:</p><ul><li>If you visit your own landing page at localhost:3000, it gets the cookie.</li><li>If your backend logs request headers, it sees the cookie.</li><li>If your public API reflects headers or cookies (bad idea), <strong>boom</strong> — it just leaked your Portainer admin key.</li></ul><p>It’s not a bug, it’s just how HTTP cookies work. And most devs (me included) just don’t think about this.</p><h3>⚠️ Why This Is a Real Security Risk</h3><p>Let’s say you’re deploying like this in production:</p><ul><li>https://example.com — public site</li><li>https://example.com:9000 — Portainer</li><li>https://example.com/api — internal API</li></ul><p>If Portainer sets a cookie on .example.com, <strong>all those services will see it</strong>.</p><p>Imagine this:</p><ul><li>Your marketing page has a contact form that sends a POST to /api/contact</li><li>Your backend logs all headers for debugging</li><li>Now your logs contain the Portainer JWT</li></ul><p>Or worse — some malicious JavaScript could steal the cookie and exfiltrate it.</p><p>Suddenly, someone has full access to your Docker containers. From a damn contact form.</p><h3>🛡️ How To Avoid This Mess</h3><p>Here’s what I should’ve done (and what you should do too):</p><h3>✅ 1. Use Subdomains, Not Just Ports</h3><p>Instead of:</p><ul><li>example.com:9000</li></ul><p>Use:</p><ul><li>portainer.example.com</li></ul><p>That way, cookies from Portainer can be scoped to just portainer.example.com, and the browser won’t send them to your other services.</p><h3>✅ 2. Set Cookies With Proper Scope</h3><p>Make sure your cookies look like this:</p><pre>Set-Cookie: portainer_api_key=...; Domain=portainer.example.com; Path=/; HttpOnly; Secure; SameSite=Strict</pre><ul><li>HttpOnly: stops JavaScript from accessing it</li><li>Secure: only send over HTTPS</li><li>SameSite=Strict: don’t send on cross-site requests</li></ul><h3>✅ 3. Use a Reverse Proxy</h3><p>With something like <strong>Nginx</strong>, <strong>Caddy</strong>, or <strong>Traefik</strong>, you can easily route portainer.example.com and api.example.com to different internal services without needing different ports.</p><h3>✅ 4. Don’t Log Cookies</h3><p>Seriously. Sanitize your logs. Never log headers or cookies directly unless you’re debugging something very specific — and even then, be careful.</p><h3>💬 Final Thoughts</h3><p>I wouldn’t have caught this if I hadn’t randomly opened the Network tab out of curiosity. And that’s what scares me.</p><p>This kind of leak is subtle. Easy to miss. But if someone had gotten that API key, they’d have root access to all my containers.</p><p>So if you’re deploying apps and tools on the same domain, <strong>double-check your cookie scope</strong>. Make sure your admin panels live on real subdomains. And inspect your own network traffic — just to be safe.</p><p>Actually, this experience helped me understand the whole cross-site scripting attack.</p><p>Stay paranoid. It pays off. 😂 .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e159cf099984" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anatomy of an HTTP Request]]></title>
            <link>https://medium.com/@elijahechekwu/anatomy-of-an-http-request-cb5ed9508b5f?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb5ed9508b5f</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 14:12:06 GMT</pubDate>
            <atom:updated>2026-04-24T08:29:32.560Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explained for Backend Devs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*VX763Wl3Kns2VROZCc_5Iw.png" /><figcaption>Anatomy of an HTTP Request</figcaption></figure><p>As a backend developer, you deal with HTTP requests every day — but how often do you break down what exactly is happening under the hood? Whether you’re designing APIs, handling middleware, or debugging client-server communication, understanding the core structure of an HTTP request is fundamental.</p><p>In this article, we’ll dissect the anatomy of an HTTP request and explain each component from a backend developer’s lens.</p><h3>What is an HTTP Request?</h3><p>HTTP (Hyper Text Transfer Protocol) is the foundation of data communication on the web. It’s a protocol that allows <strong><em>web clients</em></strong> (like your browser) and <strong><em>servers</em></strong> to exchange information. Essentially, HTTP defines how data, like web pages, images, and videos, are transferred over the internet.</p><p>HTTP is stateless (i.e., each request is treated independently, and the server doesn’t retain information about past interactions) and follows a request-response model (i.e., the client sends a request to a web server, and the server responds with the requested content.)</p><p>An<strong><em> </em>HTTP request</strong> is a message sent by a client (typically a browser or mobile app) to a server, asking for a specific resource or action.</p><p>When you hit an endpoint like GET /api/users, your client sends an HTTP request to the server—and that request contains multiple layers of important information.</p><h3>🏋️️ The 4 Main Parts of an HTTP Request</h3><h4>1. Request Line</h4><p>This is the first line of the HTTP request, it is used to initialize an action on the server. A request line indicate what kind of method, request target and version of HTTP protocol the client is using. It includes:</p><ul><li><strong>Method</strong>: e.g. GET, POST, PUT, DELETE</li><li><strong>Request Target</strong>: the path or endpoint (e.g. /api/users)</li><li><strong>HTTP Version</strong>: usually HTTP/1.1 or HTTP/2</li></ul><p><strong>Example:</strong></p><pre>GET /api/users HTTP/1.1</pre><h4>2. Headers</h4><p>Headers carry metadata about the request, this includes data about the host, client’s user agent, language preferences and more. The server leverages this information to identify the browser and OS version of the client. HTTP request headers are case-insensitive, followed by a colon (:) and a value.</p><p>Common request headers include:</p><ul><li>Host: The domain name of the server</li><li>Content-Type: Type of the request body (e.g. application/json)</li><li>Authorization: Token or credentials</li><li>User-Agent: Info about the client software and OS</li><li>Accept: This give Info about the kind of content the client can understand.</li><li>Connection : This suggest the connection between client and server should be kept open for subsequent requests.</li><li>Accept-Language: Preferred language of the client</li></ul><p><strong>Example:</strong></p><pre>Host: api.example.com<br>User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0<br>Content-Type: application/json<br>Connection: keep-alive<br>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8<br>Accept-Language: en-US,en;q=0.5<br>Authorization: Bearer &lt;token&gt;</pre><h4>3. Body (Optional)</h4><p>The body contains data sent to the server, usually with POST, PUT, or PATCH requests. It&#39;s often JSON, form data, or raw text. The format of the data in the body is specified by the Content-Type header in the request. The server needs this information to correctly understand and process the data.</p><p><strong>Example:</strong></p><pre>{<br>  &quot;name&quot;: &quot;Elijah&quot;,<br>  &quot;email&quot;: &quot;elijah@example.com&quot;<br>}<br><br>// in the header<br><br>Content-Type: aapplication/json</pre><h4>4. Query Parameters (Optional)</h4><p>These are key-value pairs appended to the URL to filter or sort data.</p><p>Request Query Parameter are made up of one or more <strong>parameter-value pairs</strong>, separated by an equals sign (=). If you have multiple parameters, they&#39;re usually separated by an ampersand (&amp;).</p><p>For example:</p><pre>GET /api/products/search?q=coffee+beans&amp;sort=price-low</pre><p>See that part after the ?? That&#39;s the request query:</p><ul><li><strong>q=coffee+beans</strong>: Here, q is the parameter (often standing for &quot;query&quot;), and coffee+beans is the value. The browser is telling the server to search for &quot;coffee beans&quot;. Notice the + sign? That&#39;s often used to represent a space in URLs.</li><li><strong>&amp;sort=price-low</strong>: The &amp; separates this from the previous parameter. sort is the parameter, and price-low is the value. This tells the server to sort the search results by price, from lowest to highest.</li></ul><h3>🚀 Why It Matters for Backend Developers</h3><p>As a backend developer, you need to understand the anatomy of an HTTP Request to:</p><ul><li>Parse incoming requests properly</li><li>Validate and sanitize inputs</li><li>Extract headers, body, and query params</li><li>Authenticate users via tokens in headers</li></ul><p>Also, understanding the request structure helps you:</p><ul><li>Write better middleware</li><li>Improve API performance and security</li><li>Debug issues faster</li></ul><h3>🔧 Tools to Inspect HTTP Requests</h3><ul><li><strong>Postman</strong> / <strong>Insomnia</strong>: GUI tools for crafting and sending HTTP requests</li><li><strong>Browser Dev Tools</strong>: Check the ‘Network’ tab</li><li><strong>cURL</strong>: CLI tool for HTTP requests</li><li><strong>Logs &amp; Middleware</strong>: Log the raw request object in Node.js (req.method, req.headers, req.body)</li></ul><h3>Final Thoughts</h3><p>An HTTP request may look simple, but it’s packed with detail. As a backend developer, having a deep understanding of how they work gives you a clear edge when it comes to writing robust, secure, and maintainable APIs.</p><p><strong><em>TL;DR</em></strong><em>: Know your methods, headers, bodies, and params. It’s not just protocol — it’s power.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb5ed9508b5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Input Validation (NodeJs + ExpressJs+ Zod)]]></title>
            <link>https://medium.com/@elijahechekwu/api-input-validation-nodejs-expressjs-zod-9616f7f219e3?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9616f7f219e3</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[zod]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 13:40:21 GMT</pubDate>
            <atom:updated>2025-04-10T13:40:21.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building Robust APIs: A Deep Dive into Input Validation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*Zw6d_SUzxZcOrvg7PYq9GQ.png" /><figcaption>API input validation</figcaption></figure><p>API Input Validation is a crucial step in API Design. API Input validation is the process of verifying that the client input meets predefined criteria before it’s process by the server/ API, ensuring data integrity and preventing errors or security vulnerabilities.</p><p>The importance of API input validation cannot be overstated. It is te first line of defense in ensuring that only valid, well-constructed and safe data enters your system. Without input validation, APIs would be vulnerable to attacks like SQL injection, cross-site scripting (XSS) and other exploits that can compromise both the backend and data. Additionally, invalid or improperly formatted data can cause unexpected behavior, crashes, or corrupt data that might severely affect the user experience and system integrity.</p><h3>Why it is important?</h3><h4><strong>Ensuring Business Logic and preventing data corruption</strong></h4><p>Input validation isn’t just about blocking malicious users or preventing broken responses — it’s also essential for protecting your<strong> business logic</strong> and the rules that govern your application’s core functionality.</p><p><strong>For example</strong>, consider an API endpoint designed to allow users <strong>within a specific age range</strong> (say, 18–35) to access certain features or benefits — like a youth discount, early-career resources, or age-targeted content.</p><p>Without proper validation:</p><ul><li>A user might submit their age as &quot;eighteen&quot;, null, or even -5.</li><li>Worse, a user might intentionally bypass client-side validation and send 150 as their age to game the system.</li></ul><p>If the API doesn’t validate and strictly enforce the expected <strong>numeric range</strong>, the backend logic might accept and process these values, resulting in:</p><ul><li><strong>Unauthorized access</strong> to benefits meant for a targeted user segment.</li><li><strong>Broken analytics</strong>, as invalid ages pollute data used for reporting and personalization.</li><li><strong>Reputational and compliance risks</strong>, especially if services are age-restricted due to legal requirements.</li></ul><h4>Data Integrity</h4><p>Without proper input validation, API endpoints that expect specific fields — such as an email address — may end up receiving invalid or malformed data. For example, a user might enter an email address with incorrect formatting, like user@domain , missing the .com part or containing invalid characters. If this input isn’t validated, it can be stored directly in the database, which might affect <strong>database integrity</strong>.</p><h4><strong>Security Vulnerabilities</strong></h4><p>Attackers can exploit APIs that don’t validate input to inject malicious data or code. This includes:</p><ul><li><strong>SQL Injection</strong>: Malicious SQL queries can be injected into input fields and executed on the database, potentially revealing sensitive data or corrupting the database.</li><li><strong>Cross-Site Scripting (XSS)</strong>: Invalid or unsanitized input can allow attackers to inject scripts that execute in the context of other users’ browsers, leading to stolen session data or unauthorized actions.</li></ul><h4><strong>System Crashes</strong></h4><p>Invalid input can cause unhandled exceptions in the backend or front-end applications, leading to system crashes or unpredictable behavior.</p><h4><strong>Poor User Experience</strong></h4><p>Failure to validate input may result in faulty responses or unhelpful error messages, making it difficult for users to understand why their requests failed or how to fix them.</p><h3>Common Input Validation Strategies</h3><p>The following validation strategies are common to server-side Input Validation. These strategies would be implemented using zod . <strong>Zod</strong> is a powerful Typescript-first schema declaration and validation library that makes input validation easy and type-safe.</p><p>Install Zod with:</p><pre>npm install zod<br></pre><p>Then in your Node.js/Express project, import it like this:</p><pre>import { z } from &quot;zod&quot;;</pre><ol><li><strong>Length, Type, Format, and Range Validation</strong>:</li></ol><ul><li><strong>Length Validation</strong>: This ensures the input meets the expected length limits (e.g., passwords should have a minimum and maximum length).</li><li><strong>Type Validation</strong>: This ensures the input is of the correct data type (e.g., an email should be a string, an age should be an integer).</li><li><strong>Format Validation</strong>: Validating if the input conforms to a specific pattern (e.g., validating phone numbers or email addresses using regular expressions — phone number must start with a country code and email must end with a common TLD top level domain )</li><li><strong>Range Validation</strong>: Ensuring numeric input falls within an acceptable range (e.g., age between 18 and 100).</li></ul><p>For example, let say we have an API endpoint POST /register that expects user details like name , email and age .</p><pre>const registerSchema = z.object({<br>  name: z.string().min(2, &quot;Name must be at least 2 characters&quot;),<br>  email: z.string().email(&quot;Invalid email address&quot;),<br>  age: z.number().int().gte(18, &quot;You must be at least 18&quot;).lte(35, &quot;You must be 35 or younger&quot;),<br>});<br><br>.min() // validate length<br>.string() //validate type<br>.email() // validate email format<br>.gte() and .lte() // validate range</pre><p><strong>2. Regular Expressions</strong>: Regular expressions (regex) are commonly used to validate structured data, like:</p><ul><li><strong>Email addresses</strong> (e.g., matching someone@example.com).</li><li><strong>Phone numbers</strong> (e.g., validating the format for international or local numbers).</li><li><strong>URLs</strong> (e.g., ensuring a valid URL is provided).</li></ul><pre>const phoneSchema = z.string().regex(/^\+?[1-9]\d{1,14}$/, {<br>  message: &quot;Invalid phone number format (E.164)&quot;,<br>});</pre><p><strong>3. Enumeration Validation</strong>: This involves checking that the input value matches one of a set of predefined, acceptable values (e.g., validating a user’s role from a list of allowed roles such as admin, user, and guest).</p><p>Suppose your API expects a role field that must be one of a few predefined options:</p><pre>const roleSchema = z.enum([&quot;admin&quot;, &quot;user&quot;, &quot;guest&quot;]);<br><br></pre><h3>Best Practices for API Input Validation</h3><p>To ensure robust and secure API Input validation, follow these best practices:</p><ol><li><strong>Reject Invalid Input Early in the Request Flow</strong>: Always validate input as early as possible in the request processing flow. Ideally, input should be checked before it reaches sensitive parts of the system (e.g., database operations or business logic). This could be achieved using validation middlewares and logic using libraries like zod to setup validation logic.</li></ol><p>In schemas/signup.ts</p><pre>import {z} from &quot;zod&quot;<br><br>export const signupSchema = z.object({<br>    firstname: z.string(),<br>    lastname: z.string(),<br>    middlename: z.string().optional(),<br>    phoneno: z.string().regex(/^\d{10,15}$/, &quot;Invalid phone number&quot;).min(10).max(15),<br>    email: z.string().email()<br>})</pre><p>In middlewares/validate.ts</p><pre>import { Request, Response, NextFunction } from &#39;express&#39;;<br>import { z, ZodError, ZodTypeAny } from &#39;zod&#39;;<br>import { ServerError } from &#39;./error&#39;;<br><br><br><br>export const validateInputData = (schema: z.ZodTypeAny)=&gt;{<br>    return (req: Request, res: Response, next: NextFunction)=&gt;{<br>        try{<br>            schema.parse(req.body);<br>            next();<br>        } catch(err){<br>            if (err instanceof ZodError){<br>                const errorMsg = err.errors.map((issue)=&gt; ({<br>                    message: `${issue.path.join(&quot;.&quot;)} is ${issue.message}`<br>                }))<br>                res.status(400).json({status: false, error: &quot;Invalid data&quot;, details: errorMsg})<br>            } else {<br>                throw new ServerError(&quot;Internal Server Error&quot;)<br>            }<br><br>        }<br>    }<br>}</pre><p>Including, validation Middleware in API routes router.ts</p><pre>import { Router } from &quot;express&quot;;<br>import { validateInputData } from &quot;../middlewares/validate&quot;;<br>import { signupSchema } from &quot;../schemas/signup&quot;;<br>import { signup } from &quot;../controllers/auth&quot;;<br><br>export const authRouter = Router()<br><br><br>authRouter.post(&quot;/signup&quot;, validateInputData(signupSchema), signup),<br><br>// early validation  before the sigup middleware<br></pre><p><strong>2. Validate Both Client-Side and Server-Side</strong>: Client-side validation can improve user experience by providing instant feedback, but it should never be relied upon as the sole method of validation. Server-side validation is essential because client-side validation can be bypassed. Always perform server-side validation to ensure the data is correctly formatted and safe.</p><p><strong>3. Return Meaningful Error Messages</strong>: When rejecting invalid input, provide users with clear, helpful error messages that explain what was wrong with their input and how they can fix it. For example, instead of a vague “400 Bad Request,” specify “The email address provided is not valid.”</p><p><strong>4. Handle Unexpected Inputs Gracefully</strong>: In cases where input doesn’t conform to the expected pattern, return proper HTTP status codes (e.g., 400 Bad Request) and detailed error messages to guide users on how to correct their input.</p><p><strong>5. Avoid Relying Solely on Client-Side Validation</strong>: Client-side validation can be easily bypassed or manipulated, so it should only serve as a convenience. Server-side validation should always be the final authority on whether the input is valid, as it ensures that even if the client sends malicious data, the server can reject it before further processing.</p><h4>Final Thoughts</h4><p>By integrating comprehensive input validation techniques, you can prevent many common errors and attacks that can cripple an API, while ensuring your application is both secure and user-friendly.</p><p><em>Remember, Garbage in, disaster out — Validate early, validate always . Trust nothing. Build secure APIs. Cheers!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9616f7f219e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis Caching for Backend Developers]]></title>
            <link>https://medium.com/@elijahechekwu/redis-caching-for-backend-developers-eb1cbe835665?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb1cbe835665</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 11:02:27 GMT</pubDate>
            <atom:updated>2025-04-10T19:02:40.971Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering Backend Performance with Redis Caching Techniques</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*uwJI9MoJmFz-FPeeUhxSMw.png" /><figcaption>Redis cache</figcaption></figure><p>Redis is a popular in-memory data store, best known and used for caching. Redis (Remote Dictionary Server) stores data in the RAM, enabling extremely fast read and write operations, making it ideal for caching and applications requiring low latency. It supports various data types, including strings, hashed, lists, sets, sorted sets, and streams, allowing for flexible data modelling.Redis is commonly used as a caching layer in front of traditional databases to improve application performance by reducing the time needed to fetch data from slow storage devices.</p><p>Redis offers built-in replication for high availability and different levels of on-disk persistence for data durability.</p><h3>Caching</h3><h4>What is a Cache?</h4><p>A <strong>cache</strong> is a high-speed storage layer which stores a subset of data, typically in a <em>transient</em> nature, so that future requests for that data are served up faster than is possible by accessing the data’s primary storage location.</p><p>A cache’s primary purpose is to increase data retrieval performance by reducing the need to access the underlying slower storage layer.</p><p><strong>Caching</strong> is the process of storing frequently accessed data in a high-speed storage layer (like <strong>Redis</strong>) so that future request for that data are served faster. Instead of going to the database (which might take 100ms), your application checks Redis (which might take 1 ms) — <strong>fast retrieval and low latency.</strong></p><p>In this article, the examples are implemented using Node.js and the <strong><em>ioredis </em></strong>library. To follow through with the examples, install the ioredis package</p><pre>npm install ioredis</pre><p>Connect to the redis client index.js . I’m using a redis image in this example</p><pre>import { Redis } from &quot;ioredis&quot;;<br><br>const redisUrl = &quot;redis://localhost:6379&quot;<br><br>const redisClient = new Redis(redisUrl, {maxRetriesPerRequest: null})</pre><h3>Key Terminologies in caching</h3><h4>Cache Hit:</h4><p>A <strong>cache hit</strong> occurs when the application requests some data from the<strong><em> cache</em></strong> (Redis) and the <strong><em>cache</em></strong> has it and is able to fulfill that request.</p><pre>const data = await redisClient.get(&quot;user:123&quot;);<br>if (data) {<br>  // This is a cache hit<br>}</pre><p><em>🔁 Cache hits mean your caching strategy is working effectively.</em></p><h4>Cache Miss:</h4><p>A cache miss occurs when the application requests some data from the cache but the data is <strong><em>not found in the cache.</em></strong></p><p>🚨 This triggers a fallback:</p><ul><li>Fetch the data from your main source (e.g., database).</li><li>Optionally store it in Redis for future use.</li></ul><pre>const data = await redisClient.get(&quot;user:123&quot;);<br><br>if (!data) { // This is a cache miss<br>  const dbData = await getUserFromDatabase(&quot;123&quot;);<br>  await redisClient.set(&quot;user:123&quot;, JSON.stringify(dbData));<br>}</pre><p>A high cache miss rate often indicates: <strong><em>Ineffective key design, Data not being cached properly, Cache expiry times that are too short</em></strong>.</p><h4>Cache Invalidation:</h4><p><strong>Cache invalidation</strong> is the process of removing or updating cache entries when the <strong>underlying data changes</strong>. This is to ensure that your application gets updated data and old data is not served to users.</p><p><strong>Common</strong> <strong>Invalidation</strong> <strong>strategies</strong></p><ul><li>Delete the cache entry after Database update.</li></ul><pre><br>// User update handler<br>async function updateUser(userId: string, newUserData: any) {<br>  // 1. Update the database<br>  await db.users.update({ id: userId }, newUserData);<br><br>  // 2. Invalidate cache<br>  await redisClient.del(`user:${userId}`);<br>}</pre><ul><li>Update the cache along with the DB write (write-through).</li></ul><pre>async function updateUser(userId: string, newUserData: any) {<br>  // 1. Update the DB<br>  await db.users.update({ id: userId }, newUserData);<br><br>  // 2. Update the cache immediately<br>  await redisClient.set(`user:${userId}`, JSON.stringify(newUserData), &#39;EX&#39;, 3600); </pre><ul><li>Use versioned keys (e.g., user:v2:123): This is great for avoiding stale data without needing to delete old cache keys — just bump the version when the data structure changes or invalidation logic updates.</li></ul><pre>const CACHE_VERSION = &#39;v2&#39;;<br><br>function getUserCacheKey(userId: string) {<br>  return `user:${CACHE_VERSION}:${userId}`;<br>}<br><br>async function getUser(userId: string) {<br>  const cacheKey = getUserCacheKey(userId);<br>  const cached = await redisClient.get(cacheKey);<br><br>  if (cached) {<br>    return JSON.parse(cached); // Cache hit<br>  }<br><br>  // Cache miss — get from DB and cache<br>  const user = await db.users.findOne({ id: userId });<br>  await redisClient.set(cacheKey, JSON.stringify(user), &#39;EX&#39;, 3600);<br>  return user;<br>}</pre><h4>Time to Live (TTL)</h4><p><strong>TTL</strong> is the amount of time a cache entry is allowed to live before it is automatically removed.</p><p>⏳ It’s used to prevent stale data from lingering forever and to reduce memory usage.</p><p><strong>Example</strong> <strong>in</strong> <strong>Redis</strong></p><pre>await redisClient.set(&quot;product:789&quot;, JSON.stringify(data), &quot;EX&quot;, 3600); // Expires in 1 hour<br><br>EX - Sets expiration in seconds<br>PX - sets expiration in milliseconds</pre><h4>Cold Cache &amp; Warm cache</h4><p><strong>Cold cache</strong> is when the cache is empty or has just been reset. This means all request would (cache miss) go to the DB and result in a slower response. This happens typically after deployment or Redis restart.</p><p><strong>Warm cache </strong>is when the cache is populated with data. This means most request would (cache hit) and result to a faster response.</p><h4>Cache Eviction</h4><p><em>Cache Eviction</em> refers to the process by which old, relatively unused, or excessively voluminous data can be dropped from the <em>cache</em>, allowing the <em>cache</em> to remain within the memory budget.</p><p>In Redis, Eviction is when Redis <strong>removes keys to free up memory</strong> — usually because the max memory limit has been reached.</p><p>Eviction policies include:</p><ul><li><strong>LRU (Least Recently Used)</strong>: Removes the keys that haven’t been used recently.</li><li><strong>LFU (Least Frequently Used)</strong>: Removes the least accessed keys.</li><li><strong>TTL-based</strong>: Removes keys that are close to expiring.</li><li><strong>No eviction</strong>: Errors out once memory is full (dangerous in prod).</li></ul><p>You can configure eviction policy in redis.conf:</p><pre>maxmemory-policy allkeys-lru</pre><h4>Cache penetration</h4><p>Cache penetration occurs when <strong>requests repeatedly miss</strong> the cache and the DB (e.g., asking for a non-existent user ID). i.e., When an application requests a non-existent key, it results in a cache miss (bypassing the cache), followed by a request to the storage system, which also returns an empty result, <strong>leading to potential performance issues</strong></p><p>Attackers sometimes abuse this to <strong>bypass the cache layer</strong> and <strong>strain the DB</strong>. This issue could be mitigated by the following means,</p><ul><li>Cache empty/null responses temporarily (user:000 → null)</li><li>Use input validation to block invalid IDs</li></ul><h3>Caching Strategies</h3><ol><li><strong>Cache</strong> <strong>Aside</strong> : In this strategy, the application checks the cache first, if there is a <strong>miss (cache miss), </strong>it loads the data from the database and populate the cache. It follows the diagram and explanation below</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*kLaaLP_pJtcelWEEbQ0DKg.png" /><figcaption>cache aside</figcaption></figure><ol><li>An application requests data from the backend.</li><li>The backend checks to find out if the data is available in the Redis cache.</li><li>If data is not found (a cache miss), the data is fetched from the database.</li><li>The data returned from the database is subsequently stored in Redis.</li><li>The data is then returned to the application.</li></ol><p><strong>Cache-aside (cache hit)</strong>: If the application request data and the data is available in the cache (cache it) the data is returned to the application</p><ol><li>The application request data from the backend</li><li>The backend checks to find out if the data is available in the Redis cache.</li><li>If data is found (a cache hit), the data is returned to the application.</li></ol><pre>// Cache aside pattern<br>let user = await redisClient.get(&quot;user:123&quot;);<br><br>if (!user) {<br>  user = await db.getUserById(&quot;123&quot;);<br>  await redisClient.set(&quot;user:123&quot;, JSON.stringify(user), &#39;EX&#39;, 3600);<br>}<br>return JSON.parse(user);</pre><p>2. <strong>Write Through Cache</strong>: In this strategy, Data is <strong>written to the cache AND database</strong> at the same time. This strategy ensures data consistency between database and cache.</p><pre>async function updateUserWriteThrough(userId: string, data: any) {<br>  const updated = await db.users.update({ id: userId }, data);<br><br>  // Write to cache as well<br>  await redisClient.set(`user:${userId}`, JSON.stringify(updated), &#39;EX&#39;, 3600);<br>  return updated;<br>}</pre><p>3. <strong>Read Through Cache</strong>: In this strategy, The cache is used as the primary data source. When data is requested, the application first checks the cache. If a cache hit occurs, the data is retrieved from the cache. If a cache miss occurs, the cache automatically loads the data from the underlying database and stores it.</p><p>This simplifies application logic by offloading cache management to the cache layer. The downside to this strategy is, it can introduce latency for cache misses if the cache is slow to load data from the database.</p><pre>// example.ts<br>async function getUserReadThrough(userId: string) {<br>  const key = `user:${userId}`;<br><br>  return await getOrSetCache(key, async () =&gt; {<br>    const user = await db.users.findOne({ id: userId });<br>    return user;<br>  });<br>}<br><br>async function getOrSetCache(key: string, fetchFn: () =&gt; Promise&lt;any&gt;) {<br>  const cached = await redisClient.get(key);<br>  if (cached) {<br>    console.log(&quot;⚡ Cache hit&quot;);<br>    return JSON.parse(cached);<br>  }<br><br>  console.log(&quot;📡 Cache miss - loading through&quot;);<br>  const fresh = await fetchFn();<br>  await redisClient.set(key, JSON.stringify(fresh), &#39;EX&#39;, 3600);<br>  return fresh;<br>}</pre><p>✅ <em>Useful when you want reusable cache logic across many endpoints.</em></p><p>4. <strong>Write Behind Cache</strong>: In this strategy, Data is written to the cache first and then to the database at a later time (asynchronously).</p><p>This simplifies application logic, Improving write performance by reducing write latency to the database. The downside to this strategy is, it can lead to data <strong>inconsistency</strong> if the cache fails before the data is written to the database</p><pre>// Simulate a background worker/queue flush<br>const writeBehindQueue: { key: string; data: any }[] = [];<br><br>async function updateUserWriteBehind(userId: string, data: any) {<br>  const key = `user:${userId}`;<br><br>  // Write only to cache<br>  await redisClient.set(key, JSON.stringify(data), &#39;EX&#39;, 3600);<br>  console.log(&quot;⚡ Data cached. Write to DB deferred.&quot;);<br><br>  // Push to background queue<br>  writeBehindQueue.push({ key, data });<br>}<br><br>// Background worker (simulate with interval)<br>setInterval(async () =&gt; {<br>  while (writeBehindQueue.length) {<br>    const { key, data } = writeBehindQueue.shift()!;<br>    const id = key.split(&#39;:&#39;)[1];<br>    await db.users.update({ id }, data);<br>    console.log(`📝 DB flushed for user ${id}`);<br>  }<br>}, 5000); // flush every 5 seconds</pre><p>5. <strong>Write Around Cache</strong>: In this strategy, All write operations bypass the cache and go directly to the database. Data is not stored in the cache during write operations. Reads are handled using a cache-aside or read-through approach.</p><p>This approach is beneficial for data with low access frequency or data that doesn’t benefit from caching</p><h3>Final Thoughts</h3><p>Implementing Redis caching in your backend development isn’t just a performance boost — it’s a design choice. The right strategy depends on your app’s <strong>read/write ratio</strong>, <strong>data freshness requirements</strong>, and <strong>complexity tolerance</strong>.</p><p>So, whether you’re scaling a microservice or optimizing a monolith, Redis gives you the tools for caching — but <strong>you define the strategy</strong>.</p><p><em>Until next time, try </em><strong><em>Redis</em></strong><em> because </em><strong><em>milliseconds matters</em></strong><em>!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb1cbe835665" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming In JavaScript]]></title>
            <link>https://medium.com/@elijahechekwu/object-oriented-programming-in-javascript-5ab69b6c4bbc?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ab69b6c4bbc</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 06:08:42 GMT</pubDate>
            <atom:updated>2025-04-07T06:08:42.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*HTZFaKEztSns2GqZpiR09A.png" /><figcaption>Object Oriented Programming in JavaScript</figcaption></figure><p>OOP stands for <strong>Object-Oriented Programming</strong>. It is a programming paradigm based on the concept of “objects,” which can contain both data (often referred to as “properties” or “attributes”) and code (referred to as “methods” or “behaviors”). OOP organizes software design around data rather than functions and logic, making it easier to manage, modify, and scale. It provides a modular way to write code.</p><h3>Key Concepts in OOP</h3><h4><strong>Class</strong></h4><p>A class is a blueprint for creating objects. It defines the attributes and methods each object will have, encapsulating the properties and behaviors of the objects.</p><p><strong>Example</strong>: A Car class defines the attributes of a car (color, engine, hp) and the behaviors like moveForward and moveReverse).</p><pre>class Car {<br>  constructor(color, engine, hp) {<br>    this.color = color;<br>    this.engine = engine;<br>    this.hp = hp;<br>  }<br><br>  moveForward() {<br>    console.log(&quot;Car moving forward.&quot;);<br>  }<br><br>  moveReverse() {<br>    console.log(&quot;Car moving in reverse.&quot;);<br>  }<br>}</pre><h4>Objects</h4><p>An object is an instance of a class. Each object can have different attributes.</p><pre>const benz = new Car(&quot;gold&quot;, &quot;V4&quot;, 550);<br>const honda = new Car(&quot;off-white&quot;, &quot;V8&quot;, 770);<br><br>benz.moveForward(); //Car moving forward<br>honda.moveReverse(); //Car moving in reverse</pre><h4>Encapsulation</h4><p>Encapsulation is a core principle in OOP that involves wrapping data and methods into a single class and restricting access to internal data. JavaScript doesn’t have true private fields like some languages, but it uses conventions (e.g., _privateField) or newer syntax using #. This promoting data integrity and preventing unauthorized modification</p><pre>class Car {<br>  constructor(color, engine, hp) {<br>    this.color = color;<br>    this.engine = engine;<br>    this.hp = hp;<br>  }<br><br>  moveForward() {<br>    console.log(&quot;Car moving forward.&quot;);<br>  }<br><br>  moveReverse() {<br>    console.log(&quot;Car moving in reverse.&quot;);<br>  }<br>}<br><br>const honda = new Car(&quot;gold&quot;, &quot;V6&quot;, 550);<br>console.log(honda.color, honda.engine, honda.hp);<br><br>// Unauthorized modifications<br>honda.color = &quot;red&quot;;<br>honda.engine = &quot;V8&quot;;<br>honda.hp = 200;<br><br>console.log(honda.color, honda.engine, honda.hp);</pre><h4>Example with encapsulation</h4><pre>class Car {<br>  #color;<br>  #engine;<br>  #hp;<br><br>  constructor(color, engine, hp) {<br>    this.#color = color;<br>    this.#engine = engine;<br>    this.#hp = hp;<br>  }<br><br>  moveForward() {<br>    console.log(&quot;Car moving forward.&quot;);<br>  }<br><br>  moveReverse() {<br>    console.log(&quot;Car moving in reverse.&quot;);<br>  }<br><br>  getInfo() {<br>    return {<br>      color: this.#color,<br>      engine: this.#engine,<br>      hp: this.#hp<br>    };<br>  }<br>}<br><br>const honda = new Car(&quot;gold&quot;, &quot;V6&quot;, 550);<br>console.log(honda.getInfo());<br><br>// Unauthorized modifications would throw an error<br>honda.color = &quot;red&quot;;<br>honda.engine = &quot;V8&quot;;<br>honda.hp = 200;</pre><p>The idea behind encapsulation is data hiding and preventing unauthorized access to data.</p><h4>Inheritance</h4><p>Inheritance is a core concept in OOP. Inheritance allows a class to inherit properties and methods from another class, improving code reuseability.</p><pre>class Car {<br>  constructor(color, engine, hp) {<br>    this.color = color;<br>    this.engine = engine;<br>    this.hp = hp;<br>  }<br><br>  moveForward() {<br>    console.log(&quot;Moving in the forward direction.&quot;);<br>  }<br><br>  moveReverse() {<br>    console.log(&quot;Moving in the reverse direction.&quot;);<br>  }<br>}<br><br>class MotorBike extends Car {<br>  constructor(color, engine, hp, wheels) {<br>    super(color, engine, hp);<br>    this.wheels = wheels;<br>  }<br><br>  whoAreYou() {<br>    console.log(&quot;I am a motorbike.&quot;);<br>  }<br>}<br><br>const suzuki = new MotorBike(&quot;black&quot;, &quot;V4&quot;, 650, 2);<br>console.log(suzuki.color, suzuki.engine, suzuki.hp, suzuki.wheels);<br>suzuki.moveForward();<br>suzuki.moveReverse();<br>suzuki.whoAreYou();</pre><h4>Polymorphism</h4><p>Derived from the Greek word <strong><em>poly</em></strong> (meaning many) and <strong><em>morph</em></strong> (to change form). Polymorphism is a concept that allows methods to have different implementations across different objects. It enables objects of various classes to be treated uniformly, with each object responding to the same method call in its own unique way.</p><pre>class Vehicle {<br>  moveForward() {<br>    console.log(&quot;Vehicle moving forward.&quot;);<br>  }<br><br>  moveReverse() {<br>    console.log(&quot;Vehicle moving in reverse.&quot;);<br>  }<br>}<br><br>class Car extends Vehicle {<br>  moveForward() {<br>    console.log(&quot;Car moving forward.&quot;);<br>  }<br><br>  moveReverse() {<br>    console.log(&quot;Car moving in reverse.&quot;);<br>  }<br>}<br><br>class MotorBike extends Vehicle {<br>  moveForward() {<br>    console.log(&quot;Motorbike moving forward.&quot;);<br>  }<br><br>  moveReverse() {<br>    console.log(&quot;Motorbike moving in reverse.&quot;);<br>  }<br>}<br><br>const honda = new Car();<br>const suzuki = new MotorBike();<br><br>honda.moveForward();<br>suzuki.moveForward();</pre><h4>Abstraction</h4><p>Abstraction is a concept in OOP that involves hiding the complex implementation details and exposing only the necessary features of an object. While similar to encapsulation, the focus here is on presenting a simplified view of complex data structures and operations.</p><p>In JavaScript, abstraction can be achieved by exposing methods that interact with private/internal fields, while hiding how those details are implemented.</p><p>An example of <strong>abstraction</strong> in JavaScript is the console.log() method. While we use it to print messages to the console, we don&#39;t need to know <em>how</em> it works internally — how it interacts with the browser&#39;s developer tools or the underlying system. All that complexity is hidden from us, and we’re given a simple interface to use. That’s abstraction in action: exposing only what we need, and hiding the details we don’t.</p><h3>🧠 Conclusion</h3><p>To wrap it up, <strong>Object-Oriented Programming (OOP)</strong> is all about structuring code to reflect the real world — organizing everything into objects that interact with each other. With key concepts like <strong>encapsulation</strong>, <strong>inheritance</strong>, <strong>polymorphism</strong>, and <strong>abstraction</strong>, OOP makes it easier to write reusable, scalable, and maintainable code.</p><p>Whether you’re building a small script or a large application, understanding and applying OOP principles will help you build cleaner and more robust software.</p><p>Thanks for reading! 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ab69b6c4bbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error Handling in API Design]]></title>
            <link>https://medium.com/@elijahechekwu/error-handling-in-api-design-c2d38cfc68d9?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2d38cfc68d9</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 05:33:27 GMT</pubDate>
            <atom:updated>2025-04-07T05:33:27.062Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Guide to Building Robust Backends</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*bT1owtkV25r-csKcRCh4sw.png" /><figcaption>Error handling in API Design</figcaption></figure><p>In this article, I’ll share best practices I’ve learned and implemented while designing APIs. When building APIs, error handling often feels like an afterthought — something to tackle later — but it shouldn’t be. Proper error handling not only improves the developer experience but also helps users understand what went wrong and how to fix it.</p><p>Whether you’re building RESTful APIs or GraphQL endpoints, designing a consistent and informative error response structure is critical. In this article, we’ll walk through best practices for error handling in API design, including status codes, response structure, actionable messages, and proper error-handling logic within the application.</p><h3>1. Embrace HTTP Status Codes</h3><p>HTTP status codes are the first line of communication between your API and the client. There are a three-digit code that indicates the outcome of an HTTP request, categorized into five classes (1xx, 2xx, 3xx, 4xx, and 5xx) to signal informational responses, success, redirection, client errors, and server errors respectively.</p><h4>1xx Informational Responses:</h4><p><strong>100</strong> <strong><em>Continue</em></strong>: Indicates that the server has received the initial part of the request and the client should continue sending the request.</p><h4>2xx Successful Responses:</h4><p><strong>200</strong> <strong><em>OK</em></strong>: The request was successful, and the server returned the requested resource.</p><p><strong>201</strong> <strong><em>Created</em></strong>: The request has been fulfilled, and a new resource has been created.</p><p><strong>204</strong> <strong><em>No Content</em></strong>: The server has successfully processed the request, but there is no content to return.</p><h4>3xx Redirection Messages:</h4><p><strong>301</strong> <strong><em>Moved Permanently</em></strong>: The requested resource has been permanently moved to a new location.</p><p><strong>302</strong> <strong><em>Found</em></strong>: The requested resource has been temporarily moved to a new location.</p><p><strong>304</strong> <strong><em>Not Modified</em></strong>: The resource has not been modified since the last request.</p><h4>4xx Client Error Responses:</h4><p><strong>400</strong> <strong><em>Bad Request</em></strong>: The server cannot process the request due to a client error, such as invalid syntax or missing data.</p><p><strong>401</strong> <strong><em>Unauthorized</em></strong>: The client needs to authenticate to access the resource.</p><p><strong>403</strong> <strong><em>Forbidden</em></strong>: The client is not authorized to access the resource.</p><p><strong>404</strong> <strong><em>Not Found</em></strong>: The server cannot find the requested resource.</p><p><strong>405</strong> <strong><em>Method Not Allowed</em></strong>: The HTTP method used in the request is not allowed for the resource.</p><h4>5xx Server Error Responses:</h4><p><strong>500</strong> <strong><em>Internal Server Error</em></strong>: The server encountered an unexpected error and cannot fulfill the request.</p><p><strong>501</strong> <strong><em>Not Implemented</em></strong>: The server does not support the functionality required to fulfill the request.</p><p><strong>502</strong> <strong><em>Bad Gateway</em></strong>: The server received an invalid response from another server it used as a gateway.</p><p><strong>503</strong> <strong><em>Service Unavailable</em></strong>: The server is temporarily unavailable.</p><p><strong>504</strong> <strong><em>Gateway Timeout</em></strong>: The server did not receive a response from another server it used as a gateway within a specified time.</p><p>One best practices to follow in proper HTTP status code, is to stick with well-understood conventions. Don’t return 200 OK for a failed request with an error message in the body — this breaks expectations and can confuse clients.</p><h3>2. Use a Consistent Error Format</h3><p>Clients shouldn’t have to guess what an error means. A consistent structure makes parsing and debugging easier. An example of a proper error Format is :</p><pre>{ <br>&quot;status&quot;: false,<br>&quot;error&quot;: {<br>    &quot;code&quot;: &quot;VALIDATION_ERROR&quot;, <br>    &quot;message&quot;: &quot;Email is required.&quot;, <br>    &quot;details&quot;: [{ <br>        &quot;field&quot;: &quot;email&quot;, <br>        &quot;issue&quot;: &quot;Missing&quot; <br>        }] <br>    } <br>}</pre><h4>Breakdown</h4><p>status: false: A boolean indicating the operation <strong>failed</strong>. This helps clients quickly distinguish between success (true) and failure (false) without parsing the entire response.</p><p>error (object): A container for detailed error information.</p><ul><li>code: &quot;VALIDATION_ERROR&quot;:A <strong>machine-readable</strong> error code. Useful for <strong>internationalization</strong>, <strong>frontend error handling</strong>, or <strong>logging systems</strong>. You might also have codes like AUTH_ERROR, NOT_FOUND, SERVER_ERROR, etc.</li><li>message: &quot;Email is required.&quot;: A <strong>human-readable</strong> summary of the error. This can be shown directly to the end user in most cases. It Should be clear, concise, and written in user-friendly language.</li><li>details (array of objects): <strong>Field-level error breakdowns</strong> — especially helpful when <strong>multiple fields</strong> are invalid. Each object describes a specific issue</li></ul><h3>3. Be Specific and Descriptive</h3><p>Avoid vague messages like “Something went wrong.” Instead, provide messages that help the client understand and fix the problem. For example,</p><h4>🔴Bad</h4><pre>{ &quot;message&quot;: &quot;Error processing request&quot; }</pre><h4>✅Good</h4><pre>{ <br>  &quot;status&quot;: false,<br>  &quot;error&quot;: {<br>    &quot;code&quot;: &quot;INVALID_DATE&quot;, <br>    &quot;message&quot;: &quot;The provided date is not in a valid ISO 8601 format.&quot; <br>  } <br>}</pre><h4>4. Handle Validation Gracefully</h4><p>Validation errors are common and should be grouped and returned at once.</p><pre>{ <br>  &quot;status&quot;: false,<br>  &quot;error&quot;: { <br>    &quot;code&quot;: &quot;VALIDATION_ERROR&quot;, <br>    &quot;message&quot;: &quot;Some fields are invalid.&quot;, <br>    &quot;details&quot;: [ { <br>      &quot;field&quot;: &quot;email&quot;, <br>      &quot;issue&quot;: &quot;Invalid format&quot; <br>      }, { <br>      &quot;field&quot;: &quot;password&quot;, <br>      &quot;issue&quot;: &quot;Too short&quot; <br>      } <br>    ] <br>  } <br>}</pre><p>This way, users get the full picture in one go.</p><h4>5. Avoid Leaking Internal Details</h4><p>Never expose internal stack traces or DB errors directly. It’s a security risk and adds no value to the client. Instead, log the error internally and return a generic error to the client:</p><pre>{ <br>  &quot;status&quot;: false,<br>  &quot;error&quot;: { <br>    &quot;code&quot;: &quot;INTERNAL_SERVER_ERROR&quot;, <br>    &quot;message&quot;: &quot;An unexpected error occurred. Please try again later.&quot; <br>  } <br>}</pre><h4>6. Make Errors Actionable</h4><p>Where possible, tell users how to fix the error.</p><pre>{ <br>&quot;status&quot;: false,<br>&quot;error&quot;: { <br>    &quot;code&quot;: &quot;RATE_LIMIT_EXCEEDED&quot;, <br>    &quot;message&quot;: &quot;Too many requests. Try again in 60 seconds.&quot; <br>  } <br>}</pre><p>This saves time for the developer and improves overall user experience.</p><h4>7. Document Error Responses</h4><p>Good API documentation includes a section on common errors, with examples. Tools like Swagger/OpenAPI can help you document this in a standardized way.</p><h4>8. Implementing a Custom Error Handler within your Application</h4><p>It is best practice when designing APIs, to implement a centralized Error Handler Logic within your application for consistency. This provides a standardized and clean way to catch and throw error within the different components of your application. Here is an example using <strong>Node.js</strong> + <strong>Express.js</strong></p><h4>Creating a custom HTTP Error class</h4><pre>import { NextFunction, Response, Request } from &quot;express&quot;;<br><br>// Creating an Custom Error Class within the application<br>class HttpError extends Error {<br>    statusCode: number;<br><br>    constructor(statusCode: number, message: string){<br>        super(message);<br>        this.name = this.constructor.name;<br>        this.statusCode = statusCode<br>    }<br>}<br>  </pre><h4>Creating specific Error Class</h4><pre>export class BadRequest extends HttpError {<br>    constructor(message: string){<br>        super(400, message)<br>    }<br>}<br><br>export class ResourceNotFound extends HttpError{<br>    constructor(message: string){<br>        super(404, message)<br>    }<br>}<br><br>export class Unauthorized extends HttpError {<br>    constructor(message: string) {<br>      super(401, message);<br>    }<br>  }<br>  <br>  export class Forbidden extends HttpError {<br>    constructor(message: string) {<br>      super(403, message);<br>    }<br>  }<br>  <br>  export class ServerError extends HttpError {<br>    constructor(message: string) {<br>      super(500, message);<br>    }<br>  }</pre><p>These specific sub-classes help you <strong>throw meaningful errors in routes/services</strong> like this:</p><pre>if (!email) throw new BadRequest(&quot;Email is required.&quot;);</pre><h4>404 Route handler</h4><pre>const routeNotFound = (req: Request, res: Response, next: NextFunction) =&gt; {<br>    const message = `Route not Found: ${req.originalUrl}`;<br>    res.status(404).json({ status: false, message });<br>}</pre><h4>Global Error Handler Middleware</h4><pre>const errorHandler = (err: HttpError, req: Request, res: Response, next: NextFunction) =&gt; {<br>    const statusCode = err.statusCode || 500;<br>    const message = err.message.replace(/&quot;/g, &quot;&quot;);<br>    <br>    res.status(statusCode).json({<br>        status: false,<br>        statusCode,<br>        message,<br>        stack: process.env.NODE_ENV === &quot;PROD&quot; ? &quot;&quot; : err.stack // hide stack in prod<br>    });<br>}</pre><h3>Final Thoughts</h3><p>Error handling is an essential part of API design. A well-designed error system helps developers quickly diagnose issues, improves user experience, and builds trust in your API. So the next time you’re building or refactoring an API, give error handling the attention it deserves — you’ll thank yourself later.</p><p><em>Want more tips on building resilient APIs and backend systems? Follow me for daily insights on backend development and software design. Cheers !!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2d38cfc68d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building a Rate Limiter from Scratch in Node.js]]></title>
            <link>https://medium.com/@elijahechekwu/building-a-rate-limiter-from-scratch-in-node-js-8ff9081d3592?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ff9081d3592</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 22:19:23 GMT</pubDate>
            <atom:updated>2025-07-26T19:48:58.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*hO37xLN4f9DZm5L_gshvFA.png" /><figcaption>Rate limiter</figcaption></figure><p>Rate limiting is an essential step to consider in maintaining the health of your API. In simple words, it’s setting a <strong>limit</strong> on the <strong>rate</strong> at which request can be made to your API.</p><blockquote><strong>Rate limiting</strong> restricts how many requests a user/client can make to an API within a specific time frame.</blockquote><p>Rate limiter could be used in the following cases</p><ul><li>Protecting your API against abuse (DDoS attacks)</li><li>Handling sudden spike in traffic (Avoiding server overload)</li><li>Ensuring fair resource use among clients (e.g., 60 requests/ min per user)</li></ul><p>In this article, we’ll <strong>build a simple but effective rate limiter from scratch in Node.js — </strong>no third-party libraries, just the core concepts. Also, we’ll talk about the pros and cons of this approach and when and why to use more advanced strategies like Redis-backed distributed limiters.</p><h3>🛠️ Approaches to Rate Limiting</h3><p>There are many algorithms to implement rate limiting and each has its pros and cons</p><ol><li>Fixed window</li><li>Sliding window</li><li>Token bucket</li><li>Leaky bucket</li></ol><p>For simplicity, we’ll implement the <strong>Fixed Window</strong> approach. It’s intuitive and gets the job done in many scenarios.</p><p>One thing to note is the constraint for limiting <strong>rate</strong>, this could be something distinct about the request. It could be any of the following,</p><ul><li><strong>Users</strong>: The constraint for limiting <strong><em>rate</em></strong> is based on a specific user identity (i.e userID).</li><li><strong>Geo-location</strong>: The constraint for limiting <strong><em>rate</em></strong> is based on the <strong><em>geographical location </em></strong>from which the request was made</li><li><strong>IP Address</strong>: The constraint for limiting <strong><em>rate</em></strong> is based on the <strong><em>IP address</em></strong> of the device that initiates the request.</li></ul><h4>Fixed Window</h4><p>This is the most basic approach of implementing rate limiting. It divides time into fixed intervals (windows) and restricts the number of requests allowed within each window, (like a 1-minute or 1-hour limit), with the counter resetting at the start of each new window.</p><p>For example, a fixed window with limit of <strong><em>10 requests per minute</em></strong>. If a user makes 10 requests between 12:00:00 and 12:00:59, any further requests until 12:01:00 will be blocked.</p><blockquote>Fixed window rate limiting algorithm restrict the number of requests allowed within a given time frame (window)</blockquote><h4><strong>How it works</strong></h4><ul><li><strong>Divide time into fixed windows:</strong> The time is divided into equal intervals, such as 1-minute or 1-hour windows.</li><li><strong>Track requests within each window:</strong> For each user or client, a counter is maintained to track the number of requests made within a specific window.</li><li><strong>Enforce limits:</strong> If the number of requests within a window exceeds the defined limit, subsequent requests are blocked until the window resets.</li><li><strong>Reset the counter:</strong> At the start of each new window, the counter is reset to zero, allowing a fresh set of requests.</li></ul><h3>Setting Up the Project</h3><p>First, let’s create a basic Express server:</p><pre>mkdir rate-limiter-node &amp;&amp; cd rate-limiter-node<br>npm init -y<br>npm install express</pre><h4>Core Idea: Fixed Window Rate Limiting</h4><p>We’ll <strong>limit</strong> requests <em>per</em> <strong>IP address.</strong></p><blockquote>Example policy: <strong>Max 5 requests per minute per IP.</strong></blockquote><p>We’ll store the request counts in an in-memory object like this,Although not efficient but this approach is suitable for this implementation.</p><pre>const rateLimiters = {};<br><br><br>// Each IP address will have a structure like this<br><br>{<br>  count: 2,<br>  startTime: 1712309000000 // timestamp of the current window start<br>}</pre><p>Create rateMiddleware.js</p><pre>const rateLimiters = {};<br><br>const rateLimiter = (req, res, next) =&gt; {<br>  const ip = req.ip;<br>  const now = Date.now();<br>  const WINDOW_SIZE_IN_MS = 60 * 1000; // 1 minute<br>  const MAX_REQUESTS = 5;<br><br>  if (!rateLimiters[ip]) {<br>    rateLimiters[ip] = {<br>      count: 1,<br>      startTime: now<br>    };<br>    return next();<br>  }<br><br>  const timePassed = now - rateLimiters[ip].startTime;<br><br>  if (timePassed &lt; WINDOW_SIZE_IN_MS) {<br>    if (rateLimiters[ip].count &lt; MAX_REQUESTS) {<br>      rateLimiters[ip].count++;<br>      next();<br>    } else {<br>      res.status(429).json({ message: &quot;Too many requests. Please try again later.&quot; });<br>    }<br>  } else {<br>    // Reset the window<br>    rateLimiters[ip].count = 1;<br>    rateLimiters[ip].startTime = now;<br>    next();<br>  }<br>};<br><br><br>module.exports = rateLimiter</pre><h4>Explanation:</h4><ol><li><strong>Define Middleware:</strong> The file defines a middleware function rateLimiter to handle incoming requests.</li><li><strong>Get Client Info: </strong>(<strong><em>line 4 — line 5</em></strong>) Extracts the requester’s IP address (req.ip) and the current time (Date.now()).</li><li><strong>Set Rate Limits:</strong> (<strong><em>line 6— line 7</em></strong>)Establishes the time window (1 minute) and the maximum allowed requests (5).</li><li><strong>First Request Check: </strong>(<strong><em>if block</em></strong>) If the IP is new, initialize its request count and start time, then allow the request.</li><li><strong>Within Limit Check:</strong> (<strong><em>line 16— line 20</em></strong>)If the IP exists and the current time is within the window, check if the request count is below the maximum.</li><li><strong>Handle Limit Exceeded:</strong> (<strong><em>line 21</em></strong>, <strong><em>else block</em></strong>)If the request count is at or above the limit within the window, reject the request with a 429 error.</li><li><strong>Reset Window: </strong>(<strong><em>line 23 — line 27</em></strong>) If the time window has passed for the IP, reset its request count and start time, then allow the request.</li><li><strong>Export Middleware:</strong> Makes the rateLimiter function available for use in other parts of the application.</li></ol><p>In index.js</p><pre>const express = require(&quot;express&quot;);<br>const rateLimiter = require(&quot;./rateMiddleware&quot;)<br>const app = express();<br>const PORT = 3000;<br><br><br>app.use(&quot;/api&quot;, rateLimiter);<br><br>app.get(&quot;/api&quot;, (req, res) =&gt; {<br>  res.send(&quot;Hello from the API!&quot;);<br>});<br><br>app.listen(PORT, () =&gt; console.log(`Server running on http://localhost:${PORT}`));</pre><h4>Testing it Out</h4><p>Start the server:</p><pre>node index.js</pre><p>Then make repeated requests to http://localhost:3000/api using a browser, Postman, or curl. After 5 rapid requests, the 6th should return:</p><pre>{ &quot;message&quot;: &quot;Too many requests. Please try again later.&quot; }</pre><h4>Limitations of this approach</h4><p>This basic in-memory implementation works for:</p><ul><li>Prototyping and hands-on learning</li><li>Single-instance apps</li><li>Internal tools</li></ul><p>But it breaks down when:</p><ul><li>You scale horizontally (e.g., multiple Node.js servers)</li><li>You want persistence across restarts</li><li>You need real-time analytics or advanced control.</li></ul><p>To overcome these limitation consider using a proper tool like express-rate-limit or implementing complex rate limit algorithm with a redis cache to persist data, across multiple Node.js server instance.</p><h4>✅ Wrap-Up</h4><p>We:</p><ul><li>Understood the need for rate limiting</li><li>Built a custom rate limiter middleware from scratch</li><li>Explored limitations and production alternatives</li></ul><p>This hands-on practices gives you insight and practical knowledge into how what rate limiting is all about and how it is implemented in tools like express-rate-limit.</p><pre>//using express-rate-limit and rate-limit-redis(as a store, rather than storing in memory)<br>// middlewares/ratelimit.ts<br><br>import rateLimit from &quot;express-rate-limit&quot;;<br>import RedisStore from &quot;rate-limit-redis&quot;;<br>import { redisCacheClient } from &quot;../db&quot;;<br>import type { RedisReply } from &#39;rate-limit-redis&#39;;<br><br>export const limiter = rateLimit({<br>    windowMs:  60 * 1000,<br>    limit: 10,<br>    store: new RedisStore({<br>        sendCommand: (...args: [command: string, ...args: (string | Buffer | number)[]]) =&gt; {<br>            return redisCacheClient.call(...args) as Promise&lt;RedisReply&gt;<br>        }<br> }),<br>    standardHeaders: true,<br>    legacyHeaders: false, <br>})</pre><pre>// in router<br><br>import { searchCar, getCar } from &quot;../controllers&quot;<br>import { Router } from &quot;express&quot;<br>import { limiter } from &quot;../middlewares/ratelimit&quot;;<br><br>export const carRouter = Router();<br><br>carRouter.get(&quot;/&quot;, limiter, searchCar);<br><br>carRouter.get(&quot;/:id&quot;, limiter, getCar);</pre><p><em>“Until next time, keep your API safe”. Cheers !!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ff9081d3592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotency in Software Design]]></title>
            <link>https://medium.com/@elijahechekwu/idempotency-in-software-design-8b89ef717b23?source=rss-ee32146b770a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b89ef717b23</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Elijah Echekwu]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 14:36:15 GMT</pubDate>
            <atom:updated>2025-04-03T14:36:15.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*t8W9Io7acLyM2XzBg03d4Q.png" /><figcaption>Idempotency</figcaption></figure><p>Idempotency is the characteristics of an operation/process that ensures that if the operation is performed more than once, the results over the time remains the same as the initial result.</p><p>Idempotency is a concept that is ingrained in our every day interactions with devices. For example, the Metro buses, have a stop button, that is idempotent in design, if the stop button is pressed more than once, it still performs the same initial intended action.</p><p>Another example is automatic doors, if the sensor detects a person, the door opens, further detection do not reopen it.</p><h4>Idempotency in HTTP Request</h4><p>In HTTP Request, a perfect example of Idempotency is the HTTP <strong>GET</strong> Method. A <strong>GET</strong> request fetches data from the server and returns the same result, irrespective of how many times the request is made (provided the data in the server has not changed)</p><p>One of the areas in software design that Idempotency is a major concern, is in API Design. In API design, <strong>idempotency</strong> is crucial to ensure that multiple identical requests have the same effect as a single request. I.e., regardless of how many times a client sends the same request, the server’s state remains unchanged beyond the first successful execution</p><p>Idempotency is particularly important for handling retries in <strong>distributed systems</strong>, <strong>network failures</strong>, and <strong>duplicate requests</strong>. It helps improve API <strong>fault tolerance</strong>, <strong>reliability</strong>, and <strong>consistency</strong>, making them more predictable and user-friendly.</p><p>An application of Idempotency in API design is in payment systems, where you want a transaction/ API calls to perform an operation only once, irrespective of the multiple times it might be called. <br>For example, Imagine a payment system with non-idempotent APIs, if a user initiates a transaction and the action was interrupted by a network failure, further retries would result in multiple transaction (and charges, as the case may be).</p><p>Idempotency in API design, makes API reliable and predictable, ensuring that the state and response of an API is predictable over multiple interactions.</p><h3>Implementing Idempotency in API Design</h3><p>The idea of idempotency is ensuring a consistent result over multiple identical action. One way to achieve that in API design, is the use of <strong>Idempotency key</strong>.</p><h4>Idempotency Key</h4><p>An <strong>Idempotency key</strong> is a unique identifier sent along in a request by the client to ensure that an API operation is processed only once, even if the request is retried multiple times.</p><p>The server stores the idempotency key along with the processed request, ensuring that idempotent calls can be made any number of times without concern that the server creates or completes an action on a resource more than once. Idempotent calls can be retried on failure with network timeouts or HTTP 5xx status codes as long as the server stores the Idempotency key. <br>This is useful for preventing duplicate transactions in scenarios like payment processing, order creation, or database updates.</p><h4>How it Works?</h4><ol><li><strong>Client Sends a Request with an Idempotency Key</strong></li></ol><ul><li>The client generates a <strong>unique key</strong> (e.g., UUID) and includes it in the request header or body.</li></ul><pre>// Example:<br><br>POST /payments<br>Content-Type: application/json<br>Idempotency-Key: 123e4567-e89b-12d3-a456-426614174000</pre><p>2. <strong>Server Checks for an Existing Idempotency Key</strong></p><ul><li>If the <strong>key</strong> is new, the server processes the request and stores the result (e.g., in a database or cache).</li><li>If the <strong>key</strong> already exists, the server returns the previously stored response instead of processing it again.</li></ul><p>3. <strong>Server Returns a Response</strong></p><ul><li>If the request was executed previously, the stored response is returned.</li><li>If it’s a new request, it is processed and stored under the given key.</li></ul><h3>Example Implementation in Node.js (<strong>Express.Js + Redis</strong>)</h3><p>This could be implemented as a middleware that checks for the <strong>Idempotency-key</strong> in the request.</p><h4>Idempotency Middleware for Handling API Request</h4><pre>// middlewares/idempotencyMiddleware.ts<br><br>import { Redis } from &quot;ioredis&quot;;<br>import { Request, Response, NextFunction } from &quot;express&quot;;<br>import crypto from &quot;crypto&quot;;<br>import dotenv from &quot;dotenv&quot;;<br>dotenv.config();<br><br><br>export const redisClient = new Redis(process.env.REDIS_URL);<br><br><br>export async function idempotencyMiddleware(req: Request, res: Response, next: NextFunction) {<br>    const idempotencyKey = req.headers[&quot;idempotency-key&quot;];<br><br>    if (!idempotencyKey) {<br>        return res.status(400).json({ error: &quot;Idempotency key required&quot; });<br>    }<br><br>    const cachedResponse = await redisClient.get(idempotencyKey);<br>    <br>    if (cachedResponse) {<br>        return res.json(JSON.parse(cachedResponse));<br>    }<br><br>    res.locals.idempotencyKey = idempotencyKey;<br>    next();<br>}</pre><h4>API Endpoint with Idempotency Handling</h4><pre>import express from &quot;express&quot;;<br>import { idempotencyMiddleware, redisClient} from &quot;./middlewares/idempotencyMiddleware&quot;<br>import crypto from &quot;crypto&quot;;<br><br><br>const app = express();<br>app.use(express.json());<br><br>app.post(&quot;/payments&quot;, idempotencyMiddleware, async (req, res) =&gt; {<br>    const paymentId = crypto.randomUUID(); // Simulating payment processing<br><br>    const response = { success: true, paymentId };<br>    <br>    // Store response in Redis with expiration (e.g., 10 minutes)<br>    await redisClient.set(res.locals.idempotencyKey, JSON.stringify(response), {<br>        EX: 600,<br>    });<br><br>    res.json(response);<br>});<br><br>app.listen(3000, () =&gt; console.log(&quot;Server running on port 3000&quot;));</pre><h3>Use Cases for Idempotency Keys</h3><h4><strong>Payment Processing</strong></h4><ul><li>Prevents duplicate charges if a user retries payment due to a slow response.</li><li>Example: PayPal uses an idempotency key to ensure a charge isn’t processed twice.</li></ul><h4><strong>Order Creation in E-commerce</strong></h4><ul><li>Prevents accidental duplicate orders when a user clicks “Place Order” multiple times.</li></ul><h4><strong>API Requests in Distributed Systems</strong></h4><ul><li>If a client retries due to network failure, the server avoids executing the request twice.</li></ul><h4><strong>Database Updates</strong></h4><ul><li>Ensures multiple requests updating the same record don’t create duplicate entries.</li></ul><p>“Idempotency in APIs prevents duplicate processing and ensures reliability. Implementing it with an idempotency key can save your users from headaches!”</p><p>🚀 <em>“Until next time, keep your APIs clean and your retries smart!” . Cheers !!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b89ef717b23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>