<?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 Abdelrahman Soliman on Medium]]></title>
        <description><![CDATA[Stories by Abdelrahman Soliman on Medium]]></description>
        <link>https://medium.com/@abesolyman?source=rss-89c99f8915cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cHDQnsGYnipp9jyJnOA7pA.jpeg</url>
            <title>Stories by Abdelrahman Soliman on Medium</title>
            <link>https://medium.com/@abesolyman?source=rss-89c99f8915cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:40:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abesolyman/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[How to make your JavaScript SDK compatible with all browsers]]></title>
            <link>https://abesolyman.medium.com/how-to-make-your-javascript-sdk-compatible-with-all-browsers-4750da937f8d?source=rss-89c99f8915cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4750da937f8d</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm-package]]></category>
            <dc:creator><![CDATA[Abdelrahman Soliman]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 12:48:48 GMT</pubDate>
            <atom:updated>2025-08-22T12:48:48.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOaRWbeDcSpl1rk5xyKCRw.png" /></figure><h3>Introduction</h3><p>As a software engineer, you’ve probably encountered terms like “CommonJS,” “ECMAScript modules,” and “cross-compatibility” when working with JavaScript packages. But what do these actually mean, and why should you care?</p><p>In this article, I’ll walk you through how I built a web SDK that works seamlessly across different JavaScript environments — from legacy browsers to modern Node.js applications. We’ll explore the fundamental differences between module systems and how to configure TypeScript to generate code that works everywhere.</p><h3>What’s the Difference Between CommonJS and ECMAScript Modules?</h3><p>So I know the first question on mind is what CommonJS and Ecma are and why we moved to ECMA? In a nutshell, CommonJS is the old JavaScript and ECMA is the new JavaScript</p><h3>CommonJS (CJS) — The Legacy Standard</h3><p>CommonJS is the traditional module system that Node.js adopted early on. It uses require() and module.exports:</p><pre>// CommonJS syntax<br>const axios = require(&#39;axios&#39;);<br><br>function fetchData() {<br>  return axios.get(&#39;/api/data&#39;);<br>}<br><br>module.exports = { fetchData };</pre><p>When it’s used:</p><ul><li>Older Node.js applications</li><li>Legacy build tools (Webpack 4 and earlier)</li><li>Some bundlers and older browsers</li></ul><h4>CommonJS Was Never Designed for Browsers</h4><p>CommonJS was created specifically for server-side JavaScript (Node.js). It has some fundamental characteristics that don’t work well in browsers:</p><pre>// CommonJS - This doesn&#39;t work in browsers!<br>const fs = require(&#39;fs&#39;);  // ❌ No file system in browsers<br>const path = require(&#39;path&#39;); // ❌ No Node.js path module<br><br>// Synchronous loading - blocks the main thread<br>const data = require(&#39;./data.json&#39;); // ❌ Synchronous = bad for browsers</pre><p>The Problem: CommonJS modules are loaded synchronously, which means:</p><ul><li>The browser has to stop everything and wait for each module to load</li><li>This blocks the main thread, making your website freeze</li><li>It’s terrible for performance and user experience</li></ul><h3>ECMAScript Modules (ESM) — The Modern Standard</h3><p>ECMAScript modules are the official JavaScript standard, using import and export:</p><pre>// ECMAScript module syntax<br>import axios from &#39;axios&#39;;<br><br>export function fetchData() {<br>  return axios.get(&#39;/api/data&#39;);<br>}</pre><p>When it’s used:</p><ul><li>Modern browsers (ES6+)</li><li>Modern Node.js (12+ with proper configuration)</li><li>Contemporary build tools (Vite, modern Webpack, Rollup)</li><li>React, Vue, and other modern frameworks</li></ul><h4>ECMAScript Modules Are Built for the Web</h4><p>ECMAScript modules were designed with browser environments in mind:</p><pre>// ECMAScript modules - Designed for browsers!<br>import { fetchData } from &#39;./api.js&#39;;  // ✅ Async by nature<br>import(&#39;./lazyModule.js&#39;).then(module =&gt; {  // ✅ Dynamic imports<br>  // Load modules on-demand<br>});</pre><p>Key Benefits:</p><ul><li>Asynchronous loading — doesn’t block the main thread</li><li>Better performance — modules load in parallel</li><li>Native browser support — no need for bundlers (in modern browsers)</li></ul><h4>The Major Benefits of ECMAScript Modules</h4><h4>1. Performance Improvements</h4><p>before (CommonJS-style bundling):</p><pre>// Old way - everything loaded at once<br>// bundle.js (2MB) - loads everything, even unused code</pre><h4>After (ESM with tree-shaking):</h4><pre>// Modern way - only load what you need<br>import { Button } from &#39;ui-library&#39;;  // Only Button component gets included<br>// bundle.js (50KB) - much smaller!</pre><p>Tree-shaking means unused code gets automatically removed, resulting in:</p><ul><li>Smaller bundle sizes</li><li>Faster page loads</li><li>Better user experience</li></ul><h4>2. Better Caching and Loading</h4><pre>// ESM allows for better caching strategies<br>import { Header } from &#39;./components/Header.js&#39;;  // Can be cached separately<br>import { Footer } from &#39;./components/Footer.js&#39;;  // Can be cached separately<br><br>// If Header changes, only Header.js needs to be re-downloaded<br>// Footer.js can still use the cached version</pre><h4>3. Dynamic Imports (Code Splitting)</h4><pre>// Load modules only when needed<br>if (user.isPremium) {<br>  import(&#39;./premium-features.js&#39;).then(module =&gt; {<br>    module.enablePremiumFeatures();<br>  });<br>}<br><br>// This means:<br>// - Initial page loads faster<br>// - Premium features only load for premium users<br>// - Better performance for all users</pre><h4>4. Native Browser Support</h4><p>Modern browsers can load ESM directly without any build step:</p><pre>&lt;!-- This works natively in modern browsers! --&gt;<br>&lt;script type=&quot;module&quot;&gt;<br>  import { createApp } from &#39;./app.js&#39;;<br>  createApp();<br>&lt;/script&gt;</pre><p>No more need for:</p><ul><li>Webpack</li><li>Browserify</li><li>Complex build pipelines (for simple projects)</li></ul><h3>The Problem: Why Can’t We Just Pick One?</h3><p>Here’s the challenge: different environments expect different module formats:</p><ul><li>Legacy browsers might only support CommonJS</li><li>Modern bundlers prefer ESM for tree-shaking</li><li>Node.js applications might use either depending on their version</li><li>Browser-based tools often expect ESM</li></ul><p>If you only support one format, you’re excluding a significant portion of potential users.</p><h3>The Solution: Dual Output with TypeScript</h3><p>My approach was to configure TypeScript to generate both formats simultaneously. Here’s how:</p><h4>1. TypeScript Configuration for ESM</h4><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es2016&quot;,<br>    &quot;module&quot;: &quot;esnext&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;declaration&quot;: true,<br>    &quot;outDir&quot;: &quot;./dist/esm&quot;,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;skipLibCheck&quot;: true<br>  }<br>}</pre><p>Key settings explained:</p><ul><li>“module”: “esnext” — Generates modern ES modules</li><li>“target”: “es2016” — Ensures compatibility with browsers from 2016+</li><li>“esModuleInterop”: true — Allows importing CommonJS modules in ESM code</li><li>“declaration”: true — Generates .d.ts type definition files</li></ul><h4>2. Package.json Configuration for Dual Output</h4><pre>{<br>  &quot;main&quot;: &quot;dist/cjs/index.js&quot;,<br>  &quot;module&quot;: &quot;dist/esm/index.js&quot;,<br>  &quot;types&quot;: &quot;dist/esm/index.d.ts&quot;,<br>  &quot;exports&quot;: {<br>    &quot;.&quot;: {<br>      &quot;import&quot;: &quot;./dist/esm/index.js&quot;,<br>      &quot;require&quot;: &quot;./dist/cjs/index.js&quot;,<br>      &quot;types&quot;: &quot;./dist/esm/index.d.ts&quot;<br>    }<br>  }<br>}</pre><p>What each field does:</p><ul><li>“main” — Fallback for older tools (CommonJS)</li><li>“module” — Preferred by modern bundlers (ESM)</li><li>“types” — TypeScript type definitions</li><li>“exports” — Modern Node.js resolution with conditional exports</li></ul><h4>3. Build Scripts for Both Formats</h4><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;build:esm&quot;: &quot;tsc&quot;,<br>    &quot;build:cjs&quot;: &quot;tsc --module commonjs --outDir dist/cjs&quot;,<br>    &quot;build&quot;: &quot;npm run build:esm &amp;&amp; npm run build:cjs&quot;<br>  }<br>}</pre><p>This generates two separate builds:</p><ul><li>dist/esm/ — Modern ES modules</li><li>dist/cjs/ — CommonJS modules</li></ul><h3>How It Works in Practice</h3><h4>For Modern Environments (ESM)</h4><pre>// Bundlers automatically choose the ESM version<br>import { SessionRecorder } from &#39;@perceptr/web-sdk&#39;;</pre><h4>For Legacy Environments (CommonJS)</h4><pre>// Older tools get the CommonJS version<br>const { SessionRecorder } = require(&#39;@perceptr/web-sdk&#39;);</pre><h4>For Typescript</h4><pre>// TypeScript gets proper types regardless of module system<br>import { SessionRecorder } from &#39;@perceptr/web-sdk&#39;;</pre><h4>The Benefits of This Approach</h4><ol><li>Universal Compatibility — Works in any JavaScript environment</li><li>Automatic Selection — Tools choose the best format automatically</li><li>Future-Proof — Supports both current and legacy systems</li><li>Better Tree-Shaking — Modern bundlers can optimize ESM imports</li><li>Type Safety — Full TypeScript support across all environments</li></ol><p><strong>To publish</strong> <strong>on</strong> <strong>NPM</strong></p><pre>// run this<br>// change version in package json<br>npm run build:esm &amp;&amp; npm run build:cjs &amp;&amp; npm publish --access public </pre><h3>Conclusion</h3><p>Creating a cross-compatible SDK might seem like extra work initially, but it’s an investment that pays off in user adoption and long-term maintainability. By understanding the differences between CommonJS and ECMAScript modules, and configuring TypeScript to generate both formats, you can create packages that work everywhere.</p><p>The key is to think about your users’ environments, not just your own. Whether they’re using a 10-year-old browser or the latest Node.js version, your SDK should just work.</p><p><em>This article is based on my experience building the </em><a href="https://www.npmjs.com/package/@perceptr/web-sdk"><em>Perceptr Web SDK</em></a><em>, a cross-compatible session recording library that works across all JavaScript environments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4750da937f8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Most JWTs Are Insecure. Here’s How to Make Yours Bulletproof”]]></title>
            <link>https://abesolyman.medium.com/most-jwts-are-insecure-heres-how-to-make-yours-bulletproof-a92c66a5f270?source=rss-89c99f8915cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a92c66a5f270</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[security-token]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Abdelrahman Soliman]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 11:57:18 GMT</pubDate>
            <atom:updated>2025-08-13T11:57:18.319Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2XUKSLsKcgko8IV_sVHWg.png" /></figure><p>JWTs (JSON Web Tokens) are everywhere.<br> They’re in your login flows, your microservices, your mobile APIs — and if you’ve ever built an auth system in Node, you’ve probably used one without thinking twice.</p><p>But here’s the uncomfortable truth:<br> A JWT is <strong>not</strong> encryption. It’s just <strong>signed, base64-encoded JSON</strong>. And that means:</p><ul><li>It can be <strong>read</strong> by anyone who has it.</li><li>It can’t be <strong>revoked</strong> once issued (unless you track it externally).</li><li>If it gets stolen, it’s essentially a <em>golden ticket</em> until it expires.</li></ul><p>And worse — JWTs <strong>can be spoofed</strong> if your server blindly trusts them without context.</p><p>In this article, we’ll go deep into <strong>how JWTs actually work</strong>, why they’re inherently vulnerable, and how you can build a <strong>context-aware, device-bound authentication system</strong> that can survive session hijacking attempts.</p><h3>JWT 101 — and the First Misconception</h3><p>Let’s get something out of the way: <strong>JWT is not encryption</strong>.</p><p>A JWT has three parts:</p><pre>header.payload.signature</pre><ul><li><strong>Header</strong> → algorithm + token type</li><li><strong>Payload</strong> → claims (user_id, email, etc.)</li><li><strong>Signature</strong> → signed with your secret (HMAC) or private key (RSA/ECDSA)</li></ul><p>Encoding is <strong>not</strong> encryption. If I get your token, I can atob the payload and read all your claims. The signature only prevents tampering — it does <strong>not</strong> stop me from using the token if I stole it intact.</p><h3>The Revocation Problem</h3><p>Statelessness is a selling point for JWTs:</p><blockquote><em>No DB lookups, just verify the signature and you’re done.</em></blockquote><p>The problem? If a JWT is stolen, the server has no idea. It has no state to compare against. The attacker can use it until expiry.</p><p>That’s why <strong>revocation</strong> requires <strong>state</strong> — either a database or a cache to track valid/invalid tokens.</p><h3>Binding JWTs to the Device</h3><p>Here’s where we get into <strong>fingerprinting</strong>.<br> Instead of trusting the JWT on its own, we <strong>embed a device-bound signature into the payload</strong> and generate a <strong>session_id</strong> verify it on every request.</p><h4>How the Signature Works</h4><p>When the token is created, we generate a fingerprint:</p><pre>const signature = md5(ipAddress + device_id + userAgent)<br>const session_id = uuid4()</pre><p>This hash is stored inside the JWT payload <strong>and session_id </strong>in our Devices table:</p><pre>model Devices {<br> device_id String @id<br> refresh_session_id String // referencing latest active refresh token<br> access_session_id String? // referencing latest active access token<br> agent String<br> user_id String<br> geolocation String?<br> user User @relation(fields: [user_id], references: [id])<br> created_at DateTime @default(now())<br> updated_at DateTime @updatedAt<br> deleted_at DateTime?<br>@@map(&quot;devices&quot;)<br>}</pre><p>Now, every request must match:</p><ul><li>The JWT’s embedded fingerprint hash</li><li>The server’s calculated hash from the current IP, device_id, and userAgent</li></ul><p>If they don’t match → <strong>reject the request</strong>.</p><h3>The Middleware Flow</h3><ol><li><strong>Extract fingerprint from request</strong><br> (ipAddress, device_id, userAgent, optional geo)</li><li><strong>Verify JWT</strong> (check signature + expiry)</li><li><strong>Compare fingerprint hash</strong> from request vs JWT payload</li><li><strong>Lookup device session</strong> (DB or cache)</li><li><strong>If valid → proceed, else → block</strong></li></ol><pre>import geoip from &quot;geoip-lite&quot;;<br>const clientIp = req.ip || req.socket.remoteAddress; // should be present by default<br>const geolocation = geoip.lookup(ipAddress); <br>const userAgent = req.headers[&#39;user-agent&#39;]; // sent by default from all browser <br>const deviceId = req.headers[&#39;x-device-id&#39;]; // custom header client has to send<br>req.fingerprint = {<br>  agent: userAgent,<br>  device_id: deviceId,<br>  ipAddress: clientIp,<br>  geolocation<br>};</pre><h4>The example flow</h4><pre>import { UNAUTHORIZED } from &quot;http-status&quot;; <br>import { md5 } from &quot;js-md5&quot;;<br>import jwt from &quot;jsonwebtoken&quot;;<br><br>// authService: standard verification of JWT utility function<br>export const verifyToken = (token: string): { payload: tokenMetaData | null; expired: boolean } =&gt; {<br>  try {<br>    return {<br>      // inteface of tokenMetaData {user_id, singautre, session_id}<br>      payload: jwt.verify(token, JWT_SECRET) as tokenMetaData,<br>      expired: false,<br>    };<br>  } catch (e) {<br>    let expired = false;<br>    if (e instanceof jwt.TokenExpiredError) {<br>      logger.error(`Token expired`, { error: e, serviceName: &quot;auth-service&quot; });<br>      expired = true;<br>    } else {<br>      logger.error(`failed to verify token`, { error: e, serviceName: &quot;auth-service&quot; });<br>    }<br>    return { payload: null, expired };<br>  }<br>};<br><br>// device service getDeviceByAccessSessionId example<br> async getDeviceByAccessSessionId(user_id: string, sessionId: string) {<br>    return await this.prisma.devices.findFirst({<br>      where: { user_id, access_session_id: sessionId },<br>      select: {<br>        device_id: true,<br>        agent: true,<br>        access_session_id: true,<br>        user: {<br>          select: selectAbstractUserFields,<br>        },<br>      },<br>    });<br>  }<br><br>const token = req.headers.authorization.split(&quot; &quot;)[1]; // sent through header <br>// step 1 validate token<br>const { payload, expired } = authService.verifyToken(token);<br> if (!payload || expired) {<br>      logger.error(`failed to verify token`, {<br>        serviceName: &quot;authenticate&quot;,<br>        isExpired: expired,<br>        url: req.url,  <br>      });<br>      res<br>        .status(UNAUTHORIZED)<br>        .send({ message: &quot;failed to authenticate user, please login again&quot; });<br>      return;<br>    }<br><br>// step 2 validate md5 digital signature<br>const isValidHash = md5(`${req.fingerprint.agent.trim()}${req.fingerprint.device_id.trim()}${req.fingerprint.ipAddress.trim()}`)<br>=== payload.fingerprint<br><br>if (!isValidHash) {<br>  return res.status(405).send({ message: &quot;failed to authenticate&quot; });<br>}<br><br>// step 3 get user from db using sessionId and make sure session is active<br>const device = await deviceService.getDeviceByAccessSessionId(payload.user_id, payload.session_id);<br> if (!device) {<br>      logger.error(`failed to get device`, {<br>        serviceName: &quot;authenticate&quot;,<br>        url: req.url,     <br>        userId: payload.user_id,<br>      });<br>      res.status(UNAUTHORIZED).send({ message: &quot;failed to authenticate user, please login again&quot; });<br>      return;<br>   }</pre><h4>why Verifying Fingerprint?</h4><p>Imagine an attacker steals your JWT via XSS or localStorage theft.<br> If they try to use it from a different IP/device:</p><ul><li>The fingerprint won’t match.</li><li>The request will be rejected.</li></ul><p>They will be scratching their heads because they are sure they are mimicking your behavior, but don&#39;t know why it is not working. This doesn’t just protect against token replay — it <strong>binds the token to the original environment</strong>.</p><h4>Device Management: Netflix-Style</h4><p>Since every JWT is tied to a device_id and session_id, we can:</p><ul><li><strong>List active devices</strong> per user</li><li><strong>Revoke a specific device</strong> (kills access/refresh tokens for that session)</li><li><strong>Support multiple devices</strong> per account</li></ul><p>This means you can give users a “log out from all other devices” button — and actually make it work.</p><h4>Performance Considerations</h4><p>Checking the DB on every request is expensive. Two solutions:</p><ul><li><strong>low latency </strong>→ Use Redis for active session lookups</li><li><strong>high security </strong>→ Full DB lookup (security &gt; latency)</li></ul><p>in short it depends… everything in software has tradeoffs and it is up to you as a software engineer to assess situation and decide what suits you best.</p><p><strong>Example</strong></p><p>Fintech / Banking -&gt; Full fingerprint match + DB lookup</p><p>SaaS AppsFingerprint match + Redis lookup</p><p>Low-Security AppsDevice_id + User-Agent only (skip IP match)</p><h3>Key Takeaways</h3><ul><li>JWTs are <strong>readable</strong> and <strong>cannot be revoked</strong> without state.</li><li>Binding them to a device fingerprint prevents session hijacking.</li><li>Device/session tracking enables per-device control and revocation.</li><li>Performance trade-offs matter — tune them to your domain.</li></ul><p>JWTs aren’t broken — they’re just <strong>half the story</strong>.<br> Add context, add state, and you turn them into something truly secure.</p><h3>Bonus Tips for Frontend side:</h3><ul><li>RefreshToken should be saved in cookie; http-only and encrypted storage in browser and key chain in mobile apps</li><li>RefreshToken to be used for refreshing accessToken and it is better to geenrate new refreshToken when it is used for refreshing</li><li>AccessToken should have a short life span maybe 15–60 mins</li></ul><h3>References</h3><ul><li><a href="https://www.vaadata.com/blog/jwt-json-web-token-vulnerabilities-common-attacks-and-security-best-practices/">JWT: Vulnerabilities, Attacks &amp; Security Best Practices</a></li><li><a href="https://snyk.io/blog/top-3-security-best-practices-for-handling-jwts/">Top 3 security best practices for handling JWTs | Snyk</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a92c66a5f270" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Async Really Works in Node.js and FastAPI (and How to Stop Blocking Your Backend)]]></title>
            <link>https://abesolyman.medium.com/how-async-really-works-in-node-js-and-fastapi-and-how-to-stop-blocking-your-backend-6b6394cfdc21?source=rss-89c99f8915cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b6394cfdc21</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abdelrahman Soliman]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 10:32:05 GMT</pubDate>
            <atom:updated>2025-08-10T10:32:05.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIlFgEbIdNyS5gcK6NtD3A.png" /><figcaption>How asnyc really works in node and python</figcaption></figure><h3>Why This Matters</h3><p>You’ve just deployed your shiny new API. Users hit /get-data and—boom—it feels <strong>fast</strong>. Until one day, a slow database query hits production, and suddenly every request hangs.<br> You check your code:</p><pre>// Node js<br>return await db.getData();</pre><pre># FastAPI<br>return await db.get_data()</pre><p>You <em>think</em> async means “non-blocking.” So why does everything slow down?<br> The problem: <strong>await</strong> doesn’t magically guarantee your backend is safe from bottlenecks.<br> To understand why, you need to know how Node.js and Python’s <strong>asyncio</strong> run your code.</p><h3>Async ≠ Multithreading</h3><p>Before diving into language differences, a core truth:</p><ul><li>Async is about <strong>cooperative multitasking</strong> — tasks take turns when they hit await or yield points.</li><li>If you’re inside a long-running CPU loop, <strong>nothing else runs</strong> until you give up control.</li></ul><p>Both Node.js and Python’s async frameworks use a <strong>single-threaded event loop</strong> for your async code. The “magic” happens when you do something like:</p><ul><li>Make a DB query over the network</li><li>Call an HTTP API</li><li>Read from disk</li></ul><p>Those operations hand control back to the loop while the OS or a worker thread waits for the data.</p><p>Imagine you are making breakfast, you want to boil some eggs and make hot coffee. So you put eggs in the water and turn on the heat. That is like await boil_eggs() so, you are free to go make your coffee till the eggs are ready.</p><h3>The Event Loop: Node.js vs Python</h3><h4>Node.js</h4><ul><li><strong>Single JS thread</strong> + <strong>libuv</strong> (C library for async I/O)</li><li>Two queues:</li><li><strong>Macrotasks</strong> (timers, I/O callbacks)</li><li><strong>Microtasks</strong> (Promises, async/await continuations)</li><li>When you await A Promise, Node pauses your function, lets other tasks run, and resumes when the Promise resolves.</li></ul><h4>Python (asyncio / FastAPI)</h4><ul><li><strong>One event loop per thread</strong></li><li>Schedules <strong>Tasks</strong> (wrappers for coroutines)</li><li>No “microtask vs macrotask” visible to you — just cooperative yielding via await.</li><li>If you call the blocking code inside async def, the loop is frozen until that call returns.</li></ul><h3>When await Is Safe (and When It’s Not)</h3><h4>Safe in Node.js</h4><pre>// Async DB driver — does NOT block the event loop<br>app.get(&quot;/data&quot;, async (req, res) =&gt; {<br>  const result = await db.query(&quot;SELECT * FROM users WHERE id=$1&quot;, [req.query.id]);<br>  res.json(result.rows);<br>});</pre><ul><li>DB I/O happens in libuv’s thread pool.</li><li>Other requests can be served while waiting.</li></ul><h4>Unsafe in Node.js</h4><pre>// CPU-bound JSON transformation — BLOCKS event loop<br>const rows = await db.query(&quot;SELECT * FROM big_table&quot;);<br>const transformed = rows.map(row =&gt; heavyTransform(row)); // 🔴 stalls everything</pre><p><strong>Fix</strong>: Move CPU work to a Worker Thread.</p><pre>import { Worker } from &quot;node:worker_threads&quot;;<br>function heavyTransformInWorker(data) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const worker = new Worker(&quot;./transform.js&quot;, { workerData: data });<br>    worker.on(&quot;message&quot;, resolve);<br>    worker.on(&quot;error&quot;, reject);<br>  });<br>}</pre><h4>Safe in FastAPI</h4><pre># Async DB driver like asyncpg or SQLAlchemy Async<br>@app.get(&quot;/data&quot;)<br>async def get_data(session: AsyncSession = Depends(get_async_session)):<br>    result = await session.execute(text(&quot;SELECT * FROM users WHERE id=:id&quot;), {&quot;id&quot;: 123})<br>    return dict(result.first())</pre><ul><li>While the DB query is running, the loop handles other requests.</li></ul><h4>Unsafe in FastAPI</h4><pre># Sync DB driver inside async def — BLOCKS the loop<br>def sync_db_call(rows):<br>  transformed = [heavyTransform(row) for row in rows]<br><br>@app.get(&quot;/data&quot;)<br>async def get_data(session: AsyncSession = Depends(get_async_session)):<br>    rows = await session.execute(text(&quot;SELECT * FROM users WHERE id=:id&quot;), {&quot;id&quot;: 123})<br>    return sync_db_call(rows)  # 🔴 stops all other requests</pre><p><strong>Fix 1</strong>: Use a sync route — FastAPI runs it in a thread pool automatically.</p><pre>@app.get(&quot;/data&quot;)<br>def get_data():<br>    return sync_db_call()</pre><p><strong>Fix 2</strong>: Keep async def but explicitly offload.</p><pre>import anyio<br>@app.get(&quot;/data&quot;)<br>async def get_data():<br>    return await anyio.to_thread.run_sync(sync_db_call)</pre><h3>Best Practices for a Resilient Node and FastAPI backend</h3><h3>1. Connection Pools and Concurrency Limits</h3><p><strong>Why it matters: </strong>Even if each call is non-blocking, too many at once can overload your DB. That is why using these libraries limits the concurrency to avoid this issue. Downside is you are increasing your latency, but everything has a tradeoff.</p><h4>Node.js</h4><pre>import pLimit from &quot;p-limit&quot;;<br>const limit = pLimit(50);<br><br>app.get(&quot;/bulk-data&quot;, async (req, res) =&gt; {<br>  const ids = req.query.ids;<br>  const results = await Promise.all(<br>    ids.map(id =&gt; limit(() =&gt; db.query(&quot;SELECT * FROM users WHERE id=$1&quot;, [id])))<br>  );<br>  res.json(results);<br>});</pre><h4>FastAPI</h4><pre>sem = asyncio.Semaphore(50)<br><br>@app.get(&quot;/bulk-data&quot;)<br>async def bulk_data(ids: list[int], session: AsyncSession = Depends(...)):<br>    async def get_one(id):<br>        async with sem:<br>            result = await session.execute(text(&quot;SELECT * FROM users WHERE id=:id&quot;), {&quot;id&quot;: id})<br>            return dict(result.first())<br>    return await asyncio.gather(*(get_one(i) for i in ids))</pre><h3>2. Timeouts and Cancellation</h3><p><strong>Why it matters :</strong>A good pratice is setting timeouts and cancellations on async opeartions to avoid them from stalling too long. these example libraries should help</p><h4>Node.js</h4><pre>import fetch from &quot;node-fetch&quot;;<br>const ac = new AbortController();<br>setTimeout(() =&gt; ac.abort(), 2000); // 2s timeout<br>try {<br>  const res = await fetch(&quot;https://api.example.com/data&quot;, { signal: ac.signal });<br>  console.log(await res.json());<br>} catch (err) {<br>  if (err.name === &quot;AbortError&quot;) console.log(&quot;Timed out&quot;);<br>}</pre><h4>FastAPI / Python</h4><pre>import asyncio, aiohttp<br>async with aiohttp.ClientSession() as session:<br>    try:<br>        async with asyncio.timeout(2):<br>            async with session.get(&quot;https://api.example.com/data&quot;) as resp:<br>                print(await resp.json())<br>    except asyncio.TimeoutError:<br>        print(&quot;Timed out&quot;)</pre><h3>3. Keep transactions short</h3><p><strong>Why it matters: </strong>Long transactions hold locks, bloat MVCC tables (e.g., Postgres), increase contention, and amplify retries/deadlocks. Async won’t save you if the DB is waiting on locks.</p><p><strong>Guidelines</strong></p><ul><li>Do <strong>validation and computation before</strong> BEGIN. Keep only the <em>minimal</em> critical section inside the transaction.</li><li>Touch rows in a <strong>consistent order</strong> to avoid deadlocks.</li><li>Prefer <strong>narrow </strong><strong>SELECT lists</strong> and <strong>proper indexes</strong> to reduce row locks and I/O.</li><li>Use <strong>SELECT … FOR UPDATE</strong> only when you truly need it, and keep the guarded work tiny.</li><li>Set <strong>per-statement timeouts</strong> and <strong>retry</strong> only for safe, idempotent operations.</li></ul><h3>4. Use caching for frequent heavy reads</h3><p><strong>Why it matters:</strong> Caches remove repeated load from your primary DB, smooth spikes, and cut tail latency. The async angle: you still await, but the work is now memory-fast, not disk/network-slow, this doesnt just imply to DB, but any frequent heavy read.</p><p><strong>Guidelines</strong></p><ul><li><strong>Cache-aside (lazy-loading):</strong> read: check cache → miss → read DB → set cache → return. write: update DB → invalidate/refresh cache.</li><li><strong>TTL</strong> to prevent staleness; combine with <strong>versioned keys</strong> or <strong>tags</strong> for targeted invalidation.</li><li><strong>Stampede protection:</strong> use locks/single-flight so only one request recomputes on a miss.</li></ul><p><strong>Node (ioredis) cache-aside with single-flight</strong></p><pre>import Redis from &quot;ioredis&quot;;<br>import pLimit from &quot;p-limit&quot;;<br>const redis = new Redis();<br>const rebuildLimit = pLimit(1); // single-flight per key (simple)<br><br>async function getUserCached(id) {<br>  const key = `user:v1:${id}`;<br>  const cached = await redis.get(key);<br>  if (cached) return JSON.parse(cached);<br>  return rebuildLimit(async () =&gt; {<br>    // double-check once inside lock<br>    const again = await redis.get(key);<br>    if (again) return JSON.parse(again);<br>    const row = await db.query(&quot;SELECT id,name,tier FROM users WHERE id=$1&quot;, [id]);<br>    const val = JSON.stringify(row.rows[0]);<br>    await redis.set(key, val, &quot;EX&quot;, 300); // 5m TTL<br>    return row.rows[0];<br>  });<br>}</pre><p><strong>FastAPI (aioredis)</strong></p><pre>import json, asyncio<br>from redis.asyncio import Redis<br>redis = Redis()<br>async def get_user_cached(session, user_id: int):<br>    key = f&quot;user:v1:{user_id}&quot;<br>    if (raw := await redis.get(key)):<br>        return json.loads(raw)<br>    lock = redis.lock(f&quot;lock:{key}&quot;, timeout=5)<br>    async with lock:  # stampede protection<br>        if (raw := await redis.get(key)):  # double-check<br>            return json.loads(raw)<br>        row = (await session.execute(text(<br>            &quot;SELECT id, name, tier FROM users WHERE id=:id&quot;<br>        ), {&quot;id&quot;: user_id})).first()._asdict()<br>        await redis.set(key, json.dumps(row), ex=300)<br>        return row</pre><p><strong>Invalidation options</strong></p><ul><li>Write-through update the cache <em>after</em> successful DB write.</li><li>Publish/subscribe <strong>cache-busting events</strong> (e.g., user:123 updated) consumed by all app instances.</li><li>For complex aggregates, use <strong>materialized views</strong> or <strong>async background rebuilders</strong> keyed by version.</li></ul><h3>5. Monitor event-loop lag (Node libuv delay, Python loop time)</h3><p><strong>Why it matters:</strong> Even with async I/O, CPU spikes or accidental blocking code can starve the loop. Measuring “how late” the loop runs scheduled work reveals bottlenecks early.</p><p><strong>Node</strong></p><ul><li>great article about <a href="https://medium.com/@priteymehta9/perf-hooks-in-nodejs-303fd1c8bfb7">perf_hooks</a></li><li>Use perf_hooks.monitorEventLoopDelay() or a simple drift probe.</li></ul><pre>import { monitorEventLoopDelay } from &quot;node:perf_hooks&quot;;<br>import express from &quot;express&quot;;<br>const app = express();<br>const h = monitorEventLoopDelay({ resolution: 10 });<br>h.enable();<br>app.get(&quot;/metrics&quot;, (req, res) =&gt; {<br>  // expose p50/p95/p99 in milliseconds<br>  res.type(&quot;text/plain&quot;).send(<br>    `node_event_loop_lag_seconds{quantile=&quot;0.5&quot;} ${h.percentile(50)/1e9}\n` +<br>    `node_event_loop_lag_seconds{quantile=&quot;0.95&quot;} ${h.percentile(95)/1e9}\n` +<br>    `node_event_loop_lag_seconds{quantile=&quot;0.99&quot;} ${h.percentile(99)/1e9}\n`<br>  );<br>});</pre><p><strong>Alerts:</strong> p95 &gt; ~100–200 ms under normal load is a smell. Check for sync code, large JSON transforms, or GC pressure.</p><p><strong>Python / FastAPI</strong></p><p>Probe loop drift with asyncio scheduling and export as a metric.</p><pre>import asyncio, time<br>from fastapi import FastAPI, Response<br>app = FastAPI()<br>lag_stats = {&quot;p95&quot;: 0.0, &quot;p99&quot;: 0.0}<br>samples = []<br>async def loop_probe():<br>    # schedule a tick every 100ms and measure delay<br>    interval = 0.1<br>    next_t = time.perf_counter() + interval<br>    while True:<br>        await asyncio.sleep(max(0, next_t - time.perf_counter()))<br>        delay = time.perf_counter() - next_t<br>        samples.append(delay)<br>        # keep last N samples<br>        if len(samples) &gt; 600:  # ~1 minute<br>            del samples[: len(samples) - 600]<br>        # update cheap percentiles<br>        sorted_s = sorted(samples)<br>        if sorted_s:<br>            lag_stats[&quot;p95&quot;] = sorted_s[int(0.95 * (len(sorted_s)-1))]<br>            lag_stats[&quot;p99&quot;] = sorted_s[int(0.99 * (len(sorted_s)-1))]<br>        next_t += interval<br>@app.on_event(&quot;startup&quot;)<br>async def _startup():<br>    asyncio.create_task(loop_probe())<br>@app.get(&quot;/metrics&quot;)<br>async def metrics():<br>    body = (<br>        f&#39;python_event_loop_lag_seconds{{quantile=&quot;0.95&quot;}} {lag_stats[&quot;p95&quot;]}\n&#39;<br>        f&#39;python_event_loop_lag_seconds{{quantile=&quot;0.99&quot;}} {lag_stats[&quot;p99&quot;]}\n&#39;<br>    )<br>    return Response(content=body, media_type=&quot;text/plain&quot;)</pre><ul><li>If lag spikes: inspect for blocking sync calls, large response serialization, or CPU-heavy tasks that belong in a <strong>ProcessPoolExecutor</strong>.</li></ul><h3>Checklist: Keeping Your Backend Async-Friendly</h3><p>✅ Use async-native DB drivers where possible<br> ✅ Offload CPU-heavy tasks (Worker Threads in Node, process pool in Python)<br> ✅ Limit concurrency to avoid DB overload<br> ✅ Add timeouts and handle cancellations<br> ✅ Keep transactions short<br> ✅ Use caching for frequent reads<br> ✅ Monitor event-loop lag (libuv delay in Node, loop time in Python)</p><h3><strong>Conclusion</strong></h3><ul><li>await pauses <strong>your function</strong>, not the whole server — <em>if</em> the awaited thing is truly async I/O.</li><li>Both Node.js and FastAPI can serve other requests during awaits.</li><li>Mixing sync work into async routes is the main way you accidentally block everything.</li><li>Use pools, concurrency limits, and proper async libraries to keep your API responsive under load.</li></ul><h3>References</h3><ul><li>Perf Hooks: <a href="https://medium.com/@priteymehta9/perf-hooks-in-nodejs-303fd1c8bfb7">https://medium.com/@priteymehta9/perf-hooks-in-nodejs-303fd1c8bfb7</a></li><li>Python async made easy: <a href="https://www.aeracode.org/2018/02/19/python-async-simplified/">https://www.aeracode.org/2018/02/19/python-async-simplified/</a></li><li>what the heck is event loop anyway: <a href="https://www.voicetube.com/videos/164491/59695294">https://www.voicetube.com/videos/164491/59695294</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b6394cfdc21" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>