<?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"><channel><title><![CDATA[Prashant Singh]]></title><description><![CDATA[Prashant Singh]]></description><link>https://kodeshaastra.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/64fc95e0466db6993c871305/93091b97-4c34-4187-bf34-d01fffd18792.webp</url><title>Prashant Singh</title><link>https://kodeshaastra.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:21:25 GMT</lastBuildDate><atom:link href="https://kodeshaastra.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[One Node app, many workers: why my rate limiter needed Redis]]></title><description><![CDATA[Node cluster + a Redis rate limiter with a Lua script, explained simply]]></description><link>https://kodeshaastra.hashnode.dev/one-node-app-many-workers-why-my-rate-limiter-needed-redis</link><guid isPermaLink="true">https://kodeshaastra.hashnode.dev/one-node-app-many-workers-why-my-rate-limiter-needed-redis</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Redis]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[backend]]></category><category><![CDATA[System Design]]></category><dc:creator><![CDATA[Prashant Singh]]></dc:creator><pubDate>Tue, 01 Dec 2026 19:07:01 GMT</pubDate><content:encoded><![CDATA[<p>I wanted to learn two things. First, how one small Express app can use <strong>all</strong> of my computer's power. Second, how to limit requests when many copies of that app run at the same time.</p>
<p>So I wrote a tiny practice app and broke it a few times. This post is what I wish someone had told me on day one. You don't need to know cluster or Redis to read it. I'll explain every new word when we reach it.</p>
<h2>Before we start: open my code next to this post</h2>
<p>This post is much easier to follow with my code open on one side and this post on the other. You don't have to, but it really helps.</p>
<pre><code class="language-bash">git clone https://github.com/KodeShaastra/UrlShortner.git
cd UrlShortner
npm install
</code></pre>
<p>You also need Node 20 or newer, and Redis running on your machine. Don't worry if you've never installed Redis. If you have Docker, this one line is enough:</p>
<pre><code class="language-bash">docker run -d -p 6379:6379 redis
</code></pre>
<p>(No Docker? Search "install Redis" for your system. On Ubuntu it's <code>sudo apt install redis-server</code>.)</p>
<p>Now start the app:</p>
<pre><code class="language-bash">node cluster.js
</code></pre>
<p>Then, in a second terminal, run this 6 times:</p>
<pre><code class="language-bash">curl localhost:3000/health
</code></pre>
<p>You'll see a different <code>pid</code> in almost every answer, and the 6th call says "Too many requests". Don't worry if that means nothing yet. By the end of this post, you'll know exactly why both happen.</p>
<h3>The 5 files, and the journey of one request</h3>
<p>The whole app is just 5 small files. Here they are in the order a request moves through them:</p>
<ol>
<li><strong><code>cluster.js</code></strong>: the starting point. It starts one worker per CPU core. (Step 1)</li>
<li><strong><code>server.js</code></strong>: every worker runs this. It connects to Redis, then opens port 3000.</li>
<li><strong><code>app.js</code></strong>: the routes. <code>/health</code> lives here.</li>
<li><strong><code>rateLimiter.js</code></strong>: runs before <code>/health</code> and decides: let the request in, or say "Too many requests". (Steps 2 to 4)</li>
<li><strong><code>redis.js</code></strong>: the connection to Redis. Each worker makes its own connection, but they all talk to the same Redis.</li>
</ol>
<p>So one request goes like this: a worker picks it up, <code>app.js</code> finds the <code>/health</code> route, <code>rateLimiter.js</code> asks Redis "how many times has this IP called?", and the worker either answers with its pid or says "Too many requests".</p>
<p>Keep this list in mind. Every code piece below says which file it comes from, so you can jump to the full code any time.</p>
<h2>The problem</h2>
<p>Node runs your JavaScript on just <strong>one CPU core</strong>. My laptop has 16. So when I start a normal <code>node server.js</code>, 15 cores just sit there doing nothing.</p>
<p>If "CPU core" sounds scary, don't worry. Think of a core as one worker that can do one job at a time. Every machine has its own number of them, and mine has 16. You can learn more about cores later. For now, keep just this in mind: I have many workers, and Node uses only one. That is the problem I wanted to fix while learning cluster and Redis, so hold on to that idea as you read.</p>
<h2>Step 1: One manager, many workers</h2>
<p>Node has a built-in tool for this called <strong>cluster</strong>. The idea is simple. Think of a bank:</p>
<ul>
<li>There is <strong>one manager</strong>. The manager doesn't serve customers.</li>
<li>The manager opens <strong>one counter per core</strong>, and puts a worker at each counter.</li>
<li>Customers (requests) come in, and each one is sent to a free counter.</li>
</ul>
<p>In Node, the manager is called the <strong>primary</strong> process, and each counter is a <strong>worker</strong> process. All of them run from the same file. So the first thing the file asks is: "Am I the manager, or a worker?"</p>
<p>From <code>cluster.js</code> (shortened):</p>
<pre><code class="language-js">if (cluster.isPrimary) {
  // I am the manager: open the counters
} else {
  // I am a worker: serve customers
}
</code></pre>
<p><strong>The manager's job:</strong> count the cores, then start one worker for each. Also from <code>cluster.js</code>:</p>
<pre><code class="language-js">const cores = os.availableParallelism(); // 16 on my laptop

for (let i = 0; i &lt; cores; i++) {
  cluster.fork(); // start one worker
}
</code></pre>
<p><code>os.availableParallelism()</code> just means "how many cores can I use?". And <code>fork()</code> means "start another copy of this same file, as a worker". When that copy starts, <code>cluster.isPrimary</code> is false, so it goes into the <code>else</code> part.</p>
<p><strong>The worker's job:</strong> run the normal app. This is the <code>else</code> part of <code>cluster.js</code>:</p>
<pre><code class="language-js">require("./server");
</code></pre>
<p><code>server.js</code> is nothing special. It's my normal Express app that starts listening on port 3000. Every worker runs it. You might ask: "Can 16 programs use port 3000 at the same time?" With cluster, yes. The manager holds the port and hands each incoming request to a worker.</p>
<p><strong>One more manager job:</strong> if a worker dies, start a new one. From <code>cluster.js</code> (shortened):</p>
<pre><code class="language-js">cluster.on("exit", (worker) =&gt; {
  console.log(`Worker ${worker.process.pid} died`);
  cluster.fork(); // put a new worker at that counter
});
</code></pre>
<p>This is why my logs say "Starting a replacement worker". I tested it by killing one worker on purpose:</p>
<pre><code>Worker 1116517 died
Starting a replacement worker...
Server running on port 3000 | PID: 1116865
</code></pre>
<p>That number is a <strong>pid</strong> (process id). Linux gives every running program its own number, like a token number at the bank. A new pid means a new worker.</p>
<p>To <strong>see</strong> which worker answered a request, I made a small <code>/health</code> route that sends back its pid. From <code>app.js</code> (without the rate limiter for now, it comes in Step 4):</p>
<pre><code class="language-js">app.get("/health", (req, res) =&gt; {
  res.json({ status: "ok", pid: process.pid });
});
</code></pre>
<p>Now the workers are running. Let's add the second thing I wanted to learn.</p>
<h2>Step 2: Rate limiting, and why a normal counter breaks</h2>
<p><strong>Rate limiting</strong> means a rule like: "one person can call my API only 5 times a minute." It stops one user (or a bot) from flooding the server.</p>
<p>The easy way is to count requests in a normal JavaScript object. This is not in my repo. It's the idea that doesn't work:</p>
<pre><code class="language-js">// ❌ This breaks with cluster
const counts = {}; // { "1.2.3.4": 3 } → this IP made 3 requests
</code></pre>
<p>Here is the catch. Each worker is a <strong>separate program with its own memory</strong>. With 16 workers, there are 16 separate <code>counts</code> objects, and they never talk to each other.</p>
<p>Back to the bank: 16 counters, and each cashier keeps their <strong>own notebook</strong> of "who came how many times". A customer who hits the limit at counter 1 just walks to counter 2. So one user could make 5 × 16 = 80 requests instead of 5.</p>
<p><strong>The fix: keep one notebook that every worker can see.</strong> That's where Redis comes in.</p>
<h2>Step 3: Redis, the shared notebook</h2>
<p>If you haven't used Redis, don't worry. For this post, think of it as <strong>one shared whiteboard</strong> that all 16 workers can read and write. It's a separate program running next to the app, and it's very fast because it keeps data in memory.</p>
<p>For each IP, I write one line on the whiteboard, like <code>rate_limit:1.2.3.4</code>. That name is called a <strong>key</strong>, and its value is the count.</p>
<p>On every request, a worker does 3 things. This one isn't in my repo either. It's the simple version, and Step 4 shows why I changed it:</p>
<pre><code class="language-js">const count = await redisClient.incr(key);       // 1. add 1 to the count
if (count === 1) await redisClient.expire(key, 60); // 2. first request? wipe it after 60 seconds
if (count &gt; 5) return res.status(429).send("Too many requests"); // 3. over the limit? stop
</code></pre>
<p>In plain words:</p>
<ol>
<li><strong><code>incr</code></strong> = "add 1 to this key". If the key doesn't exist yet, Redis creates it with 1.</li>
<li><strong><code>expire</code></strong> = "delete this key after 60 seconds". We set it only on the first request, so the 60-second window starts then. When the key is deleted, the count starts again from zero.</li>
<li><strong>429</strong> is the standard HTTP code for "Too Many Requests".</li>
</ol>
<p>Since all workers write to the same key, the limit is now 5 in total, not 5 per worker.</p>
<h2>Step 4: Why I used a Lua script</h2>
<p>The code above works most of the time. But look at it carefully: <code>incr</code> and <code>expire</code> are <strong>two separate messages</strong> to Redis. There is a small gap between them.</p>
<p>First, a good thing: <code>incr</code> on its own is safe. If two workers add 1 at the exact same moment, Redis does them one after the other, so they get 1 and 2. No count is lost.</p>
<p>The danger is the gap. What if the worker <strong>stops right after <code>incr</code></strong>, before it sends <code>expire</code>? It could crash, or lose its connection to Redis. Then:</p>
<ul>
<li>the key exists with count 1,</li>
<li>but nobody told Redis to delete it,</li>
<li>so it <strong>never resets</strong>, and after 5 requests that user is <strong>blocked forever</strong>.</li>
</ul>
<p>This won't happen often. But it only needs to happen once.</p>
<p>The fix is to send both steps to Redis as <strong>one job</strong>. Redis can run a small <strong>Lua</strong> script, and while it runs, nothing else can jump in between.</p>
<p>Don't worry, you don't need to learn Lua. This is all of it, from <code>rateLimiter.js</code>:</p>
<pre><code class="language-lua">local count = redis.call("INCR", KEYS[1])
if count == 1 then
    redis.call("EXPIRE", KEYS[1], ARGV[1])
end
return count
</code></pre>
<p>Line by line:</p>
<ul>
<li><code>redis.call("INCR", KEYS[1])</code> is the same <code>incr</code> as before. <code>KEYS[1]</code> is the key we send in, like <code>rate_limit:1.2.3.4</code>.</li>
<li>If this was the first request, set the expiry. <code>ARGV[1]</code> is the number we send in: 60 seconds.</li>
<li><code>return count</code> sends the new count back to our Node code.</li>
</ul>
<p>And this is how Node sends the script to Redis. From <code>rateLimiter.js</code> (shortened: the real code uses <code>WINDOW_SECONDS</code> and <code>MAX_REQUESTS</code> instead of 60 and 5):</p>
<pre><code class="language-js">const count = await redisClient.eval(script, {
  keys: [key],         // becomes KEYS[1]
  arguments: ["60"],   // becomes ARGV[1]
});

if (count &gt; 5) return res.status(429).json({ message: "Too many requests" });
next(); // under the limit: let the request through
</code></pre>
<p><code>eval</code> means "run this script inside Redis". Same 3 steps as before, but now steps 1 and 2 can never be split apart.</p>
<p>Last piece: how does the limiter run before <code>/health</code>? In <code>app.js</code>, it sits in front of the route:</p>
<pre><code class="language-js">app.get("/health", rateLimiter, (req, res) =&gt; { ... });
</code></pre>
<p>Express runs <code>rateLimiter</code> first. If it calls <code>next()</code>, the request moves on to the route. If it answers 429, the route never runs. A function that sits in front of a route like this is called <strong>middleware</strong>.</p>
<h2>Does it work? 5 workers, one shared limit</h2>
<p>I started the app and called <code>/health</code> 7 times:</p>
<pre><code>{"status":"ok","pid":1116517}  [HTTP 200]
{"status":"ok","pid":1116486}  [HTTP 200]
{"status":"ok","pid":1116463}  [HTTP 200]
{"status":"ok","pid":1116440}  [HTTP 200]
{"status":"ok","pid":1116511}  [HTTP 200]
{"message":"Too many requests. Please try again later."}  [HTTP 429]
{"message":"Too many requests. Please try again later."}  [HTTP 429]
</code></pre>
<p>Look at the pids. <strong>5 different workers</strong> answered the first 5 requests, and still the 6th one was blocked. No single worker saw 5 requests. Only the shared whiteboard did. Here is what Redis had:</p>
<pre><code>rate_limit:::1   value=7   ttl=60
</code></pre>
<p><code>::1</code> is just "localhost" (my own computer) written the new IPv6 way. <code>ttl</code> means "time to live": seconds left before Redis deletes the key.</p>
<h2>Two bugs I hit (so you don't have to)</h2>
<h3>1. The app "hung", but nothing crashed</h3>
<p>One day my app stopped answering. <code>curl</code> just waited forever. No error anywhere.</p>
<p>I listed my running programs with <code>ps</code>:</p>
<pre><code>ps -eo pid,ppid,pgid,stat,cmd | grep '[c]luster.js'
1161508 1004280 1161508 Tl   node cluster.js
1161517 1161508 1161508 Tl   node ...
1161518 1161508 1161508 Tl   node ...
</code></pre>
<p>Don't let this scare you. Look at only two columns:</p>
<ul>
<li><strong>STAT</strong> (4th column) is the program's state. <strong><code>T</code> means stopped</strong>, and every line had it.</li>
<li><strong>PGID</strong> (3rd column) is a "family id". The manager and all its workers share the same one.</li>
</ul>
<p>The cause: I had pressed <strong>Ctrl+Z</strong> in the terminal. Ctrl+Z doesn't quit a program. It <strong>pauses</strong> it, and it pauses the whole family: the manager and every worker.</p>
<p>The paused workers still held port 3000. So my request got in, but everyone at the counters was frozen.</p>
<p>The fix was to wake up the whole family. <code>CONT</code> means "continue", and the <code>-</code> before the number means "the whole family, not just one program":</p>
<pre><code>kill -CONT -- -1161508
</code></pre>
<p>Lesson: to stop a server, use <strong>Ctrl+C</strong>, not Ctrl+Z.</p>
<h3>2. <code>string</code> is not <code>String</code></h3>
<p>As soon as the workers woke up, I got:</p>
<pre><code>Rate limiter error: ReferenceError: string is not defined
</code></pre>
<p>I had typed <code>string("60")</code> instead of <code>String("60")</code>. JavaScript cares about capital letters. <code>String()</code> is built in, and <code>string()</code> doesn't exist. One capital letter.</p>
<h2>What to remember</h2>
<ul>
<li><strong>cluster</strong> = one manager, one worker per CPU core. The manager also replaces workers that die.</li>
<li>Workers <strong>don't share memory</strong>. So a counter for rate limiting must live in one shared place, like <strong>Redis</strong>.</li>
<li>Use a <strong>Lua script</strong> so "add 1" and "set expiry" always happen together, and no key is left that never resets.</li>
</ul>
<p>If you want to see the full code, it's here: <a href="https://github.com/KodeShaastra/UrlShortner">github.com/KodeShaastra/UrlShortner</a>. (The name is from where I started. Right now it's my playground for cluster and Redis.)</p>
]]></content:encoded></item><item><title><![CDATA[How I keep a map smooth with 100,000 points]]></title><description><![CDATA[Too many markers make Google Maps slow. Group points with Supercluster, draw only what's on screen, and render with deck.gl. Real numbers inside.]]></description><link>https://kodeshaastra.hashnode.dev/google-maps-100000-points-without-lag</link><guid isPermaLink="true">https://kodeshaastra.hashnode.dev/google-maps-100000-points-without-lag</guid><category><![CDATA[google maps]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[performance]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Prashant Singh]]></dc:creator><pubDate>Sun, 22 Nov 2026 19:41:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/64fc95e0466db6993c871305/4720ff0f-a328-4590-bca5-41cc80e29102.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>At work I build map widgets for dashboards: point maps, heatmaps and clustered markers on Google Maps. Some maps have to show a lot of points. Here is the simple way I keep them fast.</p>
<h2>The problem</h2>
<p>Say you have <strong>100,000 GPS points</strong> to show on a map.</p>
<p>If you draw every point:</p>
<ul>
<li>the browser has to handle 100,000 things, so the map gets slow when you move it;</li>
<li>and you can't read it anyway: zoomed out, it's just one big blob of dots.</li>
</ul>
<h2>The fix in one line</h2>
<p><strong>Don't draw every point. Group nearby points, draw only what's on the screen, and let the graphics card do the drawing.</strong></p>
<p>That's 3 steps.</p>
<h2>Step 1: Group nearby points (once)</h2>
<p>Points that are close together become one <strong>bubble</strong> with a number on it, like "38k".</p>
<p>A small library called <a href="https://github.com/mapbox/supercluster">Supercluster</a> does this. You give it all your points <strong>once</strong>, when the data loads:</p>
<pre><code class="language-ts">import Supercluster from "supercluster";

const index = new Supercluster({ radius: 60, maxZoom: 16 });

index.load(
  points.map((p) =&gt; ({
    type: "Feature" as const,
    properties: {},
    geometry: { type: "Point" as const, coordinates: [p.lng, p.lat] },
  })),
);
</code></pre>
<p>For 100,000 points this took about <strong>0.23 seconds</strong> on my laptop. Do it once, not every time the map moves. (In React, keep it in <code>useMemo</code>.)</p>
<h2>Step 2: Draw only what's on the screen</h2>
<p>When the user <strong>stops moving</strong> the map, ask Supercluster: <em>"What's inside this view, at this zoom?"</em></p>
<pre><code class="language-ts">map.addListener("idle", () =&gt; {
  const box = map.getBounds();
  if (!box) return;
  const sw = box.getSouthWest();
  const ne = box.getNorthEast();

  const visible = index.getClusters(
    [sw.lng(), sw.lat(), ne.lng(), ne.lat()], // west, south, east, north
    Math.round(map.getZoom() ?? 5),
  );

  draw(visible);
});
</code></pre>
<p>This is the magic part. Out of 100,000 points, here is how much actually gets drawn:</p>
<table>
<thead>
<tr>
<th>Map view</th>
<th>Drawn on screen</th>
</tr>
</thead>
<tbody><tr>
<td>All of India</td>
<td>7 bubbles</td>
</tr>
<tr>
<td>Delhi NCR</td>
<td>234</td>
</tr>
<tr>
<td>Central Delhi</td>
<td>184</td>
</tr>
<tr>
<td>Street level</td>
<td>37</td>
</tr>
</tbody></table>
<p>So you draw <strong>a few hundred things at most, never 100,000</strong>. And each answer takes less than 0.04 milliseconds.</p>
<h2>Step 3: Let the graphics card draw</h2>
<p><a href="https://deck.gl">deck.gl</a> draws using the graphics card (WebGL), on top of the normal Google map. That keeps moving and zooming smooth:</p>
<pre><code class="language-ts">import { GoogleMapsOverlay } from "@deck.gl/google-maps";
import { ScatterplotLayer } from "@deck.gl/layers";

const overlay = new GoogleMapsOverlay({ layers: [] });
overlay.setMap(map);

function draw(visible: ReturnType&lt;typeof index.getClusters&gt;) {
  overlay.setProps({
    layers: [
      new ScatterplotLayer({
        id: "dots",
        data: visible,
        getPosition: (d) =&gt; d.geometry.coordinates as [number, number],
        // Bigger bubble = more points inside it.
        getRadius: (d) =&gt; (d.properties.cluster ? 10 + Math.sqrt(d.properties.point_count) / 2 : 4),
        radiusUnits: "pixels",
        getFillColor: [45, 212, 191],
      }),
    ],
  });
}
</code></pre>
<p><strong>Nice extra:</strong> when someone clicks a bubble, <code>index.getClusterExpansionZoom(clusterId)</code> tells you how far to zoom in so that bubble splits into smaller ones.</p>
<h2>Bonus: don't pay Google twice for the same address</h2>
<p>Turning a GPS point into an address ("near Connaught Place") is a paid Google call. Field data visits the same places again and again, so remember what you already asked:</p>
<pre><code class="language-ts">const saved = new Map&lt;string, Promise&lt;string&gt;&gt;();

function getAddress(lat: number, lng: number) {
  const key = `${lat.toFixed(4)},${lng.toFixed(4)}`; // points ~11 m apart share one answer
  if (!saved.has(key)) {
    saved.set(key, askGoogle(lat, lng)); // save the request itself, not just the answer
  }
  return saved.get(key)!;
}
</code></pre>
<p>Because it saves the <em>request</em>, 10 table rows asking for the same place at the same time make <strong>1</strong> call, not 10. (I tested this.) In real code, also remove the key if the call fails, so it can try again. And check Google's terms before storing addresses for longer than a session.</p>
<h2>Summary</h2>
<ol>
<li><strong>Group</strong> nearby points into bubbles, once.</li>
<li><strong>Ask only for what's on screen</strong>, when the map stops moving.</li>
<li><strong>Draw with the graphics card</strong> using deck.gl.</li>
<li><strong>Remember addresses</strong> you already paid for.</li>
</ol>
<p><em>How I measured: 100,000 made-up points around eight Indian cities, Supercluster 8 on Node 24, on a laptop with an Intel Core i5-13500H. The code was checked with TypeScript against deck.gl 9.4.</em></p>
<hr />
<p>I build the data-heavy parts of SaaS products: dashboard builders, report builders and live maps. More about my work: <a href="https://kodeshaastra.github.io">kodeshaastra.github.io</a></p>
]]></content:encoded></item></channel></rss>