<?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 Rakesh Bhetariya on Medium]]></title>
        <description><![CDATA[Stories by Rakesh Bhetariya on Medium]]></description>
        <link>https://medium.com/@Rakeshbhetariya?source=rss-c337ee5c5072------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TEbb3nL9x_681OQkJd5qkA.png</url>
            <title>Stories by Rakesh Bhetariya on Medium</title>
            <link>https://medium.com/@Rakeshbhetariya?source=rss-c337ee5c5072------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:41:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Rakeshbhetariya/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[The 3 Things That Quietly Break Zoho Integrations (Tokens, Rate Limits, and Data Centers)]]></title>
            <link>https://medium.com/@Rakeshbhetariya/the-3-things-that-quietly-break-zoho-integrations-tokens-rate-limits-and-data-centers-2d6b6e616cae?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d6b6e616cae</guid>
            <category><![CDATA[odoo]]></category>
            <category><![CDATA[zoho-crm]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[zoho]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 19:25:39 GMT</pubDate>
            <atom:updated>2026-09-23T19:25:39.917Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s a particular kind of software failure that’s worse than the loud kind. The loud kind the thing that won’t even start, the error on day one is annoying but honest. You know immediately that something’s wrong, and you fix it before anyone relies on it.</p><p>The quiet kind is different. It works perfectly in the demo. It works for a week. Everyone’s happy, the client has moved on, you’ve moved on. And then one ordinary afternoon, weeks later, it just… stops. No warning, no obvious reason. The invoices stop pulling. The data stops syncing. And now it’s not a development task, it’s a production fire, because real people were depending on it.</p><p>Zoho integrations have three of these quiet failures built in, and I’ve watched every one of them catch developers off guard. None of them are hard to handle. All of them are invisible until they aren’t. If you’re connecting Zoho to anything a website, a custom app, an internal system these are the three landmines to defuse before you hand it over.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xSpNZGDmLRnPgbfbnHFUKQ.png" /></figure><h3>Landmine 1: The token that expires while you’re not looking</h3><p>Think of the access your app uses to talk to Zoho like a visitor’s badge at an office building. When your integration authenticates, Zoho hands it a badge that says “this app is allowed in.” Great. Your app walks in, does its job, everyone’s happy.</p><p>Here’s the catch nobody mentions at the front desk: that badge expires after about an hour. It’s supposed to. It’s a security feature a badge that worked forever would be dangerous if it ever leaked. So Zoho deliberately makes the access token short-lived.</p><p>In your demo, this never comes up. You build the integration, you test it, it works, you ship it all inside that first hour. The badge is still valid the whole time. Everything’s beautiful.</p><p>Then an hour passes. The badge expires. And if you built the integration to just hold onto that first badge and keep flashing it at the door, the door stops opening. Your integration “mysteriously” stops working, and because it worked fine at launch, nobody suspects the thing that was always going to happen.</p><p>The fix is simple once you know it exists: alongside the short-lived badge, Zoho also gives you a <em>refresh token </em>think of it as the paperwork that lets you quietly go get a new badge whenever the old one expires, without bothering anyone. A properly built integration uses that paperwork automatically, in the background, so it always has a fresh badge and never gets locked out. You never notice, because it just works.</p><p>So if you ever hear “the Zoho integration just stopped pulling data one day,” this is almost always the reason. Someone built it to hold one badge forever, and forever turned out to be about an hour.</p><h3>Landmine 2: The rate limit you sprint straight into</h3><p>The second one is about manners, and Zoho enforces them.</p><p>Imagine you walk up to a librarian and ask for a book. Fine. You ask for another. Fine. Now imagine you ask for ten thousand books as fast as you can shout the titles, over and over, all day. At some point the librarian reasonably holds up a hand and says “enough, come back later.” You’ve been cut off, not because your requests were wrong, but because there were too many, too fast.</p><p>Zoho’s API works the same way. There’s a limit on how many requests you can make both per minute and per day and the exact number depends on your plan. It’s there to stop any one integration from hammering Zoho into the ground. And here’s the trap: in testing, you never hit it. You’re one developer, clicking around, making a handful of requests. You’re nowhere near the limit, so you don’t even know it’s there.</p><p>Then the integration goes live in a real business. Now it’s not a handful of requests it’s every order, every customer, every sync, all day, at real volume. And if the integration was built carelessly asking Zoho for the same data over and over, fetching everything every time instead of just what changed, retrying aggressively when something fails it sprints straight into that limit. The librarian holds up a hand. And your integration stops working <em>at the busiest time of day</em>, which is the worst possible moment, because busy is exactly when you’re making the most requests.</p><p>The fix is to build with the limit in mind from the start: fetch efficiently, only ask for what’s actually changed, don’t repeat requests you don’t need, and back off gracefully instead of hammering when something’s slow. Basically, be a polite visitor to the library, not the person shouting for ten thousand books. Done right, you never come close to the limit and never think about it again.</p><h3>Landmine 3: The address that’s right in one country and wrong in another</h3><p>The third one is my favourite, because it’s the one that makes a perfectly good integration fail for reasons that feel like black magic until you know the trick.</p><p>Here’s the assumption almost everyone makes: that Zoho lives at one address on the internet. You build your integration pointing at that address, it works, you assume it’ll work for everyone. It’s a website; websites have one address, right?</p><p>Zoho doesn’t. Zoho runs across several regional data centers around the world one for the US, one for Europe, one for India, one for Saudi Arabia, one for Australia, and more. Each has its own address. And every Zoho account lives in exactly one of them, tied to the region it was set up in. An account in India lives at the India address; an account in Saudi Arabia lives at the Saudi address. They are not interchangeable.</p><p>You can probably see where this goes. You build and test your integration with your own Zoho account say, an Indian one pointing at the Indian address. It works flawlessly. You ship it. Then a client in the UAE or Saudi Arabia tries to use it, and it simply fails, because their account doesn’t live at the address your integration is knocking on. You’re knocking on the right door in the wrong city, and nobody’s home.</p><p>The maddening part is that everything <em>looks</em> correct. The credentials are right, the code is right, the logic is right it just fails, because it’s pointed at the wrong region. Developers can burn hours on this, convinced something’s broken, when nothing is broken except the address.</p><p>The fix is to never hard-code one region’s address as if it’s universal. Build the integration to use the right data center for the account it’s actually connecting to. It’s a small thing, a detail, but it’s the difference between an integration that works only for accounts in your country and one that works for a client anywhere in the world. If you’re building for international clients and if you’re anywhere near the Middle East, you will be this one isn’t optional.</p><h3>The pattern behind all three</h3><p>Notice what these three have in common. Every one of them works perfectly in the demo, and every one of them fails later, in production, for a reason that was invisible at build time. The token was always going to expire just not in the first hour. The rate limit was always there just not at test volume. The data center was always regional just not visible when you tested with your own account.</p><p>That’s the nature of the quiet failures: they’re not bugs you can see, they’re assumptions that hold right up until reality tests them. And reality always tests them, weeks after everyone stopped paying attention.</p><p>This is also, honestly, the difference between an integration that a developer <em>got working</em> and one that a developer <em>built to last</em>. Getting a Zoho integration working for an hour, at low volume, with your own account, is easy. Building one that refreshes its own access, respects the limits, and works for a client in any country that’s the actual job. The three landmines are exactly where that difference shows up.</p><p>So if you’re about to build a Zoho integration, defuse these three before you hand it over. Your future self, weeks from now, on the afternoon it would otherwise have quietly broken, will thank you.</p><p>I build custom software and Zoho integrations for businesses across India and the Middle East. I write about the practical details of building integrations that hold up in production including a fuller guide to <a href="https://www.rakeshbhetariya.com/blog/zoho-books-api-integration">connecting Zoho to a custom application</a>. More of my work at <a href="https://www.rakeshbhetariya.com/">rakeshbhetariya.com</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d6b6e616cae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Rate Limiter: The Line of Code Juniors Skip and Seniors Never Forget]]></title>
            <link>https://medium.com/@Rakeshbhetariya/the-rate-limiter-the-line-of-code-juniors-skip-and-seniors-never-forget-0bcc30f4a5a9?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bcc30f4a5a9</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 10:16:01 GMT</pubDate>
            <atom:updated>2026-08-17T10:16:01.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me tell you about a mistake. Not a hypothetical one the kind that shows up as a number on a bill.</p><p>A junior developer ships a “forgot password” feature. You click the button, it sends you a one-time code over SMS. Clean, simple, works on the first try. They test it, it’s perfect, they deploy it, they go home proud. As they should it <em>works</em>.</p><p>Then one morning the team wakes up to a message from the SMS provider. Overnight, that endpoint was called forty thousand times. Someone found it, pointed a tiny script at it, and just… held down the button. Forty thousand text messages. A bill with a lot of zeros. And a very awake finance team.</p><p>The junior stares at the code. Nothing is broken. There’s no bug. The endpoint did <em>exactly</em> what it was told send an SMS when called. It just never asked the one question that mattered: <em>how many times is too many?</em></p><p>The senior on the team looks at it, nods, and says the sentence every one of us has heard or will hear: “Yeah there’s no rate limiter.”</p><p>That’s the whole lesson in a sentence. So let’s actually understand it, because this is one of those things nobody teaches you until it bites, and then you never forget it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OM4WB4pU3tO1g5O5X67psg.png" /><figcaption>A visual overview of how a rate limiter controls incoming requests, allowing legitimate traffic while blocking excessive requests before they reach your server.</figcaption></figure><h3>What a rate limiter actually is</h3><p>Picture a popular club with a bouncer at the door. The club can hold a certain number of people. The bouncer’s job isn’t to stop <em>everyone</em> it’s to control the <em>rate</em> people come in, so the place doesn’t get dangerously packed. “You lot, wait a minute. Okay, now you can come in.”</p><p>A rate limiter is that bouncer for your API. It watches how many requests each user (or IP, or API key) makes in a given window of time, and once they cross the limit, it politely says “that’s enough for now, try again in a bit” instead of letting them flood in.</p><p>The key insight the junior missed: <strong>your code will do whatever it’s asked, as many times as it’s asked.</strong> It has no instinct for “this is too much.” <em>You</em> have to give it that instinct. The rate limiter is where you do it.</p><h3>Why you actually need one</h3><p>The SMS bill is just the most dramatic example. Here’s the real list of what a rate limiter protects you from:</p><p><strong>Runaway costs.</strong> Any endpoint that costs money per call SMS, email, a paid third-party API, an AI/LLM request is a loaded gun without a limit. One abusive loop (or one buggy client stuck retrying) can burn real money fast.</p><p><strong>Brute-force attacks.</strong> This is the big one for login endpoints. Without a limit, an attacker can try millions of password guesses against an account. With a limit of, say, 5 attempts per 15 minutes, that attack goes from “a few hours” to “a few thousand years.” Same code, one config, wildly different security.</p><p><strong>Server overload.</strong> Even free endpoints aren’t free every request uses CPU, memory, and database connections. One client hammering you thousands of times a second can starve everyone else. A rate limiter keeps one greedy user from ruining the experience for all the rest.</p><p><strong>Protecting what’s downstream.</strong> Your API often sits in front of a database or another service that’s slower and more fragile than it is. Limiting the front door protects the delicate rooms behind it from being trampled.</p><p><strong>Simple fairness.</strong> On a public API, limits are how you stop one user from consuming all the capacity and make sure everyone gets a fair share.</p><h3>Where you need it (and where you don’t)</h3><p>Not every endpoint needs the same treatment. Here’s where to actually put your attention, roughly in order of “you will regret skipping this”:</p><ul><li><strong>Login and authentication</strong> tight limits, always. This is your brute-force shield. A handful of attempts per window, then cool down.</li><li><strong>Anything that sends OTPs, SMS, or email</strong> our cautionary tale. Strict limits, because each call costs money and invites abuse.</li><li><strong>Password reset / signup</strong> limit these to stop bots spamming accounts and reset emails.</li><li><strong>Expensive endpoints</strong> search, report generation, and especially anything calling a paid AI API. These cost you the most per call, so protect them the hardest.</li><li><strong>Public APIs </strong>every key gets a quota. That’s not optional, it’s the business model.</li></ul><p>And to be balanced where it matters <em>less</em>: purely internal endpoints behind a private network, or static files already served and cached by a CDN. You can still limit them, but the urgency is lower. Spend your care where the abuse and the cost actually live.</p><h3>A peek at how it works under the hood</h3><p>You don’t need to build the algorithm yourself, but knowing the idea helps you configure it sensibly. The most intuitive model is the <strong>token bucket</strong>:</p><p>Imagine each user has a bucket that holds, say, 10 tokens. Every request spends one token. The bucket slowly refills over time a few tokens per minute. As long as they have tokens, requests go through. Run out, and they’re told to wait for the bucket to refill.</p><p>The neat thing about this model is it allows short <strong>bursts</strong> (a user can spend their whole bucket at once if they need to) while still enforcing a sane <em>average</em> rate over time. That flexibility is why it’s the go-to approach. Most libraries handle this for you you just decide the bucket size and refill rate.</p><h3>Adding one in Node.js</h3><p>Enough theory. In Express, the popular tool is express-rate-limit, and the basic version is genuinely a few lines.</p><pre>npm install express-rate-limit</pre><p>A sensible global limit for your whole API:</p><pre>const rateLimit = require(&quot;express-rate-limit&quot;);<br>const limiter = rateLimit({<br>  windowMs: 15 * 60 * 1000, // 15 minutes<br>  max: 100,                 // 100 requests per IP per window<br>  message: &quot;Too many requests - please slow down and try again shortly.&quot;,<br>  standardHeaders: true,    // send the rate-limit info in response headers<br>  legacyHeaders: false,<br>});<br>app.use(limiter); // applies to every route</pre><p>But remember our story the login endpoint needs a <em>much</em> tighter limit than the rest of the app. So you make a stricter one just for it:</p><pre>const loginLimiter = rateLimit({<br>  windowMs: 15 * 60 * 1000,<br>  max: 5, // only 5 attempts per 15 minutes per IP<br>  message: &quot;Too many login attempts. Please try again in 15 minutes.&quot;,<br>});<br>app.post(&quot;/login&quot;, loginLimiter, loginHandler);</pre><p>That single loginLimiter line is the difference between &quot;brute-forceable in an afternoon&quot; and &quot;not worth an attacker&#39;s time.&quot; That&#39;s the whole thing the junior in our story was missing.</p><h3>The catch that hits you at scale (hello again, Redis)</h3><p>Here’s a trap I want you to see coming, because it’s the exact same shape as the multi-server problem that shows up everywhere in backend work.</p><p>By default, express-rate-limit counts requests <strong>in the memory of one server</strong>. That&#39;s fine on a single machine. But the moment you run several servers behind a load balancer, each one keeps its <em>own</em> separate count.</p><p>So if your limit is 100 and you’re running 3 servers, a user can quietly get 300–100 from each because no server knows what the others have already counted. Your carefully-set limit silently triples, and you don’t find out until it matters.</p><p>The fix is a <strong>shared counter</strong> all your servers read from, and that’s a perfect job for Redis. Instead of each server counting alone, they all tally into one place:</p><pre>const rateLimit = require(&quot;express-rate-limit&quot;);<br>const { RedisStore } = require(&quot;rate-limit-redis&quot;);<br>const { createClient } = require(&quot;redis&quot;);<br>const redisClient = createClient({ url: &quot;redis://localhost:6379&quot; });<br>await redisClient.connect();<br>const limiter = rateLimit({<br>  store: new RedisStore({<br>    sendCommand: (...args) =&gt; redisClient.sendCommand(args),<br>  }),<br>  windowMs: 15 * 60 * 1000,<br>  max: 100,<br>});<br>app.use(limiter);</pre><p>Now all three servers share one honest count in Redis, and 100 means 100 no matter how many machines you run. Same idea as sharing WebSocket connections or job queues across servers one shared source of truth instead of every server living in its own little world.</p><h3>The honest small print</h3><p>A few things I’d rather tell you than have you learn the hard way:</p><ul><li><strong>A rate limiter is not a security system by itself.</strong> It slows down brute force, but it doesn’t replace strong passwords, proper auth, or account lockouts. It’s one layer, not the whole wall.</li><li><strong>Limiting by IP alone is imperfect.</strong> Many users can share one IP (offices, mobile networks), and determined attackers rotate IPs. For logged-in users, limiting per account is often fairer and stronger.</li><li><strong>Set limits with real usage in mind.</strong> Too loose and it does nothing; too tight and you frustrate legitimate users. Start reasonable, watch the numbers, and adjust.</li></ul><h3>Wrapping up</h3><p>The junior in our story didn’t write bad code. The endpoint worked perfectly that was exactly the problem. It did what it was told, as often as it was told, with no sense of “enough.”</p><p>That “sense of enough” is what a rate limiter adds, and it’s why seniors reach for it reflexively: on login endpoints to stop brute force, on anything that costs money to stop runaway bills, on expensive routes to protect the server and everything behind it. A few lines of config, a shared Redis counter once you scale, and a whole category of 2 AM disasters simply never happens.</p><p>The mistake isn’t shameful nearly every developer makes it once. The trick is to make it <em>once</em>, learn the sentence “there’s no rate limiter” and never get caught by that empty bucket again.</p><p><em>I’m Rakesh, a full stack developer. I write here on Medium, and you can find more of my work and writing on my site </em><a href="https://www.rakeshbhetariya.com/"><em>Rakesh Bhetariya Full Stack Developer</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bcc30f4a5a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send WhatsApp Messages from Node.js: A Complete Guide (No Twilio)]]></title>
            <link>https://medium.com/@Rakeshbhetariya/send-whatsapp-messages-from-node-js-a-complete-guide-no-twilio-c279210a2411?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/c279210a2411</guid>
            <category><![CDATA[whatsapp]]></category>
            <category><![CDATA[twilio]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rakesh-bhetariya]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 05:46:01 GMT</pubDate>
            <atom:updated>2026-08-14T05:51:13.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a fun fact that surprises most developers: you can make your Node.js app send WhatsApp messages without Twilio, without a paid API, and without handing your money to any third party.</p><p>No monthly bill. No per-message charge. Just your code, a QR scan, and messages flying out of a real WhatsApp account.</p><p>I remember the first time I got this working I sent a “Hello from my server 👋” to my own phone, watched it pop up a second later, and grinned like I’d hacked the matrix. It feels a little bit like magic. It isn’t. And by the end of this guide, you’ll have built it yourself.</p><p>We’re going to go all the way: send messages, receive them, auto-reply like a bot, wrap it in an API your app can call, and I’ll be dead honest with you about the catch (there is one, and you need to know it).</p><p>Let’s build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rJMIyu2ak6UZPP8iZA0QA.png" /><figcaption>A visual overview of how a Node.js application connects to WhatsApp Web, sends and receives messages, and powers real-time automation without Twilio.</figcaption></figure><h3>Two roads and why we’re taking the free one</h3><p>Before we touch code, you should know there are actually two ways to do WhatsApp from Node:</p><p><strong>The official road </strong>Meta’s WhatsApp Cloud API. Legitimate, built for scale, blessed by WhatsApp itself. But it comes with setup: a Meta Business account, a registered number, pre-approved message templates for anything you send first. Great for a serious company product. Overkill when you just want your app to <em>send a WhatsApp</em>.</p><p><strong>The free road</strong> a brilliant open-source library called <strong>whatsapp-web.js</strong>. No account, no approval, no cost. You scan a QR code once (exactly like WhatsApp Web on your laptop) and your Node app can send and receive messages through that account immediately.</p><p>We’re taking the free road, because it’s the one that gets you from zero to “it works!” in ten minutes. I’ll tell you the exact moment you should switch to the official road later I promise not to leave you hanging on that.</p><h3>How this even works (the “aha” moment)</h3><p>Here’s the clever trick behind whatsapp-web.js, and once you get it, everything else makes sense.</p><p>You know WhatsApp Web the version you open in a browser and connect by scanning a QR code with your phone? whatsapp-web.js basically <strong>runs that web version in a hidden browser</strong> and controls it with code. Under the hood it’s driving a real Chromium browser (via Puppeteer), logged into WhatsApp Web, clicking and typing on your behalf.</p><p>So your Node app isn’t faking WhatsApp it’s genuinely <em>using</em> WhatsApp, the same way you would in a browser tab, just automated. That’s why there’s no API key and no cost: to WhatsApp, it looks like you, on WhatsApp Web.</p><p>Cool. Let’s set it up.</p><h3>Step 1: Install and connect</h3><p>Two packages the library itself, and a little helper to draw the QR code right in your terminal:</p><pre>npm install whatsapp-web.js qrcode-terminal</pre><p>Now the starter code. Read it once, then I’ll break it down:</p><pre>const { Client, LocalAuth } = require(&quot;whatsapp-web.js&quot;);<br>const qrcode = require(&quot;qrcode-terminal&quot;);<br>const client = new Client({<br>  authStrategy: new LocalAuth(), // remembers your login (more on this soon)<br>});<br>// WhatsApp hands us a QR code to scan<br>client.on(&quot;qr&quot;, (qr) =&gt; {<br>  console.log(&quot;Scan this QR code with your phone:&quot;);<br>  qrcode.generate(qr, { small: true });<br>});<br>// fired once we&#39;re logged in and ready<br>client.on(&quot;ready&quot;, () =&gt; {<br>  console.log(&quot;✅ WhatsApp is connected and ready!&quot;);<br>});<br>client.initialize();</pre><p>Run it. A QR code prints right there in your terminal. Now grab your phone, open WhatsApp → <strong>Linked Devices</strong> → <strong>Link a Device</strong>, and scan it exactly like connecting WhatsApp Web.</p><p>A second later your terminal says <strong>“✅ WhatsApp is connected and ready!”</strong> That’s it. Your Node app is now logged into WhatsApp. Take a breath and enjoy that the hard part’s already done.</p><h3>Step 2: Send your first message</h3><p>Now the satisfying part. Let’s send a message. Add this inside the ready handler so it fires the moment we&#39;re connected:</p><pre>client.on(&quot;ready&quot;, async () =&gt; {<br>  console.log(&quot;✅ WhatsApp is connected and ready!&quot;);<br><br>  const number = &quot;919876543210&quot;;     // country code + number, NO + sign<br>  const chatId = `${@c.us&quot;&gt;number}@c.us`;    // WhatsApp&#39;s format for a contact<br>  await client.sendMessage(chatId, &quot;Hello from my Node.js server 👋&quot;);<br>  console.log(&quot;Message sent!&quot;);<br>});</pre><p>Two small things that trip everyone up the first time, so let me save you the headache:</p><ul><li>The number is <strong>country code + number, with no </strong><strong>+ and no spaces</strong>. So an Indian number +91 98765 43210 becomes 919876543210.</li><li>WhatsApp identifies a person by that number plus <strong>@c.us</strong> on the end. That&#39;s just WhatsApp&#39;s internal &quot;address&quot; for a one-to-one chat. Groups use a different suffix, but we&#39;ll keep it to direct messages here.</li></ul><p>Run it, and check the phone for that number. There’s your message. You just sent a WhatsApp from code. 🎉</p><h3>Step 3: Stop scanning that QR every time</h3><p>You might’ve noticed something annoying if you restarted the script it may ask you to scan again. Nobody wants to scan a QR code every time their server restarts.</p><p>That’s exactly what the LocalAuth() we added earlier is for. It <strong>saves your session to disk</strong>, so after the first scan, your app stays logged in across restarts just like your browser stays logged into WhatsApp Web until you sign out.</p><p>You’ll see it create a .wwebjs_auth folder in your project. That folder <em>is</em> your login session, so two quick rules: add it to .gitignore (never commit it), and know that deleting it simply means you&#39;ll scan the QR again next start. First run scans; every run after just connects. Nice and quiet.</p><h3>Step 4: Receiving messages (hello, chatbot)</h3><p>Sending is half the fun. Let’s <em>listen</em> too because the moment your app can react to incoming messages, you’ve basically got a chatbot.</p><pre>client.on(&quot;message&quot;, async (message) =&gt; {<br>  console.log(`📩 ${message.from}: ${message.body}`);<br>  if (message.body.toLowerCase() === &quot;ping&quot;) {<br>    await message.reply(&quot;pong 🏓&quot;);<br>  }<br>  if (message.body.toLowerCase() === &quot;hello&quot;) {<br>    await message.reply(&quot;Hey! I&#39;m a bot running on Node.js 🤖&quot;);<br>  }<br>});</pre><p>Every incoming message triggers this handler. We peek at message.body (the text) and reply when it matches something. message.reply() is a neat shortcut it answers <em>in the same chat</em> automatically, so you don&#39;t have to figure out who to send it back to.</p><p>Text “ping” to the connected account and watch “pong 🏓” come back on its own. From here, your imagination is the limit order updates, support auto-replies, reminders, a personal assistant. All reacting live.</p><h3>Step 5: Let your app send messages on demand</h3><p>So far messages fire on startup or on reply. But in a real app, you want to send a WhatsApp when <em>something happens</em> an order is placed, a form is submitted, an alert triggers. That means exposing a simple endpoint your app can call.</p><p>Let’s wrap our client in a tiny Express API:</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>app.use(express.json());<br><br>// ...the client setup from before stays above this...<br>app.post(&quot;/send&quot;, async (req, res) =&gt; {<br>  const { number, message } = req.body;<br>  try {<br>    const chatId = `${@c.us&quot;&gt;number}@c.us`;<br>    await client.sendMessage(chatId, message);<br>    res.json({ success: true, message: &quot;Sent!&quot; });<br>  } catch (err) {<br>    res.status(500).json({ success: false, error: err.message });<br>  }<br>});<br>app.listen(3000, () =&gt; console.log(&quot;API ready on port 3000&quot;));</pre><p>Now anywhere in your system, sending a WhatsApp is just one HTTP call away:</p><pre>curl -X POST http://localhost:3000/send \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{ &quot;number&quot;: &quot;919876543210&quot;, &quot;message&quot;: &quot;Your order has shipped!&quot; }&#39;</pre><p>That’s the whole thing wired into your app. Order ships → hit /send → customer gets a WhatsApp. No Twilio, no bill.</p><h3>Going further: real-time, two-way chat</h3><p>Once you’re receiving messages, the natural next step is showing them live in your own app a support dashboard, a custom chat UI, messages appearing on screen the instant they arrive.</p><p>For that you need a live connection between your server and your frontend, and that’s a whole skill of its own: WebSockets. I wrote a full walkthrough of building exactly that kind of live WhatsApp message flow <a href="https://medium.com/@Rakeshbhetariya/real-time-whatsapp-messages-with-websocket-13c7f5cf4f68">Real-Time WhatsApp Messages with WebSocket</a> so if you want incoming messages to appear on your screen in real time, that’s your next read. It picks up right where this one leaves off.</p><h3>The honest catch (please read this part)</h3><p>I promised I wouldn’t leave you hanging, so here’s the straight talk.</p><p>whatsapp-web.js is <strong>unofficial</strong>. It automates WhatsApp Web, and that goes against WhatsApp’s official Terms of Service. In plain English: WhatsApp doesn’t sanction this, and in theory an account using it <em>can</em> get banned especially if it behaves spammy (blasting messages to strangers, high volume, unsolicited stuff).</p><p>So here’s my honest advice on where it fits:</p><ul><li><strong>Great for:</strong> side projects, prototypes, internal tools, personal automations, learning, low-volume stuff to people who expect to hear from you. Use a spare number you don’t mind risking not your primary personal WhatsApp.</li><li><strong>Don’t:</strong> spam cold contacts or blast marketing at strangers. That’s the fastest way to a ban, and honestly it’s just rude.</li><li><strong>Switch to the official WhatsApp Cloud API when:</strong> you’re building a real product, sending at scale, messaging customers who didn’t initiate, or you simply can’t afford the account getting banned. That’s the moment the extra setup of the official road becomes worth it. It’s the grown-up version of what we built here.</li></ul><p>I’d rather you know this now than learn it the hard way. Use the free road for what it’s brilliant at, and graduate to the official one when the stakes get real.</p><h3>Wrapping up</h3><p>Look at everything you just built: your Node app <strong>connects</strong> to WhatsApp with a QR scan, <strong>stays logged in</strong> across restarts, <strong>sends</strong> messages, <strong>listens and auto-replies</strong> like a bot, and exposes an <strong>API</strong> so the rest of your app can fire off a WhatsApp whenever something happens all with zero cost and no Twilio.</p><p>That’s a genuinely useful superpower to have in your toolkit. Just wield it responsibly, keep an eye on that honest catch, and reach for the official API when you outgrow the free road.</p><p>Now go send that first “Hello from my server 👋” and enjoy the little grin. You’ve earned it.</p><p><em>I’m Rakesh, a full stack developer. I write here on Medium, and you can find more of my work and writing on my site </em><a href="https://www.rakeshbhetariya.com/"><em>Rakesh Bhetariya Full Stack Developer</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c279210a2411" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate Excel Reports in Node.js: The Complete Guide]]></title>
            <link>https://medium.com/@Rakeshbhetariya/generate-excel-reports-in-node-js-the-complete-guide-86ef6879e3a9?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/86ef6879e3a9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 16:11:01 GMT</pubDate>
            <atom:updated>2026-08-12T16:11:01.747Z</atom:updated>
            <content:encoded><![CDATA[<p>Sooner or later, someone asks for it. “Can we export this as an Excel file?”</p><p>Not a table on a webpage. Not a PDF. An actual .xlsx file they can open, sort, filter, and the real reason they want it run their own formulas on. Finance teams live in Excel. Ops teams live in Excel. And at some point your app has to hand them a proper spreadsheet.</p><p>So let me walk you through generating Excel reports in Node.js. We’ll start from “what even <em>is</em> an Excel file to code,” build a clean report step by step, style it so it looks professional, let Excel do live math with formulas, send it to the user as a download, and finally handle the big-report problem that quietly crashes servers.</p><p>(If it’s PDFs you’re after rather than spreadsheets, I wrote a separate complete guide on generating those with Puppeteer you can read that one <a href="https://medium.com/@Rakeshbhetariya/how-to-generate-pdfs-with-puppeteer-in-node-js-a-complete-guide-for-developers-3faac986e569">here</a>. This guide is all about Excel.)</p><p>Let’s go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcUmVDaJxx8K1iBisCGo5Q.png" /><figcaption>A high-level overview of how Node.js, ExcelJS, and structured data work together to generate professional Excel reports with styling, formulas, and downloadable .xlsx files.</figcaption></figure><h3>First, why not just send a CSV?</h3><p>This is the honest first question, because CSV is tempting. It’s easy you can practically build one with string concatenation.</p><p>Here’s the analogy. A CSV is a plain handwritten list on a napkin. It holds the data, sure. But it has no styling, no bold headers, no colors, no number formatting, no multiple pages, and the big one no formulas. Open a CSV and every “number” is really just text that happens to look like a number.</p><p>A real Excel file is the difference between that napkin and a properly typed, formatted report. Bold headers. Currency columns that actually behave like currency. A “Total” cell that <em>calculates itself</em>. Multiple tabs. That’s what people mean when they say “export to Excel” they don’t want a napkin, they want the report.</p><p>To build that, we need a library that understands the real Excel format. The best one for creating rich, styled reports is <strong>ExcelJS</strong>.</p><pre>npm install exceljs</pre><h3>The mental model: binders, tabs, and cells</h3><p>Before we write code, let’s get the vocabulary straight, because ExcelJS uses these exact words and it’ll make everything click.</p><p>Picture a physical binder:</p><ul><li>The <strong>workbook</strong> is the whole binder it <em>is</em> the Excel file.</li><li>A <strong>worksheet</strong> is one labeled tab inside it (like “Sales”, “Summary”). One workbook can hold many.</li><li><strong>Columns</strong>, <strong>rows</strong>, and <strong>cells</strong> are exactly what you’d expect the grid inside a tab.</li></ul><p>So building a report is really: make a binder, add a tab, pour rows into it. That’s it. Let’s do it.</p><h3>Step 1: Your first spreadsheet</h3><p>Say we have some sales data the kind of array you’d get back from a database query:</p><pre>const data = [<br>  { product: &quot;Wireless Mouse&quot;, quantity: 120, price: 24.99 },<br>  { product: &quot;Keyboard&quot;,       quantity: 80,  price: 49.99 },<br>  { product: &quot;Monitor&quot;,        quantity: 35,  price: 199.99 },<br>];</pre><p>Now let’s turn it into an Excel file:</p><pre>const ExcelJS = require(&quot;exceljs&quot;);<br><br>async function buildReport() {<br>  const workbook = new ExcelJS.Workbook();       // the binder<br>  const sheet = workbook.addWorksheet(&quot;Sales&quot;);  // a tab called &quot;Sales&quot;<br>  // define the columns: what the header says, and which data key fills it<br>  sheet.columns = [<br>    { header: &quot;Product&quot;,  key: &quot;product&quot;,  width: 30 },<br>    { header: &quot;Quantity&quot;, key: &quot;quantity&quot;, width: 15 },<br>    { header: &quot;Price&quot;,    key: &quot;price&quot;,    width: 15 },<br>  ];<br>  // pour in the rows<br>  sheet.addRows(data);<br>  // save it to a file<br>  await workbook.xlsx.writeFile(&quot;sales-report.xlsx&quot;);<br>  console.log(&quot;Report created!&quot;);<br>}<br>buildReport();</pre><p>Run that, and you’ve got a real sales-report.xlsx sitting in your folder. Open it in Excel or Google Sheets there&#39;s your data, in three neat columns.</p><p>Notice the key in each column definition. That&#39;s the quiet magic: it tells ExcelJS &quot;the product value in each data object goes in <em>this</em> column.&quot; So addRows(data) just maps your objects straight into the grid. No manual cell-by-cell placement.</p><p>It works. But right now it’s still a bit of a napkin plain and unstyled. Let’s make it look like a report.</p><h3>Step 2: Making it look like an actual report</h3><p>The header row is the first thing anyone sees, so let’s make it bold, give it a color, and white text the classic report look.</p><pre>const headerRow = sheet.getRow(1);<br>headerRow.font = { bold: true, color: { argb: &quot;FFFFFFFF&quot; } }; // white text<br>headerRow.fill = {<br>  type: &quot;pattern&quot;,<br>  pattern: &quot;solid&quot;,<br>  fgColor: { argb: &quot;FF4472C4&quot; }, // a nice blue<br>};<br>headerRow.alignment = { vertical: &quot;middle&quot;, horizontal: &quot;center&quot; };</pre><p>Quick note on those color codes: ExcelJS uses <strong>ARGB </strong>an 8-character hex where the first two characters are the alpha (opacity). FF at the front just means fully opaque. So FF4472C4 is opaque blue. Don&#39;t drop that leading FF or the color won&#39;t show up a small gotcha that trips everyone up once.</p><p>Now the price column. Right now 24.99 is just a number. Let&#39;s make it <em>behave</em> like money:</p><pre>sheet.getColumn(&quot;price&quot;).numFmt = &#39;&quot;$&quot;#,##0.00&#39;;</pre><p>That format string looks cryptic, but read it in plain English: a dollar sign, then a number with thousands separators and exactly two decimal places. Now 199.99 displays as $199.99 and, more importantly, Excel treats it as currency when the user does their own math on it.</p><p>This is the moment the napkin becomes a report.</p><h3>Step 3: Let Excel do the math (formulas)</h3><p>Here’s the feature CSV can never give you: a cell that calculates itself.</p><p>Instead of computing a total in your Node code and pasting a dead number, you can hand Excel a <strong>formula</strong>, and Excel does the math when the file opens live. If the user edits a quantity, the total updates itself. The report is <em>alive</em>.</p><p>Let’s add a total row under our data. Our data has 3 rows, so with the header they sit in rows 2 through 4:</p><pre>const totalRowNumber = sheet.rowCount + 1;<br>sheet.getCell(`A${totalRowNumber}`).value = &quot;TOTAL&quot;;<br>sheet.getCell(`B${totalRowNumber}`).value = {<br>  formula: `SUM(B2:B${sheet.rowCount})`,<br>};<br>sheet.getRow(totalRowNumber).font = { bold: true };</pre><p>Setting a cell’s value to { formula: &quot;SUM(...)&quot; } is you literally writing an Excel formula into the file. When someone opens it, Excel evaluates SUM(B2:B4) and shows the real total the same as if they&#39;d typed it themselves. That&#39;s something a static export simply cannot do.</p><h3>Step 4: Sending the file to the user</h3><p>Writing to disk is fine for a scheduled job. But usually you want a user to click “Download Report” and get the file straight from an API. Here’s that endpoint with Express.</p><p>The trick is two response headers that tell the browser “this is an Excel file, and it’s a download, not a page”:</p><pre>const express = require(&quot;express&quot;);<br>const ExcelJS = require(&quot;exceljs&quot;);<br>const app = express();<br>app.get(&quot;/report&quot;, async (req, res) =&gt; {<br>  const workbook = new ExcelJS.Workbook();<br>  const sheet = workbook.addWorksheet(&quot;Sales&quot;);<br>  sheet.columns = [<br>    { header: &quot;Product&quot;,  key: &quot;product&quot;,  width: 30 },<br>    { header: &quot;Quantity&quot;, key: &quot;quantity&quot;, width: 15 },<br>    { header: &quot;Price&quot;,    key: &quot;price&quot;,    width: 15 },<br>  ];<br>  sheet.addRows(data);<br>  // tell the browser what&#39;s coming<br>  res.setHeader(<br>    &quot;Content-Type&quot;,<br>    &quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;<br>  );<br>  res.setHeader(<br>    &quot;Content-Disposition&quot;,<br>    &quot;attachment; filename=sales-report.xlsx&quot;<br>  );<br>  // write the workbook straight into the response, then finish<br>  await workbook.xlsx.write(res);<br>  res.end();<br>});<br>app.listen(3000, () =&gt; console.log(&quot;On port 3000&quot;));</pre><p>That long Content-Type is just the official name for &quot;an .xlsx file&quot; copy it as-is. Content-Disposition: attachment is what makes the browser download it instead of trying to display it. Hit /report and the file lands in your Downloads. Clean.</p><h3>Step 5: The problem with big reports (and how to fix it)</h3><p>Everything above works beautifully until someone exports 200,000 rows.</p><p>Here’s what goes wrong, and it’s the exact same trap as generating large PDFs or handling big file uploads: by default, ExcelJS builds the <em>entire</em> workbook in memory before sending it. A few hundred rows? No problem. Hundreds of thousands? Your server tries to hold the whole giant file in RAM at once, memory spikes, and the process can crash.</p><p>The analogy: it’s the difference between writing an entire 500-page book on your desk before mailing it (you run out of desk), versus writing one page and dropping it in the mail as you go (your desk stays clear no matter how long the book is).</p><p>That second approach is <strong>streaming</strong>, and ExcelJS has a streaming writer built for exactly this. Instead of holding everything, you write each row and commit() it send it on its way keeping memory flat no matter how huge the report gets:</p><pre>app.get(&quot;/big-report&quot;, async (req, res) =&gt; {<br>  res.setHeader(<br>    &quot;Content-Type&quot;,<br>    &quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;<br>  );<br>  res.setHeader(<br>    &quot;Content-Disposition&quot;,<br>    &quot;attachment; filename=big-report.xlsx&quot;<br>  );<br><br>  // a streaming workbook that writes straight into the response<br>  const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ stream: res });<br>  const sheet = workbook.addWorksheet(&quot;Data&quot;);<br>  sheet.columns = [<br>    { header: &quot;Product&quot;,  key: &quot;product&quot;,  width: 30 },<br>    { header: &quot;Quantity&quot;, key: &quot;quantity&quot;, width: 15 },<br>  ];<br>  // imagine looping over a huge database result here<br>  for (const item of hugeDataset) {<br>    sheet.addRow(item).commit(); // write this row and release it<br>  }<br>  await workbook.commit(); // finish the file<br>});</pre><p>Same result for the user a downloaded Excel file. But now your server stays calm whether it’s 100 rows or a million, because it’s never holding the whole thing at once. This is the piece that separates a demo from something you can actually run in production.</p><h3>The honest small print</h3><p>Because a good guide tells you when <em>not</em> to use it:</p><ul><li><strong>If you truly just need raw data with no styling or formulas</strong> say, one system feeding another a plain <strong>CSV</strong> is lighter and perfectly fine. Reach for Excel when a <em>human</em> is going to open it.</li><li><strong>ExcelJS is for generating files, not heavy number-crunching.</strong> If you need giant pivot tables or complex analytics, do the calculations in your database or code first, then export the results.</li><li><strong>Need a fixed, print-perfect layout instead of an editable grid?</strong> That’s a PDF’s job, not a spreadsheet’s. I covered generating those in a <a href="https://medium.com/@Rakeshbhetariya/how-to-generate-pdfs-with-puppeteer-in-node-js-a-complete-guide-for-developers-3faac986e569">separate guide here</a> Excel is for data people will work <em>with</em>, PDF is for documents people will read.</li></ul><h3>Wrapping up</h3><p>Let’s retrace the path:</p><p>We started by asking why not CSV and saw that a real report needs styling, currency formatting, and formulas a napkin can’t give. We learned the <strong>binder → tab → cell</strong> model, built our first spreadsheet with <strong>ExcelJS</strong>, <strong>styled</strong> the header and formatted the money column, and let Excel do <strong>live math</strong> with a formula. We served it as a proper <strong>download</strong> from an Express endpoint, and finally handled the big-report memory trap with <strong>streaming</strong>, so it holds up under real load.</p><p>That’s a complete, production-ready Excel export built one simple step at a time.</p><p><em>I’m Rakesh, a full stack developer. I write here and on my own site too </em><a href="https://www.rakeshbhetariya.com/"><em>rakeshbhetariya.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86ef6879e3a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Real-Time Notification System in Node.js with Socket.IO and Redis]]></title>
            <link>https://medium.com/@Rakeshbhetariya/how-to-build-a-real-time-notification-system-in-node-js-with-socket-io-and-redis-8933a73ce558?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/8933a73ce558</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[socketio]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 15:47:38 GMT</pubDate>
            <atom:updated>2026-08-07T15:47:38.725Z</atom:updated>
            <content:encoded><![CDATA[<p>Every app eventually needs notifications. A new message arrives. An order gets placed. Someone likes your post. And the user expects to <em>just know </em>instantly, without refreshing anything.</p><p>That “instantly, without refreshing” part is where a lot of us get stuck. So let me walk you through building a real-time notification system, We’ll start from the very idea of “real-time,” build a working version with Socket.IO, and then take it all the way to the setup you’d actually run in production across multiple servers, with Redis holding it together.</p><p>No prior WebSocket experience needed. Let’s go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8z0TF7W2n1deg2mDlvnt4Q.png" /><figcaption>isual architecture of a real-time notification system where Node.js, Socket.IO, and Redis deliver live notifications to connected users.</figcaption></figure><h3>First, why can’t we just refresh?</h3><p>Imagine you’re in the back seat of a car on a long drive. You want to know when you’ve arrived. You have two options.</p><p>Option one: ask “are we there yet?” every ten seconds. Annoying, exhausting, and 99% of the time the answer is “no.” That’s <strong>polling</strong> your app asking the server “any new notifications? any new ones now? now?” over and over. It works, but it’s wasteful. Most of those requests come back empty, and there’s always a delay between the thing happening and your next question.</p><p>Option two: your parent says “I’ll tell you the moment we arrive.” Now you can relax. No asking. The information comes <em>to you</em>, exactly when it matters. That’s <strong>real-time push </strong>and that’s what we actually want.</p><p>To make option two work, we need a connection that stays open, so the server can talk to the browser whenever it wants. That’s what a <strong>WebSocket</strong> is.</p><h3>What a WebSocket actually is</h3><p>A normal web request is like sending a letter. You write it, send it, wait for a reply, and the conversation is over. If you want to talk again, you send another letter. That’s HTTP one question, one answer, done.</p><p>A WebSocket is like calling someone and <em>keeping the line open</em>. Once the call connects, either side can speak at any time, instantly, without dialing again. The browser can talk to the server, and this is the important part the server can talk to the browser whenever it wants.</p><p>That open line is exactly what a notification system needs. The moment something happens on the server, it just says it down the line, and the browser hears it immediately.</p><p>We <em>could</em> build this with the raw WebSocket protocol. But there’s a friendlier tool that handles the annoying parts for us.</p><h3>Enter Socket.IO</h3><p>Socket.IO is a library that sits on top of WebSockets and handles the messy real-world details for you:</p><ul><li>If the connection drops (user goes through a tunnel, wifi hiccups), it <strong>reconnects automatically</strong>.</li><li>It gives you <strong>rooms</strong> a clean way to send a message to one specific user instead of everyone.</li><li>It falls back gracefully on networks where raw WebSockets are blocked.</li></ul><p>Think of raw WebSockets as the engine, and Socket.IO as the whole car built around it steering, brakes, seatbelts included. We’ll use Socket.IO.</p><p>Let’s install what we need:</p><pre>npm install express socket.io</pre><h3>Step 1: The basic connection</h3><p>Let’s get a server running that can accept live connections. We’ll use Express for the HTTP part and attach Socket.IO to it.</p><pre>const express = require(&quot;express&quot;);<br>const { createServer } = require(&quot;http&quot;);<br>const { Server } = require(&quot;socket.io&quot;);<br>const app = express();<br>const httpServer = createServer(app);<br>const io = new Server(httpServer, {<br>  cors: { origin: &quot;*&quot; }, // we&#39;ll tighten this in production<br>});<br>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  console.log(&quot;A user connected:&quot;, socket.id);<br>  socket.on(&quot;disconnect&quot;, () =&gt; {<br>    console.log(&quot;A user left:&quot;, socket.id);<br>  });<br>});<br>httpServer.listen(3000, () =&gt; {<br>  console.log(&quot;Server listening on port 3000&quot;);<br>});</pre><p>Here’s what’s happening. io.on(&quot;connection&quot;, ...) fires every time a browser opens the live line to us. Each connected browser is a socketthink of it as one open phone line, with its own unique socket.id.</p><p>Now the browser side. Socket.IO serves its own client script automatically, so this is all you need:</p><pre>&lt;script src=&quot;/socket.io/socket.io.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>  const socket = io();<br>  socket.on(&quot;notification&quot;, (data) =&gt; {<br>    console.log(&quot;New notification:&quot;, data);<br>    // here you&#39;d show a toast, update a bell icon, etc.<br>  });<br>&lt;/script&gt;</pre><p>Open that page and your server logs “A user connected.” The line is open. Now we need to make it <em>useful</em>.</p><h3>Step 2: Sending a notification to ONE user</h3><p>Here’s the first real problem. Right now, if we broadcast a message, <em>every</em> connected browser gets it. But a notification is personal user 42’s “your order shipped” should go to user 42 and nobody else.</p><p>This is where <strong>rooms</strong> come in, and the analogy is simple: a room is a private channel. Picture a big office with a PA system. If you announce something over the whole building, everyone hears it. But if each person has their own private intercom line, you can talk to exactly one person.</p><p>In Socket.IO, we give every user their own private room named after their user ID the moment they connect.</p><p>But wait: how do we know <em>which</em> user just connected? The socket doesn’t magically know who they are. We have to tell it. The clean way is to have the browser send a token when it connects, and verify it on the server.</p><p>Browser side pass the user’s login token:</p><pre>const socket = io({<br>  auth: { token: &quot;the-users-login-token&quot; },<br>});</pre><p>Server side check that token before we trust the connection:</p><pre>io.use((socket, next) =&gt; {<br>  const token = socket.handshake.auth.token;<br>  try {<br>    const user = verifyToken(token);  // your own JWT/session check<br>    socket.userId = user.id;          // remember who this line belongs to<br>    next();                           // allow the connection<br>  } catch (err) {<br>    next(new Error(&quot;Authentication failed&quot;)); // reject it<br>  }<br>});</pre><p>That io.use(...) is like a security guard at the door. Every new connection has to show ID before it&#39;s let in. Once it passes, we&#39;ve stamped the socket with socket.userId, so we know who&#39;s on the other end of the line.</p><p>Now, when they connect, we put them in their own private room:</p><pre>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  socket.join(`user:${socket.userId}`);<br>  console.log(`User ${socket.userId} is now listening`);<br>});</pre><p>And here’s the payoff. Anywhere in your app after an order is placed, a message is sent, whatever you can notify exactly one person:</p><pre>function notifyUser(userId, notification) {<br>  io.to(`user:${userId}`).emit(&quot;notification&quot;, notification);<br>}<br><br>// somewhere in your order code:<br>notifyUser(42, {<br>  title: &quot;Order shipped&quot;,<br>  body: &quot;Your order #1234 is on its way!&quot;,<br>});</pre><p>io.to(&quot;user:42&quot;).emit(...) means &quot;speak only into user 42&#39;s private room.&quot; User 42&#39;s browser hears it instantly. Everyone else hears nothing. That&#39;s a working real-time notification system.</p><p>For a single server, you’re done. But the moment your app gets popular, a new problem appears and it’s the one most tutorials never warn you about.</p><h3>Step 3: The problem that breaks everything in production</h3><p>Your app grows. One server isn’t enough, so you run three of them behind a load balancer, which spreads users across the servers to share the load. Sounds healthy. But watch what happens.</p><p>User 42 connects the load balancer sends them to <strong>Server A</strong>. Their open phone line lives on Server A.</p><p>Now an order is placed, and the code that runs notifyUser(42, ...) happens to be running on <strong>Server B</strong>.</p><p>Server B shouts into user 42’s room… but user 42’s line is on Server A. Server B has never heard of user 42. The notification goes nowhere. Silence.</p><p>Here’s the analogy. Imagine three separate post offices that don’t talk to each other. You walked into post office A and left your address there. Someone drops off a package for you at post office B. Post office B has no idea who you are or where you’re standing you’re a customer of A. The package just sits there.</p><p>Each server only knows about <em>its own</em> connected users. And that quietly breaks real-time for a huge chunk of your users, in a way that works perfectly in testing (one server) and fails only under real load. Painful.</p><p>We need to give the servers a way to talk to each other.</p><h3>Step 4: Redis, the shared intercom</h3><p>This is where Redis comes in. And to be clear about its job here: we’re not using Redis to store data. We’re using it as a <strong>shared intercom</strong> that all your servers can hear.</p><p>Back to the post offices. The fix is to install one radio system connecting all three. Now when a package arrives at office B for a customer of office A, B just gets on the radio: “package for customer 42!” Every office hears it. Office A, where you’re actually standing, hands you the package. The others simply ignore the call because customer 42 isn’t with them.</p><p>That radio is Redis’s <strong>publish/subscribe</strong> system, and Socket.IO has an official adapter that wires it all up for you. When any server emits to a room, the adapter publishes that message through Redis; every other server receives it and delivers it to any matching sockets <em>it</em> is holding. You don’t change your notifyUser code at all it just starts working across every server.</p><p>Let’s add it:</p><pre>npm install @socket.io/redis-adapter redis</pre><p>Then connect two Redis clients one to publish messages, one to listen for them and hand them to Socket.IO:</p><pre>const { createAdapter } = require(&quot;@socket.io/redis-adapter&quot;);<br>const { createClient } = require(&quot;redis&quot;);<br>async function setupRedis() {<br>  const pubClient = createClient({ url: &quot;redis://localhost:6379&quot; });<br>  const subClient = pubClient.duplicate();<br>  await Promise.all([pubClient.connect(), subClient.connect()]);<br>  io.adapter(createAdapter(pubClient, subClient));<br>  console.log(&quot;Socket.IO is now connected across servers via Redis&quot;);<br>}<br>setupRedis();</pre><p>Why two clients? In Redis pub/sub, a connection that’s busy <em>listening</em> for messages can’t also be used to <em>send</em> them so we use one for publishing (pubClient) and a duplicate for subscribing (subClient). That&#39;s just how Redis works; the adapter needs both.</p><p>That’s the whole change. Your three servers now share one intercom. notifyUser(42, ...) works no matter which server runs it and no matter which server user 42 is connected to. You&#39;ve gone from a toy that works on one machine to something that scales horizontally.</p><h3>One production gotcha worth knowing</h3><p>There’s a second detail that trips people up with multiple servers: the initial connection handshake.</p><p>Socket.IO sometimes starts a connection over regular HTTP before upgrading to a WebSocket, and that handshake can involve a few requests that all need to reach the <em>same</em> server. With a load balancer bouncing requests around, that can fail. Two common fixes: enable <strong>sticky sessions</strong> (tell the load balancer to keep each user pinned to the same server), or configure the client to use the WebSocket transport directly:</p><pre>const socket = io({<br>  auth: { token: &quot;the-users-login-token&quot; },<br>  transports: [&quot;websocket&quot;],<br>});</pre><p>The Redis adapter handles messages <em>between</em> servers; sticky sessions (or WebSocket-only transport) handle the <em>initial</em> connection. You generally want both sorted for a real multi-server deploy.</p><h3>The honest small print</h3><p>Because a good guide says what it <em>doesn’t</em> do:</p><p>WebSockets deliver to people who are <strong>currently connected</strong>. If a user is offline when the notification fires, the real-time push reaches nobody there’s no line open. So a complete notification system also <strong>saves notifications to a database</strong>. The database is the permanent record (“here are your 5 unread notifications”); the WebSocket is the live delivery on top. When a user comes back online, you load their unread ones from the database, and use the socket for anything new that happens while they’re there. Real-time and stored, working together.</p><h3>Wrapping up</h3><p>Let’s retrace the whole journey:</p><p>We started with the problem asking “are we there yet?” over and over is wasteful, so instead we keep a <strong>line open</strong> so the server can push to us. That open line is a <strong>WebSocket</strong>, and <strong>Socket.IO</strong> wraps it with reconnection, fallbacks, and rooms. We gave each user a <strong>private room</strong> so notifications reach exactly one person, and a <strong>security guard</strong> (auth middleware) so we know who each line belongs to. Then we hit the real-world wall multiple servers can’t see each other’s users and solved it with <strong>Redis as a shared intercom</strong>, so every server can reach every user. Finally, we noted that a full system also <strong>stores</strong> notifications for when users are offline.</p><p>That’s a real-time notification system that actually holds up in production built up one simple idea at a time.</p><p><em>I’m Rakesh, a full stack developer. I write here and on my own site too </em><a href="https://www.rakeshbhetariya.com/"><em>rakeshbhetariya.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8933a73ce558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You reached for MongoDB. You wanted a JSONB column.]]></title>
            <link>https://medium.com/@Rakeshbhetariya/you-reached-for-mongodb-you-wanted-a-jsonb-column-4a5137ec2180?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a5137ec2180</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Tue, 04 Aug 2026 07:31:26 GMT</pubDate>
            <atom:updated>2026-08-04T07:31:26.180Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me tell you how this one actually started, because it wasn’t a hot take. It was a feature.</p><p>We were building user settings. You know the shape of this feature even if you’ve never seen ours. Theme preference. Notification toggles. A list of beta features the user has opted into. And the thing about settings is that the shape <em>keeps changing</em>. Every sprint someone adds a new toggle. Next month there’s a nested object nobody planned for.</p><p>So I did what I’ve done a hundred times without thinking.</p><p>I reached for Mongo.</p><p>Schema-less, right? Just throw the document in. No migration, no ALTER TABLE, no ceremony. The shape can drift and Mongo won&#39;t complain.</p><p>But this time, before I actually added another database to our stack, I made myself do the boring thing. I sat down and looked at what we’d be signing up for a second datastore, a second connection pool, a second backup story, settings that now live <em>away</em> from the users table they belong to. And I asked the honest question: is Mongo solving a data problem here, or is it solving my impatience?</p><p>That’s when it clicked. And I want to be honest about the real reason we pick Mongo, because naming it is the whole point:</p><p>Half the time we reach for Mongo, we’re not choosing a database. We’re choosing “I don’t want to write migrations yet.”</p><p>That’s it. That’s the actual feeling. The shape isn’t settled, and a rigid schema feels like commitment we’re not ready for. Mongo lets us stay non-committal.</p><p>But Postgres has had an answer to exactly that feeling for years. I just never reached for it, because I’d already trained my hand to grab Mongo.</p><h3>The same feature, in Mongo</h3><p>Here’s the document. Nothing exotic.</p><pre>db.userSettings.insertOne({<br>  userId: 42,<br>  theme: &quot;dark&quot;,<br>  notifications: { email: true, push: false },<br>  betaFeatures: [&quot;new-editor&quot;, &quot;dark-mode-v2&quot;]<br>});</pre><p>And reading it back for one user:</p><pre>db.userSettings.findOne({ userId: 42 });</pre><p>Clean. Flexible. The shape can change tomorrow and nothing breaks. This is the appeal, and it’s a real appeal. I’m not going to pretend it isn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5knhLO64FRGmqSir1IElA.png" /></figure><h3>The same feature, as one Postgres column</h3><p>Now here’s the part I’d been walking past for years. Postgres has a jsonb type binary JSON, indexable, queryable. You don&#39;t need a document database to store a document. You need a column.</p><pre>CREATE TABLE user_settings (<br>  user_id  integer PRIMARY KEY REFERENCES users (user_id),<br>  settings jsonb NOT NULL DEFAULT &#39;{}&#39;<br>);</pre><p>Look at that first line. REFERENCES users (user_id). We&#39;ll come back to why that one line is the whole argument.</p><p>Inserting the exact same document:</p><pre>INSERT INTO user_settings (user_id, settings)<br>VALUES (42, &#39;{<br>  &quot;theme&quot;: &quot;dark&quot;,<br>  &quot;notifications&quot;: { &quot;email&quot;: true, &quot;push&quot;: false },<br>  &quot;betaFeatures&quot;: [&quot;new-editor&quot;, &quot;dark-mode-v2&quot;]<br>}&#39;);</pre><p>The shape is just as free as Mongo’s. Postgres does not care what’s inside that jsonb. Add a new key next month, nest something three levels deep the column doesn&#39;t flinch. No migration. That&#39;s the exact &quot;I don&#39;t want to commit yet&quot; feeling I was chasing, and it&#39;s right here in a normal table.</p><h3>But can you actually query into it?</h3><p>This is the part people assume you can’t. You can.</p><p>Pull a nested value out — -&gt; gives you JSON, -&gt;&gt; gives you text:</p><pre>SELECT settings-&gt;&#39;notifications&#39;-&gt;&gt;&#39;email&#39; AS email_enabled<br>FROM user_settings<br>WHERE user_id = 42;</pre><p>Filter on something inside the document:</p><pre>SELECT user_id<br>FROM user_settings<br>WHERE settings @&gt; &#39;{&quot;notifications&quot;: {&quot;email&quot;: true}}&#39;;</pre><p>That @&gt; is the containment operator &quot;does this JSON contain this JSON.&quot; It reads a little strange the first time, but it&#39;s the one worth learning, because of what comes next.</p><h3>The indexing part (where blogs usually lie to you)</h3><p>Here’s where I want to be careful, because this is the detail that separates “I read the docs” from “I skimmed a tweet.”</p><p>You <em>can</em> index jsonb, but <strong>how</strong> you index depends on <strong>how</strong> you query:</p><ul><li>If you filter with containment (@&gt;) or key-existence (?), a <strong>GIN index</strong> on the whole column is what you want:</li></ul><pre>CREATE INDEX idx_settings ON user_settings USING GIN (settings);</pre><ul><li>If you constantly filter on one specific field with -&gt;&gt;, a GIN index won&#39;t help that you want a plain <strong>B-tree expression index</strong> on that path:</li></ul><pre>CREATE INDEX idx_theme ON user_settings ((settings-&gt;&gt;&#39;theme&#39;));</pre><p>Those are two different tools for two different query shapes. If a post tells you “just add a GIN index and everything’s fast,” it’s hand-waving. The honest version is: match the index to the operator you actually use.</p><h3>The line that ended the debate for me</h3><p>Everything above is nice. This is the part that actually made me delete Mongo from the plan.</p><p>The settings are in a normal table now. Which means I can do the two things a document database makes genuinely awkward.</p><p><strong>One I can join them to real relational data, in one query</strong></p><pre>SELECT u.username,<br>       s.settings-&gt;&gt;&#39;theme&#39; AS theme<br>FROM   users u<br>JOIN   user_settings s ON s.user_id = u.user_id<br>WHERE  s.settings @&gt; &#39;{&quot;betaFeatures&quot;: [&quot;new-editor&quot;]}&#39;;</pre><p>“Give me the usernames of everyone who opted into the new editor.” Flexible JSON filter and a relational join, in the same statement, hitting one database. With Mongo, that username lives in Postgres and the settings live in Mongo, so this “one query” becomes two round trips and a join I stitch together in application code.</p><p><strong>Two I get real transactions across both worlds.</strong> Updating a user’s row and their settings blob happens in the same ACID transaction. Either both land or neither does. No “the write succeeded in Postgres but failed in Mongo” 2 AM special.</p><p>That foreign key back on the user_settings table? That&#39;s the whole thing. My flexible data is <em>related</em> to my relational data, and now it&#39;s allowed to say so.</p><p>We didn’t need a document database. We needed one column that would stop judging us for not knowing the shape yet.</p><h3>The honest small print</h3><p>Because I’d rather say this than read it below:</p><p>This is not “Mongo bad.” Mongo is a genuinely good database at the thing it’s actually for. If you need to shard across many nodes, scale writes horizontally, handle very high write throughput, or store huge documents where a single row in Postgres would get unwieldy that’s a real Mongo job, and jsonb in a single Postgres instance is not going to out-scale a purpose built distributed store. Its aggregation pipeline and change streams are real features, not consolation prizes.</p><p>But be honest about why you’re reaching for it. If the answer is “our data is genuinely distributed and write-heavy at scale” Mongo, absolutely. If the answer is “the shape isn’t settled and I don’t want to write migrations yet” that’s not a scale problem. That’s a jsonb column.</p><p>For years I was solving the second problem with a tool built for the first. The data was never the issue.</p><p>I just hadn’t learned that the boring database I already ran could hold a document without making it a second database.</p><p><em>I’m Rakesh Bhetariya, a full stack developer. I write here and on my own site too </em><a href="https://www.rakeshbhetariya.com/"><em>rakeshbhetariya.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a5137ec2180" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We deleted Redis and used Postgres as our queue]]></title>
            <link>https://medium.com/@Rakeshbhetariya/we-deleted-redis-and-used-postgres-as-our-queue-c3d5fdf84d9b?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d5fdf84d9b</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[bullmq]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 18:02:03 GMT</pubDate>
            <atom:updated>2026-07-31T18:02:03.440Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me start with the exact moment this clicked for me.</p><p>It was 2AM. Not metaphorically. Actually 2AM.</p><p>Redis had fallen over. Not our database, our database was fine. Our <em>queue</em> was down. The thing we added so the app would be more reliable was the thing that woke me up.</p><p>And while I was sitting there half awake, staring at a dashboard, waiting for a container to come back, one thought kept circling.</p><p>Why is this even a separate thing.</p><p>The jobs were rows. They were always just rows. We had a whole second system in the architecture diagram to babysit some rows.</p><p>Let me explain how we got here, and then how we got out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lO6963QgNIgwtJRWw66h3g.png" /></figure><h3>Every Node backend eventually grows a Redis</h3><p>Not because we needed it.</p><p>Because that’s just what you do.</p><p>You start with a nice little app. Then someone says “we should send that email in the background.” Then “we should resize that image later.” Then “we shouldn’t make the user wait for this.”</p><p>And every tutorial, every blog, every senior dev in the thread says the same word.</p><p>Queue.</p><p>So you add Redis. You add BullMQ on top of it. You add it to docker-compose. You add it to your infra. You add a new thing that can be down at 2AM.</p><p>For sending emails a little bit later.</p><h3>What we actually needed</h3><p>Strip the problem all the way down.</p><p>We had work to do. We wanted to do it <em>later</em>, and <em>outside</em> the request. We had multiple workers, and we needed them to not grab the same job at the same time.</p><p>That’s it. That’s the entire requirement.</p><p>And here’s the uncomfortable part.</p><p>Postgres could already do all of it. We just didn’t know the words.</p><h3>The jobs table you’ve written a hundred times</h3><p>Nothing clever here. A table. Some jobs.</p><pre>export const jobs = pgTable(&quot;jobs&quot;, {<br>  id: serial(&quot;id&quot;).primaryKey(),<br>  payload: jsonb(&quot;payload&quot;).notNull(),<br>  status: text(&quot;status&quot;).default(&quot;pending&quot;).notNull(),<br>  createdAt: timestamp(&quot;created_at&quot;).defaultNow().notNull(),<br>});</pre><p>A job is a row. It has some data. It has a status. That’s the whole model.</p><p>Now we need a worker to pick up a pending job and do it.</p><p>Sounds easy. It’s the part where everyone quietly gets it wrong.</p><h3>How we do it today (and why it’s cursed)</h3><p>The naive version looks completely reasonable:</p><pre>// grab the next pending job<br>const [job] = await db<br>  .select()<br>  .from(jobs)<br>  .where(eq(jobs.status, &quot;pending&quot;))<br>  .limit(1);</pre><pre>if (job) {<br>  await db.update(jobs)<br>    .set({ status: &quot;processing&quot; })<br>    .where(eq(jobs.id, job.id));</pre><pre>  await handle(job);<br>}</pre><p>Read that and it looks fine.</p><p>It is not fine.</p><p>Because you don’t have one worker. You have four. And all four run this at the same millisecond.</p><p>All four SELECT the same pending job. All four think it&#39;s theirs. All four run it.</p><p>That email you wanted to send once? Sent four times.</p><p>So this is the moment. This is where someone in the meeting says the sentence.</p><p>“Maybe we should add a real queue.”</p><p>And off we go. New service. New dependency. New 2AM.</p><p>For a race condition that Postgres has had a solution for since before most of our apps existed.</p><h3>The one keyword that fixes everything</h3><p>Here it is. This is the whole post really.</p><pre>const [job] = await db<br>  .select()<br>  .from(jobs)<br>  .where(eq(jobs.status, &quot;pending&quot;))<br>  .orderBy(jobs.createdAt)<br>  .limit(1)<br>  .for(&quot;update&quot;, { skipLocked: true });</pre><p>Look at the last line.</p><p>.for(&quot;update&quot;, { skipLocked: true })</p><p>That’s SELECT ... FOR UPDATE SKIP LOCKED in Drizzle.</p><p>Let me translate what it actually says, because the plain English is beautiful:</p><p>“Give me the next pending job. Lock it so nobody else can touch it. And if a row is already locked by someone else don’t wait, don’t fight, just skip it and find me a different one.”</p><p>Read that again.</p><p>Worker 1 grabs job A and locks it. Worker 2 comes in at the same instant, sees job A is locked, shrugs, and grabs job B instead. No collision. No double send. No coordination service in the middle.</p><p>The database <em>is</em> the coordinator. It always was.</p><h3>The actual worker</h3><p>Wrap it in a transaction so the lock holds while you claim it:</p><pre>async function takeNextJob() {<br>  return db.transaction(async (tx) =&gt; {<br>    const [job] = await tx<br>      .select()<br>      .from(jobs)<br>      .where(eq(jobs.status, &quot;pending&quot;))<br>      .orderBy(jobs.createdAt)<br>      .limit(1)<br>      .for(&quot;update&quot;, { skipLocked: true });</pre><pre>    if (!job) return null;</pre><pre>    await tx.update(jobs)<br>      .set({ status: &quot;processing&quot; })<br>      .where(eq(jobs.id, job.id));</pre><pre>    return job;<br>  });<br>}</pre><p>That’s the queue.</p><p>That’s the whole thing.</p><p>Run that on a loop in four workers, forty workers, and none of them will ever step on each other. Postgres handles it. Postgres was always going to handle it.</p><p>No Redis. No BullMQ. No extra box in the diagram.</p><h3>The part I keep thinking about</h3><p>Same jobs. Same table. Same rows. Same Postgres.</p><p>The only thing that changed was that we learned the database already knew how to hand out work without workers colliding.</p><p>We didn’t need a message broker.</p><p>We needed one keyword we’d never heard of.</p><p>And that’s the thing that’s been sitting with me. We added an entire system a service, a dependency, an on-call page, a 2AM to solve a problem the database next to it had already solved. Quietly. For years. In one clause.</p><p>Maybe it was never a queue problem.</p><p>Maybe it was just a keyword problem.</p><h3>The honest small print</h3><p>Because I’d rather say it than read it in the comments:</p><p>This is not “Redis is bad” or “BullMQ is bad.” They’re excellent. If you’re doing hundreds of thousands of jobs a minute, if you need priorities, delays, rate limiting, retries with backoff, and dashboards out of the box a dedicated queue earns its keep. SKIP LOCKED gives you the core trick, not the whole product.</p><p>Also: you don’t have to hand-roll this. If you want the Postgres-is-my-queue approach but with retries and scheduling already built, <strong>pg-boss</strong> and <strong>Graphile Worker</strong> both sit right on top of this exact mechanism. That’s literally what they do under the hood. Standing on their shoulders is not cheating.</p><p>And yes, at extreme scale a queue built on a log (Kafka, or a real broker) behaves differently than rows in a table. Know your numbers.</p><p>But for the 90% of us running thousands of background jobs resize this, email that, sync the other thing who added Redis purely out of habit?</p><p>You already have a queue.</p><p>It’s the database you’re already paying for.</p><p><em>I’m Rakesh, a full stack developer. I write here and on my own site too </em><a href="https://www.rakeshbhetariya.com/"><em>rakeshbhetariya.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d5fdf84d9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL 19 Property Graphs: Graph Queries Without a Graph Database]]></title>
            <link>https://medium.com/@Rakeshbhetariya/postgresql-19-property-graphs-graph-queries-without-a-graph-database-ba5373d99b9a?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba5373d99b9a</guid>
            <category><![CDATA[graphic-design]]></category>
            <category><![CDATA[property-graph]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 08:50:32 GMT</pubDate>
            <atom:updated>2026-07-17T08:50:32.824Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me start with something we all quietly agree on.</p><p>We use Postgres for almost everything.</p><p>Relations. JSON when we get lazy. Full text search. Then AI happened and everyone needed a vector database and Postgres said <em>pgvector.</em></p><p>Just like every database problem, Postgres tries to figure it out. And I say that because yesterday’s update is exactly the proof.</p><p><strong>Postgres 19 Beta 2 dropped, and it implements SQL/PGQ property graphs.</strong></p><p>Let me explain what that actually means,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noQRaJ_rvvljVeNoMRJyGw.png" /><figcaption>Property Graphs</figcaption></figure><h3>The thing we kept working around</h3><p>There was always one type of question Postgres made painful.</p><p>Not hard. Painful.</p><p>The “how are these two things connected” question.</p><p>Who follows who. Who knows who. Who bought what that someone else also bought. Who is two steps away from me.</p><p>The data was right there in our tables. We just had to write increasingly cursed SQL to get it out.</p><p>So what did we do? We added a graph database. Neo4j or something like it. New service. New sync pipeline. New thing that breaks at 2AM while the data is somehow both correct and wrong at the same time.</p><p>For a question our data could already answer.</p><h3>What SQL/PGQ actually is</h3><p>Here’s the part that made me stop and read it twice.</p><p>It is not a new storage engine. It is not a new database. Nothing gets copied. Nothing moves.</p><p>Your data stays in your normal tables.</p><p>You just tell Postgres:</p><blockquote><em>“Treat these tables as the </em>things<em>. Treat these tables as the </em>connections between the things<em>.”</em></blockquote><p>Things = vertices. Connections = edges.</p><p>That’s a graph. And now you can query it like one.</p><p>The graph is basically a read-only view over the tables you already have. Same planner. Same executor. Same Postgres. You can even mix graph queries and normal SQL in one query.</p><p>Nothing new to run. Nothing new to sync. Nothing new to break.</p><h3>Okay, Take Instagram As an Example</h3><p>Forget the abstract stuff. Let’s build the schema you’ve written a hundred times.</p><p>sql</p><pre>CREATE TABLE users (<br>    user_id integer PRIMARY KEY,<br>    username varchar<br>);</pre><pre>CREATE TABLE follows (<br>    follow_id integer PRIMARY KEY,<br>    follower_id integer REFERENCES users (user_id),<br>    followee_id integer REFERENCES users (user_id)<br>);</pre><p>Two tables. users, and follows. That&#39;s Instagram&#39;s skeleton.</p><p>Now the classic feature: <strong>friends of friends.</strong></p><p>People your friends follow, that you don’t follow yet. Suggestions. “People you may know.”</p><h3>How we do it today</h3><p>sql</p><pre>SELECT DISTINCT u3.username<br>FROM follows f1<br>JOIN follows f2 ON f1.followee_id = f2.follower_id<br>JOIN users u3 ON f2.followee_id = u3.user_id<br>WHERE f1.follower_id = 1<br>  AND f2.followee_id &lt;&gt; 1<br>  AND NOT EXISTS (<br>      SELECT 1 FROM follows f3<br>      WHERE f3.follower_id = 1<br>        AND f3.followee_id = f2.followee_id<br>  );</pre><p>Look at that.</p><p>It works. It’s fine. It’s also completely unreadable, and f1, f2, f3 are doing a lot of emotional labour there.</p><p>Come back to this in six months and you don’t read it you <em>decode</em> it.</p><p>And now imagine your PM says: <em>“can we go one level deeper? Friends of friends of friends.”</em></p><p>Another self-join. Another alias. The query grows. Your will to live shrinks.</p><p>That’s usually the exact moment someone in the meeting says <em>“maybe we should look at a graph database.”</em></p><h3>How it looks with SQL/PGQ</h3><p>First you declare the graph. <strong>Once.</strong></p><p>sql</p><pre>CREATE PROPERTY GRAPH insta<br>    VERTEX TABLES (<br>        users LABEL user<br>    )<br>    EDGE TABLES (<br>        follows<br>            SOURCE KEY (follower_id) REFERENCES users (user_id)<br>            DESTINATION KEY (followee_id) REFERENCES users (user_id)<br>            LABEL follows<br>    );</pre><p>Read what just happened.</p><p>Your users table became the dots. Your follows table became the arrows.</p><p>You didn’t create anything. You didn’t migrate anything. Your follows table was <em>always</em> an edge you just never called it that. The foreign keys were always the connections. We just never had the vocabulary.</p><p>Now the query:</p><p>sql</p><pre>SELECT DISTINCT suggestion_name<br>FROM GRAPH_TABLE (insta<br>    MATCH (me IS user WHERE me.user_id = 1)<br>          -[IS follows]-&gt;<br>          (friend IS user)<br>          -[IS follows]-&gt;<br>          (suggestion IS user)<br>    COLUMNS (suggestion.username AS suggestion_name)<br>);</pre><p>Now look at the middle of it. Just this line:</p><pre>(me)-[IS follows]-&gt;(friend)-[IS follows]-&gt;(suggestion)</pre><p><strong>“Me follows friend, friend follows suggestion.”</strong></p><p>That’s it. That’s the query.</p><p>That’s not SQL you decode. That’s the sentence you would say to a teammate if you were explaining the feature at a whiteboard. The arrows literally point in the direction the relationship goes.</p><p>Want to go one level deeper? Friends of friends of friends?</p><p>Add one more arrow.</p><pre>(me)-[IS follows]-&gt;(a)-[IS follows]-&gt;(b)-[IS follows]-&gt;(suggestion)</pre><p>Not another JOIN. Not another alias. Not another 20 minutes of your afternoon.</p><p>One arrow.</p><h3>The part I keep thinking about</h3><p>Same data. Same tables. Same rows. Same Postgres.</p><p>The only thing that changed was <strong>how we’re allowed to describe what we want.</strong></p><p>And that’s what’s been rattling around in my head since I read this.</p><p>We used to spin up an entire second database for this. A whole new system in the architecture diagram. New ops burden, new failure mode, new sync layer, new on-call page.</p><p>Maybe it was never a data problem.</p><p>Maybe it was just a <strong>syntax</strong> problem.</p><p>We didn’t need a different engine. We needed a different way to <em>look</em> at the same rows.</p><h3>The honest small print</h3><p>Because I’d rather say it than have someone say it in the comments:</p><ul><li><strong>It’s beta.</strong> Postgres 19 Beta 2, not GA. Don’t put it in prod this week.</li><li><strong>Property graphs are read-only.</strong> They’re views over your tables. You still write to the tables the normal way.</li><li><strong>This is not full Neo4j.</strong> No shortest-path yet, and the deeper graph-algorithm stuff isn’t here.</li></ul><p>So if you’re doing serious graph algorithms at scale, a real graph database still has a job.</p><p>But for the 90% of us who just wanted “friends of friends” without adding a second database to our lives? This is it. This is the whole thing.</p><h3>Why this keeps happening</h3><p>Notice the pattern.</p><p>Mongo was going to eat Postgres. Then Postgres shipped JSONB. Vector databases were the next big line item. Then pgvector showed up. Now graph databases.</p><p>Postgres has spent a decade quietly deleting line items from our architecture diagrams.</p><p>Every few years we get excited about a specialised database, and a while later Postgres just… absorbs the useful 90% of it and hands it to us as a feature. No migration. No new service. Just an upgrade.</p><p>At some point the question stops being <em>“which database do I add?”</em></p><p>And starts being <em>“what’s left that Postgres won’t eventually do?”</em></p><p>Genuinely curious what you think after this, would you still reach for a dedicated graph DB?</p><p>Docs if you want to go deeper: <a href="https://www.postgresql.org/docs/19/ddl-property-graphs.html">PostgreSQL 19 — Property Graphs</a> and <a href="https://www.postgresql.org/docs/19/queries-graph.html">Graph Queries</a>.</p><blockquote>I’m Rakesh a full stack developer. I write here and on my own site too <a href="https://www.rakeshbhetariya.com/">rakeshbhetariya.com</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba5373d99b9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 12 Things You Skipped After Launching Your Website]]></title>
            <link>https://medium.com/@Rakeshbhetariya/the-12-things-you-skipped-after-launching-your-website-9874fd088bf6?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/9874fd088bf6</guid>
            <category><![CDATA[website]]></category>
            <category><![CDATA[seo-tips]]></category>
            <category><![CDATA[google-search-console]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[google-analytics]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 17:17:03 GMT</pubDate>
            <atom:updated>2026-07-15T17:17:03.109Z</atom:updated>
            <content:encoded><![CDATA[<p>You did it.</p><p>You designed it. You coded it. You deployed it. You sent the invoice.</p><p>You even checked the contact form. Twice.</p><p>Then you closed the tab and moved on with your life.</p><p>Cute.</p><p>Here’s what’s happening while you’re celebrating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*epiTuBrYshRxPUEmyz6ayA.png" /></figure><p>Google has no idea your website exists. Your pages are loading like it’s 2009 on mobile. Visitors are landing, getting confused, and leaving in 6 seconds and you’ll never know, because you didn’t install anything that could tell you.</p><p>Your website isn’t live.</p><p>It’s on life support. And nobody’s monitoring the machines.</p><p>I know this because I did exactly the same thing. For more than 10 client websites. Build, deploy, invoice, disappear. I thought “launched” meant “finished.”</p><p>It doesn’t. Launch day is day one, not the finish line.</p><p>The fix isn’t advanced SEO. It’s not ads. It’s not some growth-hacking nonsense.</p><p>It’s 12 boring, unsexy, takes-a-few-minutes things that most people skip and then wonder why their beautiful website gets zero traffic.</p><p>I wrote the full checklist here:</p><p>👉 <a href="https://www.rakeshbhetariya.com/blog/what-to-do-after-launching-a-website">What To Do After Launching a Website: 12 Important Steps</a></p><p>Read it before your next visitor finds the problems instead of you.</p><p>Or don’t. Google doesn’t know your site exists anyway.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9874fd088bf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleaning Up Docker Remove Unused Images, Containers & Save Space]]></title>
            <link>https://medium.com/@Rakeshbhetariya/cleaning-up-docker-remove-unused-images-containers-save-space-7151c45f3fa6?source=rss-c337ee5c5072------2</link>
            <guid isPermaLink="false">https://medium.com/p/7151c45f3fa6</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-swarm]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Rakesh Bhetariya]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 18:21:01 GMT</pubDate>
            <atom:updated>2026-04-12T18:21:01.272Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is part of my <strong>Docker Basics Series</strong>, where I explain Docker step-by-step in a simple and practical way.</p><p>If you’ve followed the series till now, you’ve learned:</p><ul><li>How to run containers</li><li>Build images using Dockerfile</li><li>Use Docker Compose</li><li>Manage volumes &amp; networking</li><li>Dockerize a real application</li><li>Publish images to Docker Hub</li></ul><p>Now comes something every developer eventually faces:</p><p><strong>“Why is Docker taking so much space?”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXZ66d81IDg0b7fiLmmjXQ.jpeg" /></figure><h3>The Problem</h3><p>After using Docker for some time:</p><ul><li>You have dozens of images</li><li>Many stopped containers</li><li>Unused volumes</li><li>Old builds</li></ul><p>And suddenly:</p><p>Disk space is gone<br>System becomes slow<br>Docker feels heavy</p><h3>The Solution</h3><p><strong>Clean up Docker regularly</strong></p><p>Docker keeps everything by default:</p><ul><li>Containers</li><li>Images</li><li>Volumes</li><li>Cache</li></ul><p>Nothing is removed automatically.</p><h3>Simple Understanding</h3><p>Docker doesn’t delete anything unless you tell it to.</p><p>So over time:</p><pre>Unused stuff → Keeps increasing → Takes space</pre><h3>Check What’s Using Space</h3><pre>docker system df</pre><p>This shows:</p><ul><li>Images size</li><li>Containers</li><li>Volumes</li><li>Build cache</li></ul><h3>Removing Containers</h3><h3>Remove stopped containers:</h3><pre>docker container prune</pre><h3>Removing Images</h3><h3>Remove unused images:</h3><pre>docker image prune</pre><h3>Remove all unused images:</h3><pre>docker image prune -a</pre><h3>Removing Volumes</h3><pre>docker volume prune</pre><p>Be careful this deletes stored data</p><h3>Removing Networks</h3><pre>docker network prune</pre><h3>One Command to Clean Everything</h3><pre>docker system prune</pre><h3>Remove everything including images:</h3><pre>docker system prune -a</pre><h3>What This Command Does</h3><p>It removes:</p><ul><li>Stopped containers</li><li>Unused networks</li><li>Dangling images</li><li>Cache</li></ul><p>Cleans your system instantly</p><h3>Important Warning</h3><p>Before running cleanup:</p><p>Make sure you don’t need that data</p><p>Especially:</p><ul><li>Volumes</li><li>Databases</li><li>Important images</li></ul><h3>Best Practices</h3><ul><li>Clean Docker weekly</li><li>Use meaningful image tags</li><li>Remove unused containers regularly</li><li>Avoid keeping unnecessary builds</li><li>Monitor disk usage</li></ul><h3>Real-World Impact</h3><p>Without cleanup:</p><p>Disk full<br>Slow builds<br>Confusing environment</p><p>With cleanup:</p><p>Faster system<br>Clean workspace<br>Better performance</p><h3>What You Learned</h3><p>You now know:</p><p>How Docker stores data<br>How to remove containers, images, volumes<br>How to free disk space<br>How to maintain Docker properly</p><h3>Final Step in the Series</h3><p>You’ve now learned:</p><p>Containers<br> Images<br> Dockerfile<br> Compose<br> Volumes<br> Networking<br> Real app<br> Docker Hub<br> Cleanup</p><p>This is a <strong>complete Docker foundation</strong></p><h3>Docker Basics Series Completed</h3><p>If you followed all blogs:</p><p>First of all thank you so much and you’re now <strong>ahead of most beginners</strong></p><p><strong>Written by Rakesh Bhetariya</strong><br>Full-Stack Developer | Docker Basics Series</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7151c45f3fa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>