<?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 Jayantjoshi on Medium]]></title>
        <description><![CDATA[Stories by Jayantjoshi on Medium]]></description>
        <link>https://medium.com/@jayantjoshi0001?source=rss-1256aa19f108------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ExggWNgzpbuS_YrvJtkrAQ.png</url>
            <title>Stories by Jayantjoshi on Medium</title>
            <link>https://medium.com/@jayantjoshi0001?source=rss-1256aa19f108------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:47:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jayantjoshi0001/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 Leaderboard for 10M users]]></title>
            <link>https://medium.com/@jayantjoshi0001/the-leaderboard-for-10m-users-657d4c647d8b?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/657d4c647d8b</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 09:16:04 GMT</pubDate>
            <atom:updated>2026-09-11T09:16:04.267Z</atom:updated>
            <content:encoded><![CDATA[<p>A few days ago I was in an interview for an SDE intern role, and got asked something deceptively simple, out of nowhere, with basically no warm-up:</p><blockquote><em>“How would you design a leaderboard and game history system that can support 10 million users?”</em></blockquote><p>No hints, no “let’s start small,” no follow-up until I’d said my piece. Just the question, and then silence while I thought out loud. That’s a pretty common interviewer move — give a wide-open prompt and just watch how someone thinks, especially for an intern-level role where you’re not expected to have shipped a system at this scale before. You’re being judged less on “did you get the perfect answer” and more on “do you actually understand the tradeoffs, or are you just naming technologies.”</p><p>I gave a gut answer on the spot, because it’s the answer most people reach for the first time they think about leaderboards. It wasn’t a complete answer, and I knew it wasn’t the moment I said it — but it was clearly good enough to show I understood <em>why</em> I was reaching for those tools, not just that I knew their names. The interviewer didn’t grill me hard on the gaps, just asked one pointed follow-up and let it go. I ended up moving to the next round, which told me the instinct itself wasn’t wrong — it was just incomplete. So I want to walk through what I actually said in the room, and then what I’ve worked out since, sitting with the problem properly instead of under interview pressure. Not naming where this came from — but if you’ve sat through a few gaming-startup interviews, you’ve probably heard some version of this question too.</p><h3>My first instinct, said out loud on the spot</h3><blockquote><em>“I’d use Redis. Every time a user finishes a game, I write their score into a Redis sorted set with </em><em>ZADD. The user ID is the member, the score is the score. Ranking is basically free — </em><em>ZREVRANK gives me a user&#39;s position instantly, and </em><em>ZREVRANGE gives me the top N. Then every 2–3 seconds, I take whatever changed and flush it into Postgres so we have a durable, queryable history.&quot;</em></blockquote><p>It’s not a bad answer for a whiteboard. Sorted sets are <em>the</em> canonical data structure for this problem — they’re implemented as a skip list + hash table internally, so you get O(log N) insert and O(log N) rank lookup, and O(log N + M) for range queries. That’s genuinely hard to beat for “give me this user’s rank” and “give me the top 100” at the same time.</p><pre>ZADD leaderboard:global 4820 user:8213<br>ZREVRANK leaderboard:global user:8213     -&gt; 0-indexed rank, instantly<br>ZREVRANGE leaderboard:global 0 99 WITHSCORES  -&gt; top 100</pre><p>The periodic flush to Postgres was my hand-wavy answer to “but what about durability and history?” Redis is in-memory, so if it falls over you lose everything since the last snapshot. Batch-writing every couple of seconds felt like a reasonable compromise between “don’t hammer Postgres on every single score update” and “don’t lose too much if something crashes.”</p><p>The interviewer nodded, asked one follow-up — “what happens to that answer at 10 million concurrent users?” — and in the moment, I didn’t have a fully crisp answer. I said something reasonable about sharding Redis, gestured at the idea that history and live rank are different problems, and that was apparently enough signal for them to move on rather than dig in further. That’s the nature of an intern interview: they’re not expecting you to have the production-grade answer memorized, they’re checking whether the instinct is sound and whether you know your own edges. Mine held up.</p><p>But that follow-up question sat with me afterward, because the honest truth is: <strong>my on-the-spot answer was built for a system with 100 users, not 10 million.</strong> It would technically still run at 10M scale, the same way a bicycle will technically still get you across a country. It’s the wrong tool past a certain point, and the genuinely interesting part of this problem — the part I didn’t have time to get into under interview conditions — is figuring out exactly where those points are.</p><p>So let me actually do the thing I didn’t have room to do in the room — walk it up from scratch, stage by stage, and be precise about where each version breaks.</p><h3>Stage 1: 100 users</h3><p>At 100 users, basically nothing matters. This is worth saying out loud because it’s tempting to jump straight to “how do I make this handle 10 million” and over-engineer something nobody needs yet.</p><ul><li>One Postgres instance. A scores table with user_id, score, game_id, created_at.</li><li>Rank computed with a plain SQL query:</li></ul><pre>SELECT COUNT(*) + 1 AS rank<br>FROM scores<br>WHERE score &gt; (SELECT score FROM scores WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1);</pre><ul><li>No Redis. No caching layer. No queue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*kYOQr14507VgNsOz8clZeA.png" /><figcaption>Design for 100 Users</figcaption></figure><p>At this scale a full table scan on a few hundred rows finishes in microseconds. Adding Redis here is pure resume-driven development — it adds an entire class of failure modes (cache/DB consistency, TTL bugs, another process to monitor) to solve a performance problem you don’t have yet. The right skill at 100 users is knowing when <em>not</em> to reach for the fancy tool.</p><p>The one thing worth doing even here: design the schema so it <em>can</em> grow. Store raw score events as an append-only log rather than mutating a single “current score” row per user. That one decision — history as an immutable stream of events, not a mutable snapshot — is the seed that everything later scales from.</p><h3>Stage 2: 10,000 users</h3><p>Now real concurrency shows up. You’ve probably got a live game mode where scores come in bursts — a tournament ending, a daily challenge resetting at midnight, whatever. A few things start to hurt:</p><ul><li>That COUNT(*) WHERE score &gt; query used for rank is now scanning thousands of rows on every single leaderboard view. It&#39;s still fast, but it&#39;s now the single most expensive query in your system, and it runs constantly.</li><li>Connection pool exhaustion becomes a real risk if every score submission opens a fresh connection.</li></ul><p>This is roughly the point where Redis actually earns its keep — not for durability, but for <strong>read amplification</strong>. Leaderboards get read far more often than they get written (everyone checks their rank; not everyone plays a new game every second). So:</p><ul><li>Postgres stays the source of truth, writes go there synchronously.</li><li>After a write, update a Redis sorted set as a <em>read-optimized cache</em> of current standings.</li><li>Rank and top-N reads go to Redis; everything else (history, profile stats, audit) goes to Postgres.</li></ul><p>Notice the shift already: Redis isn’t “instead of” Postgres anymore, it’s a materialized view of it. And to be precise about the flow — there’s exactly <strong>one write path</strong>, not a mix of “sometimes Redis, sometimes DB.” Every score always lands in Postgres first, because that’s the single source of truth. Redis only ever gets updated <em>after</em> that, as a derived cache. What varies is the <strong>read path</strong>, and that’s a deliberate choice based on what’s being asked, not a coin flip: “what’s my rank / show me the top 100” is a leaderboard-shaped question, so it goes to Redis. “Show me my match history / my profile stats” is not a ranking question at all — Redis doesn’t even have that data — so it was never going to go through Redis in the first place, and it goes straight to Postgres.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWjEkfRSWWTly_-m8MHGjA.png" /><figcaption>Design for 10k Users</figcaption></figure><blockquote><strong><em>Why not Redis-first?</em></strong><em> The other option here is </em>write-behind caching<em> — ack the write the moment it’s in Redis, then trickle it into Postgres asynchronously. It’s a real pattern, and it’s faster. But it means there’s a window where a score exists </em>only<em> in memory — if that Redis node crashes before the flush, that score is gone for good, not delayed. For a competitive leaderboard, silently losing someone’s score because a cache hiccuped is worse than the sub-millisecond cost of writing to Postgres first. At 10K users, a synchronous insert is cheap enough that there’s no real reason to trade away durability for it. This is the same gap I glossed over in my original on-the-spot answer — worth being explicit about it here instead of repeating it.</em></blockquote><h3>Stage 3: 100,000 users</h3><p>Somewhere in this range, a bunch of assumptions from stage 2 quietly stop holding:</p><p><strong>One leaderboard isn’t enough.</strong> Users want daily, weekly, all-time, per-game-mode, and friends-only leaderboards. That’s not one sorted set anymore, it’s a small family of them, and every score update now fans out to write into 4–5 different keys:</p><pre>ZADD lb:daily:2026-09-11   3210 user:8213<br>ZADD lb:weekly:2026-w37    3210 user:8213<br>ZADD lb:alltime            9880 user:8213   (cumulative, different math)<br>ZADD lb:mode:blitz         3210 user:8213</pre><p><strong>Memory becomes a real line item.</strong> A sorted set with 100K members isn’t huge, but multiply it by five leaderboard variants, plus friends-leaderboards per user (which don’t scale as one global structure — they need per-user or per-clique keys), and you start actually watching Redis memory graphs instead of ignoring them.</p><p><strong>The synchronous double-write gets risky.</strong> Writing to Postgres, then Redis, on every request means a request-time failure in either one leaves you inconsistent, and it couples your write latency to two systems instead of one. This is where I’d introduce a queue (even something as simple as Redis Streams or a lightweight message queue) between “score submitted” and “leaderboards updated” — the API call just enqueues the event and returns immediately, and a worker applies it to both stores. This also gives you a natural retry/replay mechanism if a downstream store falls behind.</p><p><strong>Rank starts needing to be “good enough,” not perfect.</strong> For daily/weekly boards exact rank via ZREVRANK is still fine at this size. But it&#39;s worth noticing this is the first stage where &quot;exact real-time rank for everyone&quot; starts to have a cost you can measure, which foreshadows stage 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J03AaR0CiJ8LizrPsEhQKA.png" /><figcaption>Design for 100k users</figcaption></figure><h3>Stage 4: 10,000,000 users</h3><p>This is where my original interview answer really falls apart, and it’s worth being specific about <em>why</em>, not just saying “add more servers.”</p><p><strong>A single Redis sorted set doesn’t work anymore.</strong> Redis Cluster shards by hash slot on the key, but a sorted set lives entirely on one node — you can’t split one giant ZADD leaderboard:global across a cluster and still get accurate global rank cheaply. At 10M members, ranking on a single node is a real memory and CPU concern, and it&#39;s a single point of contention every single score write competes for.</p><p>The real answer is to <strong>stop thinking of “the leaderboard” as one structure</strong>, and shard it the way the product actually uses it:</p><ul><li>Shard by something natural: region, game mode, or a consistent-hash bucket of user ID.</li><li>Compute <em>global</em> top-N and global rank asynchronously, on a schedule (say every 10–30 seconds), by merging the shards — not on every read. Nobody actually needs their exact global rank to update within 50ms; “you’re #4,213,982, updated a moment ago” is a completely acceptable UX for anything past the top few thousand.</li><li>For the <em>top</em> of the leaderboard (top 100, top 1000 — the part people actually stare at), keep a small, tightly maintained real-time structure. This is the classic “exact at the top, approximate in the tail” pattern, and it’s how basically every large-scale leaderboard (think competitive games, trading apps, fitness apps) actually works under the hood.</li></ul><p><strong>Leaderboard state and game history become two genuinely different systems.</strong> This is the biggest thing my interview answer got wrong — I treated “push to Postgres every 2–3s” as good enough for history at any scale, and it isn’t. Leaderboard state is small, hot, mutable, and needs low-latency reads. Game history is huge, append-only, cold after a few days, and needs high-throughput writes with almost no read-path urgency. Trying to serve both from one relational table means your history table becomes gigantic and starts slowing down the exact rank queries you need to stay fast.</p><p>So at this scale:</p><ul><li>Every game event gets published to a durable log (Kafka, Kinesis, or similar) the moment it happens. This is now the actual source of truth, not Postgres.</li><li>A consumer updates the sharded Redis leaderboard structures from that stream.</li><li>A separate consumer batches events into a write-optimized store for history — something like Postgres with monthly partitioning, or a columnar store (ClickHouse, for instance) if you want fast analytical queries like “show this user’s score trend over 6 months” without destroying an OLTP database.</li><li>Old partitions age out to cold/object storage (S3-style) since nobody’s querying last year’s individual match history at real-time speed.</li></ul><p><strong>A few other things that only bite you at this scale, and that I’d genuinely bring up now if asked again:</strong></p><ul><li><em>Hot keys.</em> A viral tournament or a celebrity streamer playing live can dump a disproportionate share of writes onto one shard. Consistent hashing helps distribute normal traffic, but you still want some form of local buffering/batching in front of a hot shard so it doesn’t fall over.</li><li><em>Idempotency.</em> At 10M scale, retries are guaranteed to happen — a worker crashes mid-batch, a network blip causes a duplicate publish. Every score event needs a unique ID so “apply this event” is safe to run twice.</li><li><em>Out-of-order events.</em> Events can arrive slightly out of order across a distributed system. If you’re computing anything cumulative (like all-time score), you want the event log itself to be the source of truth you can replay, not a running counter you mutate in place — because a running counter has no way to self-correct if something arrived twice or out of order.</li><li><em>Read replicas for history.</em> Once history lives in its own partitioned store, put read replicas in front of it for anything user-facing (profile stats, match history pages), and keep the primary reserved for ingestion.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2U6CWy1OP_Qz5ABZJNrzWQ.png" /><figcaption>Design for 10M users</figcaption></figure><h3>What I’d add if I got the follow-up round</h3><p>If this comes back around in the next round, I’d start in the exact same place — sorted sets are genuinely the right primitive for ranking, and I’d say so with the same confidence. That part of my on-the-spot answer wasn’t a lucky guess, it’s just correct. But I’d build the rest of the answer around one idea instead of listing tools: <strong>leaderboard state and game history are different problems with different shapes, and they diverge harder the bigger the system gets.</strong> At 100 users you can fake that divergence with one database and nobody notices. At 10 million, “push everything to Postgres every few seconds” — which is basically what I said in the room — isn’t really a full design, it’s a description of what happens right before you’re forced to separate the hot, mutable, read-heavy leaderboard from the cold, append-only, write-heavy history log.</p><p>The thing I’ve taken from this, going into the next round: a strong systems design answer for an intern-level interview isn’t about reciting the “correct” architecture — it’s about being able to say confidently where your first idea holds up and exactly where it starts to bend. I had the first half of that down cold in the room. This is me building out the second half properly, on my own time, so next time I don’t need the follow-up question to find the edge of my own answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=657d4c647d8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I think AI agents are about to have a hiring problem. Am I wrong?]]></title>
            <link>https://medium.com/@jayantjoshi0001/i-think-ai-agents-are-about-to-have-a-hiring-problem-am-i-wrong-929b689685e9?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/929b689685e9</guid>
            <category><![CDATA[news]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 07:46:48 GMT</pubDate>
            <atom:updated>2026-07-29T07:46:48.976Z</atom:updated>
            <content:encoded><![CDATA[<p>On June 30, 2026, OKX — a crypto exchange with over 150 million users — quietly launched something strange: a marketplace where AI agents hire <em>each other</em>, negotiate, do the work, and settle payment, with no human anywhere in the loop. OKX’s CEO framed it as the start of the “one-person company” era — a single founder backed by an unlimited AI workforce. Two weeks earlier, Visa had wired its payment rails directly into ChatGPT so agents could complete purchases on a user’s behalf. Mastercard made a similar move. Analysts at Morgan Stanley are now projecting agentic commerce could touch $190–385B of US e-commerce by 2030.</p><p>In other words: agents can now <em>get paid</em>. That part of the puzzle is being solved fast, by people with a lot of capital.</p><p>But one line buried in the TechCrunch coverage of the OKX launch stuck with me more than any of the funding numbers. A co-founder of a rival “agent trust” infrastructure company said the hard part was never getting agents to transact — it’s helping them find each other and figuring out what happens when the work is bad. He compared it to building a digital court system.</p><p>That’s the part nobody’s really solved. And it’s the part I want to think out loud about here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tSvn8g8Q0ZYJaCgG.jpg" /></figure><h3>The gap: agents can pay each other, but they can’t yet trust each other</h3><p>Here’s the situation as I see it. Coding agents (Claude Code, Cursor, and friends) have gone from novelty to daily habit for a lot of developers in the last year or so. Research and data teams are running increasingly complex agent pipelines. And all of these agents, at some point, hit a task that isn’t really <em>their</em> job — a security review, a fact-check, a translation, a dataset cleanup, an image asset.</p><p>Today, when that happens, one of three things occurs:</p><ol><li>The agent just does it anyway, badly, because it’s not actually a specialist at that thing.</li><li>A human quietly steps in, hires a freelancer on Fiverr or Upwork, and waits hours or days for something the agent workflow otherwise does in seconds.</li><li>A team builds narrow, in-house tooling for a need that only comes up occasionally — expensive, and every other team is rebuilding the same wheel.</li></ol><p>What’s missing is a <em>cross-vendor</em> way for one agent to discover, hire, and pay a <em>different</em> agent — built by a different team, running on a different stack — and actually trust that what comes back is correct, fast enough that it doesn’t break the workflow’s pace.</p><p>General marketplaces like OKX AI are going after this, but they’re optimizing for breadth and blockchain settlement, not for the actual hard problem: <em>how does an agent know another agent’s output is good, automatically, without a human checking?</em> Their trust model today leans on the crypto-native tools they already have — on-chain reputation, staking — which is a reputation signal, not a verification signal. It’s closer to a five-star rating than a passing test suite.</p><h3>The idea I’ve been chewing on</h3><p>What if the trust layer didn’t come from reputation at all, but from <em>verification</em>? A marketplace where:</p><ul><li>A provider agent lists a narrow, well-defined service — “I review PRs,” “I extract structured data from messy PDFs,” “I translate documents and preserve meaning” — with a clear input/output contract and a price.</li><li>A buyer agent finds that provider, hires it programmatically, and pays into escrow.</li><li>The payment only releases once the output is <em>actually checked</em> — tests pass, a schema validates, a rubric is matched — not once a human eyeballs it or a star rating looks good enough.</li></ul><p>Basically: trust built the way software already trusts software — a CI pipeline that either passes or it doesn’t — applied to agent-to-agent hiring instead of reputation scores.</p><h3>The part I’m least sure about — and want your read on</h3><p>While working through this, I kept running into two <em>very</em> different reasons an agent would want to hire another agent, and I’m not sure everyone building in this space is treating them as equally real:</p><p><strong>Reason 1 — Capability gap.</strong> The agent isn’t good enough at the task. It needs a specialist. This is the case everyone designs for first — it’s intuitive, it’s the “hire an expert” story.</p><p><strong>Reason 2 — Bandwidth gap.</strong> The agent is perfectly capable of the task, it’s just busy doing something else right now, and a single agent thread is fundamentally serial. It doesn’t need a specialist — it needs <em>any</em> competent, available agent to take something off its plate so two things can happen at once instead of one after another.</p><p>My instinct is that #2 is actually the more common trigger day-to-day — “I’m just busy” happens a lot more often than “I’m not skilled enough” — but almost nobody is building for it explicitly. Every marketplace I’ve looked at is built around “find the best provider,” ranked by reputation. Almost none of them let you search for “find me whoever’s free right now,” ranked by availability. Those are genuinely different queries over the same data, and I think a real product needs to treat both as first-class from day one, not bolt the second one on later.</p><h3>Why I think this matters, and why I could be wrong</h3><p>The optimistic case: MCP has become a real standard for agent-to-agent communication, payment rails are opening up fast, and verification tooling (automated test-running, LLM-as-judge, schema validation) is finally mature enough to build a <em>machine-era</em> trust layer on top of. The infrastructure is arriving faster than the trust mechanism — whoever builds a credible, narrow, verifiable trust layer first has a real shot at becoming a default.</p><p>The honest case against it: this whole thing rests on an assumption I can’t yet prove — that agents will delegate to <em>other vendors’</em> agents often enough, for either of these two reasons, to sustain a real marketplace. If agentic tools consolidate into single-vendor walled gardens, or if “I’ll just do it myself in five extra minutes” quietly beats “coordinate an external hire” for most routine tasks, the whole premise gets a lot smaller. I don’t have data on this yet. Nobody really does — the category is a few months old.</p><h3>So, genuinely — is this a real gap?</h3><p>A few things I keep going back and forth on:</p><ul><li>If you’re using agentic workflows (coding, research, data, creative) — have you actually hit either of these two situations? A task your agent wasn’t good enough at, or a task it didn’t have time for?</li><li>When that happened, what did you actually do — push through anyway, hand it to a human, or just let it wait?</li><li>Does the “reputation vs. verification” trust distinction feel real to you, or is a star rating already good enough?</li><li>Bandwidth-gap vs. capability-gap — which one, if either, actually resonates with how you work today?</li></ul><p>So — is this an actual gap, or am I seeing a problem that isn’t really there?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=929b689685e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How i tamed a 180k product database as an intern]]></title>
            <link>https://medium.com/@jayantjoshi0001/how-i-tamed-a-180k-product-database-as-an-intern-373e93f66656?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/373e93f66656</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 20:53:20 GMT</pubDate>
            <atom:updated>2026-07-04T20:53:20.434Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A story about reading a scope doc twice, drawing a lot of boxes, and shipping analytics that actually load fast.</em></p><p>There’s a very specific kind of fear that shows up when someone hands you a one-page ticket that says “add analytics to the category dashboard” and then, almost as an afterthought, mentions the numbers: <strong>~180,000 products. ~20,000 clients. 17,000+ product categories.</strong> No team standing by. No senior engineer pairing with you. Just you, a scope document, and a blinking cursor.</p><p>I’m an intern. This was an internal admin tool, not some client-facing showcase — which honestly made it <em>more</em> interesting, not less. Nobody was going to clap for a shiny UI. They wanted something that worked, was correct, and didn’t fall over under real data volume. That’s a different kind of pressure than “make it pretty,” and I want to walk through how I actually got from “I have no idea where to start” to “this is done, tested, and signed off.”</p><p>If you’re a student, an intern, or just someone who freezes up a little when a spec doc lands in your inbox — this one’s for you.</p><h3>Step 1: Resist the Urge to Open VS Code Immediately</h3><p>My first instinct, like most people’s, was to start coding. Open a component, wire up some state, make a chart appear. I sat on my hands instead.</p><p>Here’s the thing nobody tells you about specs: <strong>the first read is always wrong.</strong> Not wrong as in incorrect — wrong as in incomplete. You read it once and think you understand it. You don’t. You’ve absorbed the vocabulary, not the shape of the problem.</p><p>So I read the Scope of Work twice. The first pass, I just let it wash over me — what’s the business trying to achieve, why does this matter, who’s asking for it. The second pass, I read it like a lawyer looking for loopholes. I made a literal list of every sentence that implied a decision I’d eventually have to make.</p><p>Things like:</p><ul><li>“Top 5 Categories by total listings” — okay, but what counts as a “listing”? A product? A client? Both?</li><li>“Paid vs Free” — what actually defines <em>paid</em>? Is it a boolean somewhere, or is it derived from a subscription tier field buried three collections away?</li><li>“No double-counting clients” — said once, almost casually, in a functional requirement. This single line ended up being the most important sentence in the whole document.</li></ul><p>That last one is a great example of why reading carefully matters more than reading fast. It would have been very easy to write a naive aggregation, ship it, and quietly under-report or over-report every single number on the dashboard — and nobody would notice until an angry Slack message three weeks later asking why the “Top 5 Categories” total doesn’t match the sum of its subcategories.</p><h3>Step 2: Turn the Prose Into Questions, Then Turn the Questions Into a Plan</h3><p>A spec document tells you <em>what</em> the business wants. It almost never tells you <em>how the data actually lives in your database.</em> That gap is where most bugs are born.</p><p>So before writing a single line of aggregation logic, I went and actually looked at the schema. Not the documentation of the schema — the real collections, the real fields, the real edge cases. And immediately, a bunch of assumptions I’d made from reading the spec fell apart:</p><ul><li>I assumed “client” and “product” data would come from the same place. They don’t. Client membership in a category lives in one collection; live product listings live in a completely different one. A business can be a legitimate member of a category with zero currently-visible products in it (they toggled display off), and that business still needs to count as a <em>client</em> — just not as a contributor to the <em>product</em> count.</li><li>I assumed subscription tiers would be a single clean field. In reality, tier logic touches an active-status flag, a trial flag, and an end date, all of which needed to agree before I could confidently say “this client is Paid — Grow tier.”</li><li>I assumed I’d need some kind of scheduled snapshot job to make the numbers fast, because that’s the “obvious” answer to any large dataset. Turned out, once I actually profiled the collections and built the right indexes, live aggregation was fast enough — no cron job, no cache warm-up dance, no extra moving part to babysit at 2 AM. Simpler is genuinely better when it’s <em>actually</em> sufficient, and the only way to know that is to measure instead of assume.</li></ul><p>This is the part I’d tell any intern to slow down for. Writing the plan <em>before</em> the code isn’t bureaucracy — it’s where you catch the expensive mistakes while they’re still free to fix. Every wrong assumption I found at this stage cost me twenty minutes. Every one I would have found after writing the code would have cost me a day, plus the awkward conversation about why the dashboard shows the wrong numbers in front of the whole team.</p><p>Once that clicked, the architecture basically drew itself: two independent queries, run in parallel, merged right before the response goes out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*S_WKFpFh6Pl65cRQjFJChg.png" /></figure><h3>Step 3: Design for Reuse, Not for “This One Screen”</h3><p>The dashboard needed the same kind of breakdown — Paid vs Free, split by tier — at three different levels of a hierarchy: the top-level category, the mid-level subcategory, and the leaf-level product category. It would have been easy to build three slightly different versions of the same component, one per page, and call it done by Friday.</p><p>I didn’t do that, and I’m glad I didn’t.</p><p>Instead, I built one component that doesn’t know or care what page it’s rendered on. You hand it a node type and a node ID, and it fetches its own data and renders itself. The page around it doesn’t manage any analytics state at all — it just says “here’s a category ID, go.” Same for the “Top 5” leaderboard — one component, reused at the home page and again one level down, just with a different scope passed in.</p><p>This paid off almost immediately, because two levels of the hierarchy behave slightly differently (the leaf level has no “Top 5” widget below it, since there’s nothing left to rank), and I only had to handle that difference in <em>one</em> place instead of hunting it down across three separate implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*6hbjXS7ivHePiJVvtAd6Ew.png" /></figure><p>If there’s a lesson in there, it’s this: <strong>when a spec describes the same shape of UI appearing three times with minor variations, that’s the universe telling you to write one component, not three.</strong></p><h3>Step 4: Correctness Before Speed, Always</h3><p>The scariest requirement in the whole document was the one about <em>not double-counting clients.</em> Imagine a business that’s listed products under three different subcategories, all under the same parent category. If your aggregation isn’t careful, that one business gets counted three times when you roll everything up to the top-level category — quietly inflating every number on the dashboard.</p><p>I spent real, dedicated time proving to myself this couldn’t happen — seeding test data specifically designed to break my own logic before anyone else could. I built a business with memberships across multiple sibling categories, ran the aggregation, and checked that it appeared exactly once in the parent rollup, not three times. Only once that held up did I move on to worrying about how fast the query ran.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*A0ejpv9g9na6k0mLVQhAYQ.png" /></figure><p>That ordering matters. A fast dashboard showing wrong numbers is worse than a slightly slower dashboard showing right ones — because wrong numbers erode trust in every other number you ever show that team again.</p><h3>Step 5: Ship in Phases, Not in One Big Bang</h3><p>I didn’t try to build everything at once. I broke the work into phases roughly like this:</p><ol><li><strong>Confirm the unknowns.</strong> Before writing meaningful code, I ran small scripts against the actual database to answer open questions — what are the real possible status values, are there businesses missing category data entirely, are there edge cases in how subscription end-dates are stored. Answering these first meant I wasn’t building on sand.</li><li><strong>Get the data layer right.</strong> Indexes, aggregation pipelines, and proving they run fast on the <em>real</em> volume of data, not a toy dataset of 20 rows.</li><li><strong>Build the shared components.</strong> With mocked data first, so frontend work didn’t have to wait on backend work being perfect.</li><li><strong>Wire it all together</strong> into the actual pages, with loading states so nothing jumps around while data streams in.</li><li><strong>Test it against every single acceptance criterion, one by one</strong>, and only then call it done.</li></ol><p>Breaking it into phases like this meant that at any point, if someone asked “how’s it going,” I had a real, specific answer — not just “still working on it.”</p><h3>The Actual Lesson</h3><p>I think the honest takeaway isn’t “I’m really good at MongoDB aggregations” (I wasn’t, going in). It’s that <strong>the hard part of a project like this was never the code.</strong> The hard part was reading a document slowly enough to notice the one sentence that changes your entire data model, resisting the pull to start typing before you actually understand the problem, and being willing to say “let me go check the actual database” instead of trusting my first assumption.</p><p>As an intern, the temptation is to prove yourself by writing a lot of code fast. What actually built confidence — mine and the team’s — was doing the opposite: slowing down at the start so I didn’t have to redo everything at the end.</p><p>If you’re staring down a big dataset and a scope document that feels intimidating, my honest advice is this: <strong>read it twice, question every noun, go look at the real data before you trust the spec’s description of it, and design your components for the shape of the problem, not just the screen in front of you.</strong> The database doesn’t get smaller just because you’re new. But the problem does, once you actually understand it.</p><p><em>If this resonated with you — whether you’re an intern staring at your first “real” ticket, or a senior engineer who remembers what that felt like — I’d love to hear how you approach reading a spec before writing a single line of code. Drop a comment, or share it with someone who’s about to get handed their first scary-looking ticket.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=373e93f66656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I modeled the same app three ways: SQL, MongoDB, and a graph database]]></title>
            <link>https://medium.com/@jayantjoshi0001/i-modeled-the-same-app-three-ways-sql-mongodb-and-a-graph-database-ef1ae199a747?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef1ae199a747</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 10:42:12 GMT</pubDate>
            <atom:updated>2026-06-17T10:42:12.466Z</atom:updated>
            <content:encoded><![CDATA[<p>A few weeks ago I got asked to research how system architecture actually gets designed — DFDs, ERDs, NoSQL schemas, all of it. The research was useful. But it was also completely abstract. I could tell you what a crow’s foot symbol means. I couldn’t tell you why it matters.</p><p>So I picked one small, realistic app and built its data model three separate ways: as a relational ERD, as a MongoDB document schema, and as a graph database. Same app, same five-ish entities, three completely different shapes. That contrast taught me more about database design in an afternoon than the research did in a week.</p><p>Here’s the app: a B2B marketplace. Suppliers list products. Buyers send RFQs (requests for quotes) for products they want. Suppliers respond with quotes. Suppliers also hold certifications — things like ISO badges or eco-certifications — that buyers filter by when deciding who to trust. Nothing exotic. Five entity types, a handful of relationships. Perfect for this exercise because it’s complex enough to be interesting and simple enough to actually draw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*csOM5d9tOVeS12sJravQhg.png" /><figcaption>Image by <a href="https://dev.to/gduple/database-types-explained-4ja7">DEVCommunity</a></figcaption></figure><h3>Attempt 1: the relational way (ERD)</h3><p>If you’ve touched a database course, this is the version you already know in your bones. Suppliers, buyers, products, certifications, RFQs, and quotes each get their own table. Relationships are foreign keys. A product belongs to exactly one supplier — supplier_id sits right there on the product row. A supplier can hold many certifications, so certifications get their own table with a supplier_id pointing back.</p><p>The diagram above is the actual ERD for this. A few things worth noticing in it:</p><p>Every relationship is explicit and enforced. The database itself won’t let you insert a quote that points to an RFQ that doesn’t exist — that’s what a foreign key constraint does. You don’t have to remember to keep things consistent; the schema remembers for you.</p><p>Cardinality is precise. The line between supplier and product carries real meaning: one supplier, many products (that’s the “many” end with the crow’s foot symbol you’ll see in any ERD tutorial). The line between RFQ and quote works the same way — one RFQ can collect many quotes from different suppliers.</p><p>Querying across relationships is a join, and joins are cheap to reason about because the structure never lies to you. “Show me every quote for RFQs raised by buyers in Germany” is one query with a few joins, and the database guarantees the data on both sides of every join is accurate, because there’s nowhere for inconsistent data to hide.</p><p>The tradeoff: this rigidity is also the cost. If a buyer wants to attach three different shipping addresses to one RFQ, you need another table. If certifications start needing a renewal date, an issuing body, and a verification document, you alter the table and migrate every existing row. Relational schemas are honest, but they’re not flexible, and “not flexible” gets expensive fast when requirements are still moving.</p><figure><img alt="ERD of B2B Marketplace" src="https://cdn-images-1.medium.com/max/1024/1*8pW9AL7Ca8mlK8CQ2WFkDg.png" /><figcaption>ERD of B2B Marketplace</figcaption></figure><h3>Attempt 2: the document way (MongoDB)</h3><p>This is where it stopped being academic for me. MongoDB doesn’t have foreign keys or joins by default. Every time you model a relationship, you’re making an active choice: do I embed this data inside the parent document, or do I store it separately and just reference it by ID? There’s no schema enforcing the “correct” answer. You have to actually think about how the data gets used.</p><p>The diagram above shows the decision I landed on for this domain, and the reasoning behind each piece matters more than the diagram itself.</p><p>Certifications get embedded directly inside the product document. Why: a product’s certifications are small, they don’t change often, and every single time you display a product, you also want to show its certifications right there on the page. Pulling them out into a separate collection would mean an extra database round-trip every time, for data you always need anyway. Embedding means one read gets you everything.</p><p>The supplier is referenced, not embedded. Why: a supplier is a heavyweight, independent thing. The same supplier shows up on twenty different product pages, supplier details get updated independently of any product, and sometimes you want supplier information on its own (their dashboard, their analytics) with no products in sight. If you embedded the full supplier record inside every product, you’d be duplicating supplier data twenty times over, and updating their company name would mean rewriting twenty documents instead of one.</p><p>RFQs aren’t linked inside the product document at all — they’re just queried separately when needed. Why: this is the relationship most likely to explode in volume (a popular product could get hundreds of RFQs) and most likely to need its own independent lifecycle (RFQs get statuses, expirations, follow-ups). MongoDB documents have a hard ceiling — 16 megabytes — and an unbounded list like “every RFQ ever sent for this product” is exactly the kind of thing that will eventually blow past that ceiling if you embed it. Once a list can grow without limit, that’s your signal to stop embedding it.</p><p>If I had to compress the whole decision into one sentence, it’d be this: embed what you almost always read together and that stays small, reference what changes independently or could grow large, and don’t force a relationship into the document at all if it’s genuinely a separate, high-volume concern. That’s not a rule I memorized — it’s the rule I arrived at by actually trying to model this one app and hitting the tradeoffs myself.</p><p>The payoff for all that thinking: reading a product page becomes one fast lookup instead of five joins. The cost: there’s no foreign key stopping you from referencing a supplier that doesn’t exist anymore. Consistency becomes your job, not the database’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6q0W0MKiwkujjWNTfWiOMg.png" /><figcaption>Structural diagram showing the MongoDB embed vs. reference decision for the same domain</figcaption></figure><h3>Attempt 3: the graph way</h3><p>The graph version is the one that actually changed how I think about “relationships” as a concept, rather than just a technical detail.</p><p>In a graph database, everything is either a node (a thing — a supplier, a product, a certification) or an edge (a relationship between two things — “lists,” “holds,” “submitted by”). There’s no table schema and no document shape to plan around. You’re not deciding where data lives. You’re just drawing connections.</p><p>Look at the diagram above. Two different suppliers both hold the same certification — “ISO 14001.” In the relational version, finding that overlap means joining the certification table against itself through two supplier rows. In the MongoDB version, it means querying products for one supplier, separately querying products for the other, and comparing the embedded certification lists in your application code, because the database itself has no idea those two lists might overlap.</p><p>In the graph version, that overlap isn’t something you have to compute. It’s already sitting there as a path: supplier A → holds → ISO 14001 → held by → supplier B. One hop. The relationship was never “missing,” it was just never the kind of thing a table or a document was built to represent directly.</p><p>This is the real difference between a graph database and the other two: SQL and MongoDB both store entities and treat relationships as something you reconstruct at query time, through joins or lookups. A graph database stores the relationship itself as a first-class thing, sitting right alongside the entities. If your application’s hardest questions sound like “find everyone connected to this thing, then everyone connected to those things” — fraud rings, recommendation chains, supply networks — a graph isn’t a nice-to-have. It’s the only one of the three models where that question doesn’t get exponentially uglier the deeper you go.</p><p>The honest tradeoff: for the boring 90% of marketplace queries — “show me this product,” “list this supplier’s open RFQs” — a graph database is overkill. You don’t need network traversal to render a product page. Graphs win exactly when the question is about connections, and lose on raw simplicity everywhere else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*dPYjTml19B8XIkvgqeHoAA.png" /><figcaption>Graph Database Diagram showing relationships in connected network</figcaption></figure><h3>So which one is “right”?</h3><p>None of them, in isolation — that was the actual lesson here, not a cop-out. The three diagrams aren’t competing answers to the same question. They’re answers to three different questions:</p><p>If the question is “how do I guarantee this data stays consistent and correct,” the relational model wins, because the database enforces the rules for you.</p><p>If the question is “how do I read the data I need in the fewest possible trips, when most of my access patterns are predictable,” the document model wins, because you get to shape the data around how it’s actually read.</p><p>If the question is “how do I find connections I didn’t know to look for,” the graph model wins, because relationships are stored, not reconstructed.</p><p>A real marketplace at scale probably ends up using more than one of these for different parts of the system — relational for billing and payments where correctness is non-negotiable, documents for the product catalog where read speed matters most, maybe a graph layer later for fraud detection or recommendations. The mistake isn’t picking the “wrong” database. It’s picking one without ever asking what your actual access pattern looks like, then being surprised when the schema fights you six months in.</p><p>I went into this trying to learn what an ERD looks like next to a NoSQL schema. What I actually walked away with was smaller and more useful: a schema isn’t a description of your data. It’s a bet on how you’re going to use it. Pick the bet that matches your real questions, not the one that’s most familiar.</p><p>Three databases, one app, and the only thing I’m fully confident about now is that the question “which database should I use” is the wrong question to start with. The right one is “what do I need to ask my data, and how often?” Get that answer first, and the schema almost picks itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef1ae199a747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS: From Zero to Something]]></title>
            <link>https://medium.com/@jayantjoshi0001/nestjs-from-zero-to-something-aed02b4c4ca5?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/aed02b4c4ca5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Sat, 16 May 2026 10:47:13 GMT</pubDate>
            <atom:updated>2026-05-16T10:47:13.594Z</atom:updated>
            <content:encoded><![CDATA[<p>Okay so I’ve been building Node.js backends for a while now, and every time I started a new project I’d open a blank index.js, stare at it for 20 minutes, and then basically copy-paste my last project&#39;s structure. Files everywhere. No real organization. Just vibes.</p><p>Then someone on my team went “hey have you tried NestJS?” and I said “no” and they said “you should” and now here we are.</p><p>This is everything I wish someone had told me when I started. Buckle up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*_wjfpaN3yHUb18yg.png" /><figcaption>Image by nestjs.com</figcaption></figure><h3>So What Even Is NestJS?</h3><p>NestJS is a Node.js framework for building server-side applications. It runs on top of Express (or Fastify if you’re feeling spicy), so all that Express knowledge you have? Still useful. But it wraps everything in a proper, <strong>opinionated architecture</strong> using TypeScript decorators.</p><p>Think of it this way — Express gives you an empty room and says “build whatever you want.” NestJS gives you a room with furniture, floor plans, and a rulebook. Sounds annoying. Actually a lifesaver.</p><p>It borrows ideas from Angular (the folder structure, decorators, modules), so if you’ve ever touched Angular you’ll feel right at home. If you haven’t — don’t worry, it’s not required knowledge.</p><p><strong>The stuff it gives you out of the box:</strong></p><ul><li>Built-in Dependency Injection container (no more passing things around manually)</li><li>Module system that keeps your code organized</li><li>Full TypeScript support</li><li>A CLI that generates files for you (yes, really)</li><li>First-class support for REST, GraphQL, WebSockets, Microservices</li></ul><p>The big “aha” for me was this: NestJS solves the <em>blank page problem</em>. You don’t have to figure out how to structure your app — it tells you.</p><h3>Setting Up a New Project</h3><p>First, install the CLI globally:</p><pre>npm install -g @nestjs/cli<br>nest new my-awesome-project<br>cd my-awesome-project<br>npm run start:dev</pre><p>That last command starts the app with hot reload, so every time you save a file it restarts automatically. Honestly this alone justifies the framework.</p><p>When you run nest new, you get a folder structure like this:</p><pre>src/<br>  app.controller.ts<br>  app.controller.spec.ts<br>  app.module.ts<br>  app.service.ts<br>  main.ts</pre><p>The main.ts is your entry point — it&#39;s where the app boots up:</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  await app.listen(3333);<br>}<br>bootstrap();</pre><p>Clean, right? Just NestFactory.create() and you&#39;re off. For this project we&#39;re going to delete the auto-generated AppController and AppService and build feature modules from scratch like the cool kids do.</p><h3>The Three Amigos: Modules, Controllers, Services</h3><p>Here’s the mental model that clicked everything for me. Every feature in NestJS is a <strong>module</strong>. Inside a module you have:</p><ul><li>A <strong>Controller</strong> — handles HTTP requests, talks to the outside world</li><li>A <strong>Service</strong> — contains your actual business logic</li><li>The <strong>Module</strong> file — ties them together</li></ul><p>Let’s look at each one.</p><h3>Modules</h3><p>A module is just a TypeScript class with a @Module() decorator:</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { AuthController } from &#39;./auth.controller&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Module({<br>  imports: [],        // other modules this module needs<br>  controllers: [AuthController],<br>  providers: [AuthService],<br>  exports: [AuthService], // stuff other modules can use<br>})<br>export class AuthModule {}</pre><p>You can generate this with the CLI instead of typing it out:</p><pre>nest generate module auth<br># shorthand:<br>nest g module auth</pre><h3>Controllers</h3><p>Controllers handle incoming requests. You decorate them with @Controller(&#39;path&#39;) and then use @Get(), @Post(), etc. on individual methods:</p><pre>@Controller(&#39;auth&#39;)<br>export class AuthController {<br>  constructor(private authService: AuthService) {}<br><br>  @Post(&#39;signup&#39;)<br>  signup(@Body() dto: AuthDto) {<br>    return this.authService.signup(dto);<br>  }<br>  @HttpCode(HttpStatus.OK) // override 201 → 200<br>  @Post(&#39;signin&#39;)<br>  signin(@Body() dto: AuthDto) {<br>    return this.authService.signin(dto);<br>  }<br>}</pre><p>See how @Body() pulls out the request body automatically? No req.body nonsense. The decorators do the heavy lifting.</p><h3>Services (and Dependency Injection)</h3><p>Here’s where it gets interesting. Services are classes marked with @Injectable(), and NestJS will <strong>automatically inject</strong> them wherever they&#39;re needed. You never call new AuthService() yourself.</p><pre>@Injectable()<br>export class AuthService {<br>  constructor(private prisma: PrismaService) {}<br>  // prisma is magically provided by NestJS<br>}</pre><p>The @Injectable() decorator tells NestJS &quot;hey, this class is managed by me, feel free to inject it.&quot; Then you list it in your module&#39;s providers array and NestJS handles the rest. This is called <strong>Dependency Injection (DI)</strong>, and once you get used to it you&#39;ll never want to go back to manually wiring things up.</p><blockquote><strong><em>The golden rule:</em></strong><em> Any class you want to inject must be </em><em>@Injectable() AND registered as a provider in a module. You never call </em><em>new on services.</em></blockquote><h3>Database Setup: Docker + Prisma</h3><p>For the database we’re using Docker to spin up a PostgreSQL container, and Prisma as our ORM. No installing Postgres locally. No weird OS-specific setup issues.</p><h3>Docker Compose</h3><p>Create a docker-compose.yml:</p><pre>version: &#39;3&#39;<br>services:<br>  dev-db:<br>    image: postgres:13<br>    ports:<br>      - 5434:5432<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: 123<br>      POSTGRES_DB: nest</pre><p>Then spin it up:</p><pre>docker compose up dev-db -d</pre><p>That -d flag runs it in the background. Your DB is now running on port 5434.</p><h3>Prisma Setup</h3><pre>npm install -D prisma<br>npm install @prisma/client<br>npx prisma init</pre><p>This creates a prisma/schema.prisma file. Here&#39;s what our schema looks like for a bookmark app:</p><pre>model User {<br>  id        Int        @id @default(autoincrement())<br>  createdAt DateTime   @default(now())<br>  updatedAt DateTime   @updatedAt<br>  email     String     @unique<br>  hash      String<br>  firstName String?<br>  lastName  String?<br>  bookmarks Bookmark[]<br>}</pre><pre>model Bookmark {<br>  id          Int      @id @default(autoincrement())<br>  createdAt   DateTime @default(now())<br>  updatedAt   DateTime @updatedAt<br>  title       String<br>  description String?<br>  link        String<br>  userId      Int<br>  user        User     @relation(fields: [userId], references: [id])<br>}</pre><p>Then run migrations:</p><pre>npx prisma migrate dev --name init</pre><p>Prisma generates a type-safe client, so you get full autocomplete when writing queries. To create a PrismaService that wraps the client and can be injected in NestJS:</p><pre>@Injectable()<br>export class PrismaService extends PrismaClient {<br>  constructor(config: ConfigService) {<br>    super({<br>      datasources: { db: { url: config.get(&#39;DATABASE_URL&#39;) } },<br>    });<br>  }<br><br>  cleanDb() {<br>    return this.$transaction([<br>      this.bookmark.deleteMany(),<br>      this.user.deleteMany(),<br>    ]);<br>  }<br>}</pre><p>The cleanDb() method runs both deletes in a single transaction — super useful for resetting state in tests.</p><h3>Validation with DTOs</h3><p>A <strong>Data Transfer Object (DTO)</strong> defines the shape of data coming into your API. NestJS uses class-validator decorators to validate request bodies automatically.</p><pre>npm install class-validator class-transformer</pre><p>Here’s an auth DTO:</p><pre>import { IsEmail, IsNotEmpty, IsString } from &#39;class-validator&#39;;<br><br>export class AuthDto {<br>  @IsEmail()<br>  @IsNotEmpty()<br>  email: string;<br><br>  @IsString()<br>  @IsNotEmpty()<br>  password: string;<br>}</pre><p>Then enable validation globally in main.ts:</p><pre>app.useGlobalPipes(new ValidationPipe({<br>  whitelist: true,<br>}));</pre><p>whitelist: true is the secret sauce — it strips any properties from the request body that aren&#39;t defined in the DTO. Someone sending { email: &quot;x@x.com&quot;, password: &quot;123&quot;, isAdmin: true } to your signup route? isAdmin gets stripped automatically. Security win.</p><h3>Authentication: Hashing, JWT, Guards</h3><h4>Password Hashing with Argon2</h4><p>Never store plaintext passwords. We use Argon2 (better than bcrypt, fights GPU brute-force):</p><pre>npm install argon2</pre><pre>import * as argon from &#39;argon2&#39;;<br><br>// Signup — hash the password<br>const hash = await argon.hash(dto.password);<br><br>// Signin — verify<br>const pwMatches = await argon.verify(user.hash, dto.password);<br>if (!pwMatches) throw new ForbiddenException(&#39;Credentials incorrect&#39;);</pre><h3>JWT Tokens</h3><pre>npm install @nestjs/jwt passport-jwt @nestjs/passport<br>npm install -D @types/passport-jwt</pre><p>Register the JWT module with your secret from environment variables:</p><pre>JwtModule.registerAsync({<br>  useFactory: (config: ConfigService) =&gt; ({<br>    secret: config.get(&#39;JWT_SECRET&#39;),<br>    signOptions: { expiresIn: &#39;15m&#39; },<br>  }),<br>  inject: [ConfigService],<br>}),</pre><p>And sign a token after successful login:</p><pre>async signToken(userId: number, email: string) {<br>  const payload = { sub: userId, email };<br>  const token = await this.jwt.signAsync(payload, {<br>    expiresIn: &#39;15m&#39;,<br>    secret: this.config.get(&#39;JWT_SECRET&#39;),<br>  });<br>  return { access_token: token };<br>}</pre><h3>Guards + JWT Strategy</h3><p>A <strong>Guard</strong> decides whether a request gets through. The JWT guard validates the Bearer token on protected routes.</p><p>First, create a Passport strategy:</p><pre>@Injectable()<br>export class JwtStrategy extends PassportStrategy(Strategy, &#39;jwt&#39;) {<br>  constructor(config: ConfigService, private prisma: PrismaService) {<br>    super({<br>      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),<br>      secretOrKey: config.get(&#39;JWT_SECRET&#39;),<br>    });<br>  }<br><br>  async validate(payload: { sub: number; email: string }) {<br>    const user = await this.prisma.user.findUnique({<br>      where: { id: payload.sub },<br>    });<br>    delete user.hash; // never leak the hash<br>    return user; // attaches to req.user<br>  }<br>}</pre><p>Then create a guard that uses it:</p><pre>export class JwtGuard extends AuthGuard(&#39;jwt&#39;) {}</pre><p>And apply it to a route or whole controller:</p><pre>@UseGuards(JwtGuard)<br>@Get(&#39;me&#39;)<br>getMe(@GetUser() user: User) {<br>  return user;<br>}</pre><h3>Custom @GetUser() Decorator</h3><p>Instead of doing req.user everywhere, we create a custom decorator:</p><pre>export const GetUser = createParamDecorator(<br>  (data: string | undefined, ctx: ExecutionContext) =&gt; {<br>    const request = ctx.switchToHttp().getRequest();<br>    if (data) return request.user[data]; // @GetUser(&#39;email&#39;)<br>    return request.user; // full user<br>  },<br>);</pre><p>Now you can do @GetUser() or even @GetUser(&#39;id&#39;) in any controller parameter. Clean.</p><h3>Environment Variables</h3><p>Never hardcode secrets. Use @nestjs/config:</p><pre>npm install @nestjs/config</pre><pre>// app.module.ts<br>ConfigModule.forRoot({ isGlobal: true }),</pre><p>.env file:</p><pre>DATABASE_URL=&quot;postgresql://postgres:123@localhost:5434/nest?schema=public&quot;<br>JWT_SECRET=&quot;your-super-secret-key&quot;</pre><p>Then inject ConfigService anywhere you need env variables:</p><pre>const secret = this.config.get(&#39;JWT_SECRET&#39;);</pre><h3>The Full Bookmarks CRUD</h3><p>Here’s the controller for our bookmarks feature — this is what a complete, production-style NestJS controller looks like:</p><pre>@UseGuards(JwtGuard)<br>@Controller(&#39;bookmarks&#39;)<br>export class BookmarkController {<br>  constructor(private bookmarkService: BookmarkService) {}<br><br>  @Get()<br>    getBookmarks(@GetUser(&#39;id&#39;) userId: number) {<br>      return this.bookmarkService.getBookmarks(userId);<br>   }<br>  <br>  @Get(&#39;:id&#39;)<br>    getBookmarkById(<br>      @GetUser(&#39;id&#39;) userId: number,<br>      @Param(&#39;id&#39;, ParseIntPipe) bookmarkId: number,<br>    ) {<br>      return this.bookmarkService.getBookmarkById(userId, bookmarkId);<br>   }<br>  <br>  @Post()<br>    createBookmark(<br>      @GetUser(&#39;id&#39;) userId: number,<br>      @Body() dto: CreateBookmarkDto,<br>    ) {<br>      return this.bookmarkService.createBookmark(userId, dto);<br>   }<br><br>  @Patch(&#39;:id&#39;)<br>    editBookmark(<br>      @GetUser(&#39;id&#39;) userId: number,<br>      @Param(&#39;id&#39;, ParseIntPipe) bookmarkId: number,<br>      @Body() dto: EditBookmarkDto,<br>    ) {<br>      return this.bookmarkService.editBookmark(userId, bookmarkId, dto);<br>   }<br><br>  @HttpCode(HttpStatus.NO_CONTENT)<br>    @Delete(&#39;:id&#39;)<br>    deleteBookmark(<br>      @GetUser(&#39;id&#39;) userId: number,<br>      @Param(&#39;id&#39;, ParseIntPipe) bookmarkId: number,<br>    ) {<br>      return this.bookmarkService.deleteBookmark(userId, bookmarkId);<br>   }<br>}</pre><p>Notice ParseIntPipe on the :id param — that&#39;s a built-in NestJS pipe that converts the string route param into a number, and throws a 400 Bad Request automatically if it can&#39;t parse it. Little things like this are why I love this framework.</p><h3>End-to-End Testing with Pactum.js</h3><p>Writing e2e tests sounds boring until you realize how much confidence they give you when refactoring. Pactum.js makes it actually enjoyable:</p><pre>npm install -D pactum</pre><pre>describe(&#39;Auth&#39;, () =&gt; {<br>  describe(&#39;Signup&#39;, () =&gt; {<br>    it(&#39;should signup&#39;, () =&gt; {<br>      return pactum<br>        .spec()<br>        .post(&#39;/auth/signup&#39;)<br>        .withBody({ email: &#39;test@test.com&#39;, password: &#39;123&#39; })<br>        .expectStatus(201);<br>    });<br>  });<br><br>  describe(&#39;Signin&#39;, () =&gt; {<br>    it(&#39;should signin and store token&#39;, () =&gt; {<br>      return pactum<br>        .spec()<br>        .post(&#39;/auth/signin&#39;)<br>        .withBody({ email: &#39;test@test.com&#39;, password: &#39;123&#39; })<br>        .expectStatus(200)<br>        .stores(&#39;userAt&#39;, &#39;access_token&#39;); // 👈 save for later tests<br>    });<br>  });<br>});<br><br>// Use the stored token in later tests<br>it(&#39;should get current user&#39;, () =&gt; {<br>  return pactum<br>    .spec()<br>    .get(&#39;/users/me&#39;)<br>    .withHeaders({ Authorization: &#39;Bearer $S{userAt}&#39; })<br>    .expectStatus(200);<br>});</pre><p>The .stores(&#39;userAt&#39;, &#39;access_token&#39;) part is genius — it saves the token from the signin response and you can reference it in subsequent tests with $S{userAt}. No manual copy-pasting tokens.</p><p>For tests you also want a <strong>separate test database</strong> so your test data doesn’t pollute dev data. The course sets up a .env.test file and a separate Docker container for this. Your package.json ends up with scripts like:</p><pre>&quot;pretest:e2e&quot;: &quot;docker compose rm test-db -s -f -v &amp;&amp; docker compose up test-db -d &amp;&amp; dotenv -e .env.test -- prisma migrate deploy&quot;,<br>&quot;test:e2e&quot;: &quot;dotenv -e .env.test -- jest --watch --no-coverage --config ./test/jest-e2e.json&quot;</pre><h3>The Final Project Structure</h3><p>After building everything out, here’s what the folder structure looks like — and honestly it’s <em>chef’s kiss</em> organized:</p><pre>src/<br>├── auth/<br>│   ├── decorator/<br>│   │   └── get-user.decorator.ts<br>│   ├── dto/<br>│   │   └── auth.dto.ts<br>│   ├── guard/<br>│   │   └── jwt.guard.ts<br>│   ├── strategy/<br>│   │   └── jwt.strategy.ts<br>│   ├── auth.controller.ts<br>│   ├── auth.module.ts<br>│   └── auth.service.ts<br>├── bookmark/<br>│   ├── dto/<br>│   │   ├── create-bookmark.dto.ts<br>│   │   └── edit-bookmark.dto.ts<br>│   ├── bookmark.controller.ts<br>│   ├── bookmark.module.ts<br>│   └── bookmark.service.ts<br>├── prisma/<br>│   ├── prisma.module.ts<br>│   └── prisma.service.ts<br>├── user/<br>│   ├── dto/<br>│   │   └── edit-user.dto.ts<br>│   ├── user.controller.ts<br>│   ├── user.module.ts<br>│   └── user.service.ts<br>├── app.module.ts<br>└── main.ts</pre><p>Everything has a home. Every feature is self-contained. New dev joins the team? They can navigate this without a 30-minute walkthrough.</p><h3>Quick Reference: CLI Commands</h3><p>Here are the commands you’ll actually use every day:</p><pre>nest new &lt;name&gt;                      # create project<br>nest g module &lt;name&gt;                 # generate module<br>nest g controller &lt;name&gt; --no-spec  # generate controller<br>nest g service &lt;name&gt; --no-spec     # generate service<br>nest g guard &lt;name&gt;                 # generate guard<br>nest g pipe &lt;name&gt;                  # generate pipe<br>nest g decorator &lt;name&gt;             # generate custom decorator<br>npm run start:dev                   # start with hot-reload</pre><h3>Wrapping Up</h3><p>Okay so what did we actually cover?</p><p>We went from zero to a complete REST API with user auth (signup, signin), JWT-protected routes with guards, full CRUD for bookmarks, a type-safe Prisma setup with Docker, global validation pipes, custom decorators, and e2e tests.</p><p>That’s… actually a lot. And the cool part is the architecture scales — add a new feature, create a new module, follow the same pattern. It doesn’t turn into spaghetti.</p><p>The thing that surprised me most about NestJS is how little time I spend thinking about <em>how to organize things</em> now. That brain space is freed up to think about actual problems. And that alone is worth learning a new framework.</p><p>Go build something. You’ve got the blueprint now.</p><p><em>Thanks for reading. If this helped you, go touch some grass, then come back and build the next project.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed02b4c4ca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bug That Killed Retention and Never Made It to Jira]]></title>
            <link>https://medium.com/@jayantjoshi0001/the-bug-that-killed-retention-and-never-made-it-to-jira-ae20a22998d6?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae20a22998d6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[short-story]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 19:11:49 GMT</pubDate>
            <atom:updated>2026-04-09T19:11:49.586Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>The most dangerous UX failures aren’t crashes or 500 errors. They’re the tiny moments of friction users never complain about — they just quietly leave.</em></blockquote><p>She opened the app on a Tuesday morning, ready to submit a time-off request before her 9am standup.</p><p>She filled in the dates. Selected the reason from the dropdown. Typed a short note to her manager. Clicked Submit.</p><p>An error appeared. <em>Something went wrong. Please try again.</em></p><p>Fine. She tried again. Except — the form was empty. The dates, the reason, the note. Gone. She’d have to start over.</p><p>She glanced at the clock. Eight fifty-seven. She closed the app, walked into standup, and mentally filed it under <em>things I’ll do later</em>.</p><p>Later never came. She started messaging her manager directly. Then she stopped using the app altogether for anything non-essential. Six months later, her company’s renewal conversation hit a bump: “Honestly, half the team just doesn’t use it anymore.”</p><p>Nobody filed a bug report. Nobody tweeted about it. Nobody even mentioned it in a support ticket.</p><p>The form-clearing-on-error bug never made it to Jira.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ip8D4Cd7dG_5e5lJY514fw.jpeg" /><figcaption>Image by <a href="https://in.pinterest.com/pin/68749905814/">Behance</a></figcaption></figure><h3>Nothing was broken. Everything was wrong.</h3><p>Here’s the uncomfortable truth about that story: the app <em>worked</em>. Technically, correctly, it worked. The error was handled. The UI didn’t crash. From the server’s point of view, nothing went wrong.</p><p>But from the user’s point of view, the app wasted two minutes of her time on a Tuesday morning when she was already running late. And that’s the kind of experience that doesn’t generate reports — it generates quiet abandonment.</p><p>These are invisible bugs. They live below the threshold of “worth reporting.” They’re never urgent enough to interrupt someone’s day to write up. They’re just… friction. And friction compounds.</p><blockquote>Users don’t churn in moments. They churn in millimeters — one tiny frustration at a time, until the habit breaks.</blockquote><h3>A taxonomy of things nobody files</h3><p>You’ve felt these before. Maybe you’ve even shipped them. Here are five that are doing real damage in products right now:</p><p><strong>01 — The form that forgets</strong></p><p>Validation fires, the error displays — and all the user’s input vanishes. Technically, the error was “shown.” Experientially, the user was punished for making a mistake.</p><p><em>Result: Task abandonment. Especially brutal in longer forms.</em></p><p><strong>02 — The tap target that almost works</strong></p><p>A button that’s 36px tall on a design file and 28px in production. On desktop, it’s fine. On a phone, on a commute, with cold thumbs — it just doesn’t hit reliably. Users don’t know why. They just feel clumsy using your app.</p><p><em>Result: Subconscious product distrust. “This app is annoying” with no specific reason.</em></p><p><strong>03 — The 300ms button that gives no feedback</strong></p><p>The user taps. Nothing happens visually. They tap again. Now the action fires twice. Or they assume it didn’t work and navigate away before it completes.</p><p><em>Result: Duplicate submissions, partial actions, and a sense that the product feels “laggy” even when it isn’t.</em></p><p><strong>04 — The CTA that’s below the fold on real devices</strong></p><p>Designed on a 13&quot; MacBook. Tested on the same. The “Continue” button is perfectly visible. On an iPhone SE — or any phone with a bottom nav bar eating space — it’s hidden. Users don’t scroll to find it. They think the page has no action.</p><p><em>Result: Drop-off that looks like disinterest but is actually obscured UI.</em></p><p><strong>05 — The error message that explains nothing</strong></p><p>“Something went wrong.” “Invalid input.” “Please try again.” These aren’t messages — they’re a shrug. The user doesn’t know what failed, so they don’t know how to fix it. They try randomly, then leave.</p><p><em>Result: Support tickets that say “it just didn’t work” with no reproducible steps.</em></p><h3>Why these never get caught</h3><p>Product teams are good at tracking what they know to look for.</p><p>You watch the funnel. You watch DAU, retention curves, conversion rates. You run heatmaps. You do the occasional user interview. You ship, you measure, you iterate.</p><p>But these bugs don’t show up cleanly in any of that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*dzov6lxOBc1IM2-Tb7sjwQ.png" /></figure><p>The signal is there. It’s just too distributed and too quiet to trigger anyone’s alarm system.</p><p>And here’s the other reason these bugs survive: they feel too small to fight for.</p><p>A developer fixing a production outage gets visible credit. Someone spending two days hunting down why a button feels 200ms too slow — on a screen nobody specifically complained about — struggles to justify that work in a sprint planning meeting.</p><p>So it stays. And it compounds.</p><h3>The uncomfortable take</h3><p>Your biggest retention problem isn’t your pricing page, your onboarding flow, or your feature gap with a competitor.</p><p>It’s probably 40 tiny UI failures that you don’t know exist, that your users can’t articulate, and that will never appear in a roadmap because nobody has a word for them yet.</p><h3>Try this before you keep reading</h3><p>Think of the last time you abandoned something online without quite knowing why. Not a crash. Not a clear error. Just a moment where you quietly gave up and did something else.</p><p>What happened right before you left? If you can remember, it was probably one of these: something felt slow, something didn’t respond the way you expected, something made you redo work you’d already done.</p><p>Now ask yourself: did you report it? Did you even think to?</p><p>That’s the exact experience your users are having. Silently. Every day.</p><h3>The audit nobody does</h3><p>Most teams do code reviews. Some do accessibility audits. Very few do what you might call a <em>friction audit</em> — a deliberate pass through the product looking specifically for things that are technically working but experientially broken.</p><p>Not “does the button submit the form?” but “does submitting this form <em>feel</em> good?” Not “is the error displayed?” but “does the user know what to do after seeing the error?”</p><p>The gap between those two questions is where retention quietly dies.</p><p>And the hard part isn’t fixing the bugs — it’s finding them. Because nobody will tell you they exist. Your users aren’t your QA team. They’re people with lives and alternatives. When your product creates friction, they don’t file a ticket. They find another way.</p><p><em>The bugs that matter most are the ones that feel too small to mention. Which is exactly why they’re the ones most worth finding.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae20a22998d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time when Google failed]]></title>
            <link>https://medium.com/@jayantjoshi0001/time-when-google-failed-75104ee341d3?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/75104ee341d3</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[startup-lessons]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 07:21:56 GMT</pubDate>
            <atom:updated>2026-02-11T07:21:56.387Z</atom:updated>
            <content:encoded><![CDATA[<p>Last winter, I was sitting in a campus café with my college senior who now works at Google.</p><p>We hadn’t met in years, so over chai we drifted into the kind of conversations engineers love — products, failures, launches, and what really breaks companies.</p><p>That’s when he casually brought up <strong>Google Wave.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gkeFDX5sjX-LdJSK.jpeg" /><figcaption>Image By <a href="https://ainiro.io/assets/images/blog/broken-google-logo-on-wall.jpeg">AINIRO Magic Cloud</a></figcaption></figure><p>He said something that stuck with me:</p><blockquote><em>“Wave didn’t fail because the technology was weak.<br> It failed because humans couldn’t understand it.”</em></blockquote><p>For those who don’t know — <strong>Google Wave</strong> was launched in 2009 as a real-time collaboration tool. On paper, it was <em>ahead of its time</em> — live editing, threaded conversations, shared documents, integrations, everything.</p><p>Technically brilliant.<br> Conceptually powerful.<br> And yet… it was shut down in <strong>2010</strong>.</p><p>Why?</p><p>Because the interface was <strong>overly complex, cluttered, and confusing.</strong><br>Most users didn’t even understand what Wave was supposed to be — email, chat, document, or something else?</p><p>My senior laughed and said,</p><blockquote><em>“It was built by developers… for developers.”</em></blockquote><p>Not for real users.</p><h3>The Quiet UX Problem No One Took Seriously</h3><p>Wave wasn’t killed by bugs.<br> It wasn’t killed by performance issues.<br> It was killed by <strong>poor UX and unclear design.</strong></p><p>Users struggled with:</p><ul><li>Overloaded screens</li><li>Too many features at once</li><li>No clear mental model</li><li>No simple onboarding</li><li>Unintuitive collaboration flow</li></ul><p>The product was <em>developer-driven, not UX-driven.<br></em>And that steep learning curve slowly strangled adoption.<br>This made me think about modern startups.<br>Not Google-sized companies — but ambitious young teams building AI tools today.</p><h3>A Startup That Looked Just Like Wave</h3><p>Around the same time, I was watching a promising AI startup struggle.</p><p>They had amazing tech.<br>They had funding.<br>They had hype.</p><p>But their product felt messy.</p><p>Buttons had poor contrast.<br>Screens were inconsistent.<br>Onboarding confused users.<br>Critical flows didn’t make sense.</p><p>Sound familiar?</p><p>Just like Google Wave — the team built something powerful but didn’t make it <strong>usable.</strong></p><p>Users didn’t complain loudly at first. They just… left.</p><p>No angry emails.<br>No dramatic backlash.<br>Just silence.</p><p>And silence kills startups.</p><h3>What If Google Wave Had Ceriwink?</h3><p>Imagine if a tool like <a href="https://ceriwink.com/"><strong>Ceriwink</strong></a> existed back in 2009.<br>Before launching Wave, the team could have:</p><ul><li>Uploaded their designs</li><li>Let AI review UX consistency</li><li>Identified:<br>- Visual clutter<br>- Confusing interactions<br>- Accessibility gaps<br>- Poor information hierarchy<br>- Inconsistent components</li></ul><p>Instead of discovering problems <em>after launch</em>, they could have fixed them <strong>before millions of users got confused.<br></strong>Wave might still have struggled — but at least it wouldn’t have failed for something as fixable as bad UX.</p><h3>Why I Built Ceriwink</h3><p>This is exactly why I’m building <a href="https://ceriwink.com/"><strong>Ceriwink.</strong></a></p><p>Not to replace designers.<br>But to <strong>support fast-moving teams</strong> who don’t always have UX experts.</p><p><a href="https://ceriwink.com/">Ceriwink</a> acts like an AI Design QA teammate that:</p><ul><li>Reviews UI like a designer</li><li>Flags UX risks like a product manager</li><li>Catches accessibility issues automatically</li><li>Works in seconds, not weeks</li></ul><p>No manual reviews.<br>No expensive consultants.<br>No last-minute redesign panic.</p><p>Just better design, faster shipping, and fewer Google Wave–style failures.</p><h3>Final Thought</h3><p>Google Wave didn’t die because it wasn’t innovative.<br>It died because innovation without usability is useless.<br>And that’s the problem <a href="https://ceriwink.com/">Ceriwink</a> is here to solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75104ee341d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From a Single Tap to Millions of Screens]]></title>
            <link>https://medium.com/@jayantjoshi0001/from-a-single-tap-to-millions-of-screens-04026dca6445?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/04026dca6445</guid>
            <category><![CDATA[sdet]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sde-interview]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 13:29:46 GMT</pubDate>
            <atom:updated>2025-10-16T13:29:46.021Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever posted a funny reel to a friend on Instagram and stopped for a moment to consider the magic that unfolds next? Almost before you’ve asked yourself the question, an alert glows on their screen. It’s a frictionless, instantaneous connection we too often take for granted. This virtual tap on the shoulder is an essential part of the experience, occurring hundreds of times a day on the platform. Whether it’s a friend uploading a new picture, a direct message delivered to your mailbox, or someone liking your new post, Instagram’s notification mechanism toils around the clock to keep you informed.<br>At first glance, the logic appears simple: something occurs, and an alert is triggered. When User A likes User B’s picture, the system merely notifies User B. Easy, right? The truth, though, is much more nuanced. Behind that one, seemingly innocuous alert is a complex and powerful structure intended not only to inform, but to entice without overwhelming. This infrastructure must provide smart decisions every millisecond to provide the appropriate information to the appropriate person at the appropriate time and through the appropriate channel.<br>To really see what’s going on behind the scenes, we have to look past the simple trigger-and-alert model. The process is multi-layered, with each layer having its purpose. It begins with determining how to send the message in the form of different <strong>Push Notifications</strong>, whether it’s a pop-up on your home screen, an SMS, or even an email synopsis. At the same time, the platform records such occurrences as <strong>In-app Notifications</strong>, which leave a lingering entry in your activity stream that you can review whenever you want.<br>Also, to prevent drowning your device in repetitive pings, the system uses sophisticated <strong>Aggregation of Notifications</strong>. Rather than sending ten separate notices for ten likes, it groups them into a single, compact notice such as, “John Doe and 9 others liked your photo.” You as a user also have granular control through deep <strong>Notifications Configuration</strong> settings, where you can optimize precisely what you want to be notified of. Bringing all this together is the brains of the operation: a mighty <strong>Notification Decider</strong>. This central piece of code inspects many factors in real-time to decide whether or not a notification is even needed, making the alerts you see useful and pertinent. In the sections ahead, we’ll cover each of these pieces in detail to demystify the engineering wonder behind each Instagram notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1n4Mh9Ck-qXn-XRn3eUdQ.png" /><figcaption>Basic Architecture</figcaption></figure><p>Now that we have a high-level view of the components involved, let’s explore the single greatest technical challenge a notification service faces: <strong>the fan-out problem</strong>. Fan-out is the process of taking a single event — like a user posting a new photo — and distributing it to a massive list of recipients. For a platform like Instagram, this isn’t just a challenge; it’s a monumental task that happens millions of times per minute. The complexity of this problem scales dramatically depending on the user’s influence, creating a significant engineering hurdle.</p><p>To execute the fan-out, the system relies on various delivery mechanisms. For alerts that need to grab your attention outside the app, it uses external services for <strong>Push Notifications</strong>, such as Google’s GCM (Google Cloud Messaging) for Android, Apple’s Push Notification Service (APNS) for iOS, or other third-party services like OneSignal. Sending an <strong>SMS</strong> or an <strong>Email</strong> follows a similar pattern; at its core, each of these is a network call to an external provider. While these are effective for real-time alerts, the real architectural complexity lies in handling the persistent <strong>in-app notifications</strong>, which require writing data to a database for every single follower. This is where a well-thought-out database model becomes absolutely critical. To manage the immense load, systems never write these updates one by one; instead, they use <strong>Batch Writes</strong> to group thousands of notifications into a single, efficient database operation.</p><p>Let’s put the fan-out challenge into perspective with <strong>step scaling</strong>. Consider four different users:</p><ul><li><strong>U1</strong> has 100 followers. When they post, the system needs to generate 100 notifications. This is a manageable task.</li><li><strong>U2</strong> has 10,000 followers. The load increases by a factor of 100.</li><li><strong>U3</strong> has 500,000 followers. Now we’re talking about half a million database writes and push notifications for a single post.</li><li><strong>U4</strong> is a major celebrity with 5 million followers. A single action from this user triggers a massive wave of 5 million notifications that must be delivered almost instantly.</li></ul><p>Handling the scale of U3 and U4 requires a highly optimized and specialized approach. This is why for the <strong>In-app Updates Center</strong> — the activity feed inside the app — a traditional relational database isn’t always the best fit. Since this feed primarily shows a list of recent events and doesn’t require complex relationships or joins between tables (especially if the data is denormalized), a <strong>NoSQL database</strong> like Amazon DynamoDB or Cassandra is an ideal choice. These databases are designed for horizontal scalability and extremely high write throughput, making them perfect for handling the fan-out storm generated by millions of users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*GARWdjrG9VwXINJ7ZSj-qA.png" /></figure><h3>A Look at the ‘Updates’ Table</h3><p>To store these in-app notifications, a data structure like the one shown in the image is often used. This table, named Updates, is the backbone of the user&#39;s activity feed. Let&#39;s break down its structure:</p><ul><li><strong>Id (PK)</strong>: This is the <strong>Primary Key</strong>, a unique identifier for every single notification record in the database. No two rows can have the same Id. It&#39;s of type bigint to accommodate a massive number of entries.</li><li><strong>User_Id (FK)</strong>: This is a <strong>Foreign Key</strong> that links the notification to the user who should <em>receive</em> it. This tells the system whose activity feed this update belongs to.</li><li><strong>created_At</strong>: This is a timestamp, likely stored as an integer (Unix time), that records exactly when the notification was generated. This is essential for sorting the activity feed chronologically.</li><li><strong>title</strong> &amp; <strong>description</strong>: These varchar (variable character) fields store the actual text of the notification, such as &quot;John Doe&quot; for the title and &quot;liked your photo&quot; for the description.</li><li><strong>metadata (JSON)</strong>: This is a highly flexible field used to store any additional, semi-structured data related to the notification. As the note points out, this could include a URL to the actor’s profile photo, information about a user’s verification badge, or the ID of the post that was interacted with. Using the JSON datatype allows engineers to add new types of information without having to change the database schema.</li></ul><p>so, lets see how a notification looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsYvWhfjBAyVFG4p1g0Omw.png" /><figcaption>Notification Bar</figcaption></figure><h3>Interactive Notifications: The onClick Problem</h3><p>Up until now, we’ve built a solid system that can fan out notifications to millions of users and store them in a space-efficient manner. Our database schema and rudimentary API are ready for the job, at least for someone with a smaller audience. But we’ve neglected the essence of any contemporary notification: interactivity. A notification is not merely information; it’s a call to action. When the user clicks on “John Doe liked your photo,” they want to be brought directly to that photo. This raises an important question: what do we do about the onClick event for all notifications?</p><h3>The “Keep the Client Dumb” Philosophy</h3><p>The secret to doing this nicely is one of the fundamental software design principles: make the client dumb. Here, the “client” is the Instagram application running on your phone. This design rule states that the client program should be as little business logic as possible. Rather than have the app try and determine where to go based on the content of the notification, the backend server should decide and send plain instructions.</p><p>When the backend sends an alert preparation, it ought not simply send the message (“John Doe liked your picture”). It should also send the exact destination, or deep link, where the app must launch when the alert is clicked (instagram://post/12345). This has two gargantuan benefits. Backend deployments are infinitely more slim and quicker than app deployments. If a change is required in the navigation for a particular type of notification, you can implement the same change on the server, and the same change will become effective for all users right away. On the other hand, if this logic was baked into the application, you would need to push out a new version, get through app store approvals, and then cross your fingers in the hopes that every user updates their app — a process that can take weeks and leaves you with a fragmented user base running various versions of the logic.</p><h3>Designing a Future-Proof System</h3><p>This brings about the foundation of a well-architected notification system: a generic yet flexible format. The intention is to have a notification payload that can include all the possible elements without having to update the client application. The backend will do the work of filling up this structure with all the required information: the title, the description, an image URL, and most importantly the onClick deep link.</p><p>The client only has to display this data. It doesn’t have to know the distinction between a “like,” a “comment,” or a “new follower.” It just gets a packet of information and presents it based on an agreed-upon template. By pushing this intelligence to the backend, you develop a system that is extremely agile. When Instagram ships a new feature, such as collaborative posts or a new sticker type, the engineering team can ship new notification types and behaviors without ever having to touch the code of the mobile app. This maintains a uniform experience across all users and enables the platform to move very quickly. This is how you build a system that not only works today but is ready for tomorrow’s features.</p><h3>Taming the Flood: Smart Notification Aggregation</h3><p>Now that we have a system for delivering interactive notifications, we face another user experience challenge: notification overload. If a post goes viral, the owner could receive hundreds of alerts per minute, rendering their phone unusable. To solve this, we must implement <strong>notification aggregation</strong>, the process of intelligently bundling multiple alerts into a single, cohesive message. There are several ways to approach this, with different platforms adopting different strategies.</p><p>Let’s look at two common implementations:</p><ol><li><strong>The LinkedIn Model</strong>: LinkedIn often uses an “object-centric” approach. It creates <strong>one notification per object</strong> (like a post or an article) and continuously updates that single notification as new interactions occur. For example, you might first see, “Jane Doe commented on your post.” As more people engage, that same notification will evolve to say, “Jane Doe and 9 others commented on your post.” This keeps the notification feed clean by containing all activity related to a single item within one entry.</li><li><strong>The Instagram Model</strong>: Instagram typically <strong>aggregates and groups notifications of the same type for the same object</strong>. If ten people like your photo within a few minutes, you won’t get ten separate alerts. Instead, the system will bundle them into a single notification that reads, “John Doe, Jane Smith, and 8 others liked your photo.” This method is highly effective at reducing noise while still providing a clear summary of recent activity.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*MnWqAXEJU2zhQS7VxX86kA.png" /></figure><h3>Inside the Fan-out Implementation</h3><p>Choosing an aggregation strategy is just one part of the puzzle. The real work happens during the fan-out process itself. When an event occurs (e.g., User A posts a photo), a sophisticated workflow is triggered to ensure notifications are sent efficiently and intelligently.</p><p>Here’s a breakdown of the typical steps:</p><ol><li><strong>Identify Recipients</strong>: The first step is to determine <em>who</em> should receive the notification. For a new post, this means fetching the complete list of User A’s followers.</li><li><strong>Check User Preferences</strong>: Not every follower will want a notification. The system must then filter this list by checking the personal <strong>notification preferences</strong> of each recipient. If a user has disabled notifications for new posts from people they follow, they are removed from the list.</li><li><strong>Create and Delegate</strong>: For every remaining user, the system creates a notification “task” and delegates it to a <strong>publisher service</strong>. This service is responsible for the heavy lifting of formatting the notification and sending it to the correct channel (APNS, GCM, etc.).</li><li><strong>The Decider’s Final Say</strong>: Before the task is executed, it often passes through a final, intelligent filter — the “brain” of the system we mentioned earlier. This decider asks critical questions to prevent unnecessary alerts:</li></ol><ul><li><strong>Does this event even deserve a notification?</strong> For a user with millions of followers, sending a push notification for every single “like” is impractical. The system might have rules to suppress low-priority notifications for high-activity accounts.</li><li><strong>Does this specific user require this notification <em>right now</em>?</strong> The system might check if the user is currently active in the app. If they are, a push notification is redundant, and an in-app alert will suffice. It might also rate-limit notifications to a single user to avoid spamming them.</li></ul><p>By following this multi-step process, the system ensures that notifications are not just sent, but are delivered in a way that is relevant, timely, and respectful of the user’s attention.</p><h3>Fanout Logic</h3><p>→ For a notification type / event</p><ul><li>find people to send notification to</li><li>keep the cursor open &amp; read in batches</li></ul><p>→ filter out user that does not require this notification due to</p><ul><li>maximum notifications per day (DB)</li><li>lesser affinity (Affinity DB)</li><li>configured preference (Preference DB)</li></ul><p>→ For users that survive filters, create task &amp; send it to publisher</p><h3>Implementing Publisher</h3><p>The final piece of the puzzle is the <strong>Publisher</strong>. You can think of publishers as the postal workers of the notification system. By design, <strong>publishers are “dumb”</strong> — they contain no complex business logic. Their job isn’t to decide <em>who</em> gets a notification or <em>why</em>; their sole purpose is to execute the delivery task they are given.</p><p>To do this, they need all the necessary details, which are passed along in the task from the fan-out service. However, publishers do have direct access to databases to fetch the final pieces of information needed for delivery. For example, if the task is to send a push notification, the publisher will query a database to get the user’s current device token. If it’s an email, it will fetch their email address and perhaps their profile photo URL to personalize the message. This separation of concerns — the fan-out service doing the thinking and the publisher doing the sending — is what allows the entire system to be incredibly scalable, maintainable, and efficient.</p><h3>Conclusion</h3><p>So, the next time you share a reel or get an alert that a friend has liked your photo, take a moment to appreciate the invisible symphony of technology at play. What seems like a simple, instantaneous event is actually the final step in a complex and highly optimized journey. From conquering the monumental <strong>fan-out challenge</strong> for users with millions of followers to making every notification seamlessly interactive with backend-driven logic, the system is a masterclass in scalable architecture.</p><p>We’ve seen how intelligent <strong>aggregation</strong> prevents our devices from being overwhelmed, how a sophisticated <strong>filtering funnel</strong> ensures that only the most relevant alerts reach us, and how the entire process is managed by a “brain” that makes smart decisions every millisecond. Ultimately, the goal of this immense engineering effort is elegantly simple: to make a global platform feel personal and to keep us connected, one meaningful notification at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04026dca6445" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Deep Dive Slack’s Realtime Communication Architecture]]></title>
            <link>https://medium.com/@jayantjoshi0001/lets-deep-dive-slack-s-realtime-communication-architecture-cadb8234949b?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/cadb8234949b</guid>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 13:58:02 GMT</pubDate>
            <atom:updated>2025-09-05T13:58:02.920Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello and welcome back to the build! If you are here for Part 1, put on your hard hat — we’re going to pour the concrete and wire the electricity on our real-time chat app.</p><p><strong>Wait, you’re new here?</strong><br>Welcome! If you’ve just come across this post, great! But I have to warn you: you’ve entered into the sequel. We’re in the process of designing the architecture for a huge, scalable chat application like Slack, and you’ve missed the first half of the film!</p><p>To get the whole picture, I strongly encourage you to begin with <a href="https://medium.com/@jayantjoshi0001/lets-build-slack-s-realtime-communication-fdc22b0ae511"><strong>Part 1: The Blueprint</strong>.</a> It’s a fast, no-coding read wherein we set forth the whole foundation. Seriously, it’ll click all of this into place for you. Go ahead, we’ll wait!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tst38h2q3qW3orTTx5j0Xg.png" /></figure><h3>A Quick Recap</h3><p>Okay, for all those who’re in the loop, let’s refresh our memory. In our previous session, we wore our architect caps and created the outline of our system.</p><p>First, we decomposed the fundamental elements of a chat application and devised a simple yet strong four-table database schema: Workspaces, Channels, Messages, and Membership. We even made the smart choice to handle Direct Messages as just special channels with merely two individuals, avoiding complexifying our design.</p><p>Then we addressed the elephant in the room: <strong>scale</strong>. We realized one database couldn’t scale to billions of messages, so we added the idea of database sharding. Our golden principle was to shard our messages based on channel_id, so all the messages for a given channel reside together in a single happy little database shard. This action ensured light speed scrolling and prevented ugly cross-database queries.</p><p>Last but not least, we diagrammed the entire course of a single message. We tracked its course from the user’s app, via a load balancer to an API server, where it was stored in the proper database shard. Next, we observed how an event was sent off to Kafka (our central announcement system), which in turn made our Edge Servers publish the new message immediately to all channel members through a persistent WebSocket connection.</p><p>Whew! We’ve established a strong foundation already. Today, we’re going past the blueprint to address the difficult, real-world issues that distinguish a great architecture from one that is merely good. Ready to go deeper? Let’s do this.</p><p>Okay, our design is good to go. A message arrives, gets stored in the appropriate database shard, and an announcement is made to Kafka. Finally, the most important step: getting that message into the right hands, in real time. And that’s where our army of Edge Servers comes in. ????</p><p>Consider every Edge Server as a small town’s local post office. It has a direct, individual relationship — our WebSocket — with every individual living in it right now (user). The server is aware of who is connected to it at all times and how to contact them immediately. Libraries such as Socket.IO take care of a great deal of this connection management for us, which is wonderful.</p><p>So, if User A needs to communicate with User B, and both just happen to be connected to the same Edge Server, the process is easy, isn’t it?<br>The message lands on the Edge Server.</p><p>It is rapidly forwarded to Kafka to be made known to the broader system.<br>The Edge Server looks at its internal list of connections, and there is User B.<br>Swoosh! It sends the message down the open WebSocket to User B.</p><p>Easy peasy. The letter was posted and received within the same post office. But life ain’t always easy, is it?</p><h3>A Distributed Party</h3><p>What if the message isn’t addressed to a single individual, but to a channel with 50 individuals? And what if those 50 individuals are distributed across 20 different Edge Servers worldwide? ????</p><p>Abruptly, then, our local post office breakdowns. The Edge Server that User A is using may be aware of only 3 of the 50 channel members. It has no notion how to locate the other 47. It can’t just yell the message into thin air and hope that the other servers pick it up. That would be madness!<br>This is the traditional problem of a distributed system. We require a “central dispatch” or a brain that can orchestrate this delivery.</p><p>Here’s how we do it:<br>As previously, the first message event gets published to Kafka.<br>We have a specific service — let’s say the Real-Time Delivery Service — which is listening to Kafka all the time.</p><p>When this service receives a “new message” event, it behaves as the coordinator. It initially queries, “Who are all the members of this channel?” Then, it looks at a central registry that is aware of exactly which Edge Server every online user is connected to.</p><p>Now that it has an entire list of deliveries, it performs as a dispatcher, giving orders to the concerned Edge Servers: “Hey Server-5, deliver this to User X. Server-12, you have Users Y and Z. Server-23, you see User W.”<br>Every Edge Server gets its individual orders and sends the message only to the users assigned to it.</p><p>This way, we have a smart and structured system that is capable of sending a message to a channel of any size, regardless of how the users are partitioned throughout our infrastructure.</p><h3>The Safety Net</h3><p>But then what about if a user is off? Or what about if the WebSocket connection flutters for a second and he’s missed the real-time push? The message is pushed out, never makes it. Do we simply drop it?</p><p><strong>No way in the world. We can never, ever lose a message.</strong></p><p>The real-time WebSocket delivery is for the “live” experience, the wizardry of watching messages show up immediately. But it is not our delivery guarantee. The guarantee is the message we stored in our database back in Step 1.</p><p>Our ultimate safety net is a plain REST API. When a user taps on a channel to open it, the app always sends a regular API request to get the most recent messages from the database. This “channel scroll” API is our source of truth. It fills gaps from messages that may have been lost in real-time.</p><p>So we have the best of both worlds:</p><ul><li>WebSockets provide us with that amazing, real-time “live” sensation.</li><li>One API call provides us with iron-clad reliability, guaranteeing the user’s perspective is always complete and current.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_ew3i1Rc2FqHgLtOEXM0w.png" /></figure><h3>Scaling the Edge</h3><p>Edge Server handles connections, serves as a local post office, and routes messages. A very crucial question has just been raised: are we seriously just going to use one of these servers? What if our application becomes popular and millions of people try to connect simultaneously?</p><p>The solution, naturally, is to horizontally scale. That is, add more servers to split the load.</p><p>Pretend each Edge Server has a limit, like for 4 users. The first four users (A, B, C, and D) log in, and all is well. However, when user 5 (E) arrives, the load balancer sends them to a shiny new, unused server: Edge Server 2.<br>This introduces a new challenge. We understand how to deliver messages within the same server, but how do we deliver them between servers?</p><h3><strong>The Local Delivery</strong></h3><p>Let’s consider the easy one first. How does a message travel from User A to User B, both of whom are logged in to Edge Server 1?</p><p>Every Edge Server keeps what’s referred to as a local pool of connections. A tiny black book of all users connected to it. Just a simple mapping: <br>user_id → websocket_connection.</p><p>When Server 1 sees a message from User A that’s meant for User B, it simply needs to look up its local address book, identify the connection of User B, and pass the data down the pipe. It’s akin to sending a memo to someone in the same building — quick, easy, and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gVwIJ9FT0VOMQJ_R9IZ4A.png" /></figure><h3>The Cross-Server Delivery</h3><p>But what about when User A on Edge Server 1 sends a message to a channel where User E is, who is way on the other side on Edge Server 2? The message only gets through if it manages to get to Edge Server 2 in some way. The easiest concept might be to simply connect the servers together. We can have a specialized TCP connection between Server 1 and Server 2. When Server 1 wants to send a message to someone on Server 2, it simply passes it along on this private wire.</p><p>This is fine. for two servers. But what happens if we have 100 Edge Servers? Does each server have to make a direct connection to the remaining 99 servers?</p><p>That would be a wild tangle of connections, a management nightmare! ????️ Whenever you add a new server, it would have to connect to all other servers. This approach simply isn’t scaleable. We can certainly do better.</p><h3>Real-Time Pub/Sub</h3><p>Rather than our servers communicating directly with one another, we can add a middleman message bus with a Publish-Subscribe design, or Pub/Sub for short.</p><p>What in the world is <strong>Pub/Sub</strong>? The best example is a YouTube channel.</p><p>The <strong>publishers</strong> are the content creators (our Edge Servers that get a new message). A creator doesn’t know his subscribers. They simply post a video to their channel (a “topic”).</p><p>The <strong>subscribers</strong> are the viewers (our other Edge Servers). They don’t know the creator personally. They simply say they want to see that channel by clicking “Subscribe.”</p><p>The <strong>Broker</strong> is the YouTube platform itself. It’s the intermediary that notices the new video and automatically sends it to all the subscribers.</p><p>It works like this in our system:</p><ul><li>When Edge Server 1 receives a message for a channel, it publishes that message to a central Pub/Sub topic for a given channel (e.g., a topic titled channel-123). It doesn’t care who else is listening.</li><li>Edge Server 2, which is aware that its user ‘E’ belongs to that channel, has already subscribed to topic channel-123.</li><li>The Pub/Sub system (which may be an application like Redis or a specialized service) immediately forwards the message from the publisher to all subscribers.</li><li>Edge Server 2 gets the message and forwards it to User E via its local connection.</li></ul><p>That is genius because it makes our servers independent. They don’t have to know about one another whatsoever. They simply need to know how to communicate with the middle Pub/Sub system. This is a tidy, structured, and extremely scalable method of dealing with real-time communication between a worldwide fleet of servers.</p><p>The underlying concept to our real-time communication is easy but profoundly powerful:</p><p>Each and every Slack channel in our app will have a corresponding channel in our Pub/Sub system (such as Redis).</p><p>This will result in if you have a #general, a #random, and a #project-x channel in your Slack workspace, we will have a pubsub-general, a pubsub-random, and a pubsub-project-x topic in our Pub/Sub system.</p><p>The Edge Servers now behave smartly. They don’t subscribe to all. An Edge Server will subscribe only to the Pub/Sub topics of the channels whose currently connected users are members. This is a dynamic, living system.</p><p>Let’s clear this up with an example. Suppose Edge Server 1 has four users logged in:</p><ul><li>User A is in channels: C1, C2, C3</li><li>User B is in channels: C2, C4, C5</li><li>User C is in channels: C1, C3</li><li>User D is in channels: C4</li></ul><p>To service all of these users, Edge Server 1 would subscribe to the Pub/Sub topics for C1, C2, C3, C4, and C5.</p><p>Then, a new user, User E, comes to our app. She is a member of channel C3. The load balancer directs her to a less loaded server, Edge Server 2. When User E logs in, Edge Server 2 realizes it has to fetch messages for C3, so it instantaneously connects to our Pub/Sub system and subscribes to the C3 topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*3tlss5cO12RzgZ4SRXpVxg.png" /></figure><p><strong>What If Real-Time Fails?</strong><br>We’ve discussed our ultimate safety net: the REST API to load a channel’s history when you open it. This ensures you never miss anything. What about occasional network glitches, though? If your WiFi goes down for 30 seconds, do you need to reload the channel manually to view the 5 messages you missed?</p><p>We can do better. To provide a truly seamless experience, we can add a replay buffer.</p><p>When a user goes offline, we can buffer any real-time messages sent to them in a holding area (such as an additional short-term Kafka topic). Upon reconnect, the system can “replay” the handful of messages they missed, sending them down the freshly opened WebSocket. This makes temporary connection drops feel entirely transparent to the end-user.</p><h3>Our Final Architecture</h3><p>Finally, after this long odyssey, we can zoom out and view the entire architectural diagram. This is the blueprint that ties together all we’ve seen so far, from persistence to real-time delivery.</p><p>Take a brief tour:</p><ul><li>Users (<a href="http://twitter.com/A">@A</a>, <a href="http://twitter.com/B">@B</a>, <a href="http://twitter.com/C">@C</a>) connect through WebSockets (WS) to a cluster of Edge Servers for real-time communication.</li><li>Upon sending a message, the Edge Server routes it to Kafka to manage persistence.</li><li>Messaging Service Workers take the message from Kafka and store it in the proper partition in our sharded Messages DB. That is the persistence flow.</li><li>Meanwhile, the Edge Server employs the Realtime Pub/Sub (Redis) infrastructure to broadcast the message to other Edge Servers.</li><li>Other Edge Servers (such as the one serving users <a href="http://twitter.com/D">@D</a> and <a href="http://twitter.com/E">@E</a>) receive the message from Pub/Sub and send it to their connected users.</li><li>The old API Servers (accessed through a Load Balancer) remain to deal with all the rest: loading historic messages (the “channel scroll”), authentication, and loading user profiles.</li></ul><p>And there you have it. A decoupled, scalable, resilient system designed for huge, real-time communications. From a humble four-table schema to a full, distributed global infrastructure. No longer are you simply a consumer of apps like Slack — you’re an architect with knowledge of how they operate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*3418pwNJkSAWsUaOtOCYWg.png" /></figure><h3><strong>Conclusion</strong></h3><p>And there you have it, our architectural adventure is complete! We’ve traveled from an easy question — “How do apps like Slack work?” — to a full-fledged, production-quality blueprint for a highly scalable real-time communication system. It’s been a wild ride, so let’s do a quick walk back through the city we’ve constructed together.</p><p><strong>Our Architectural Journey</strong>: <br>We began with a good foundation, laying out a lean and minimalist database schema which could be the skeleton of our application. But we knew that we needed to prepare for the future where there would be billions of messages, so we added database sharding by channel_id, an important choice that allowed our app to be fast and responsive regardless of how large it became.</p><p>With our data storage in order, we shifted to the wizardry of real-time. We defined WebSockets as our two-way, persistent communication lifeline and built a small armada of specialized Edge Servers to handle millions of them.</p><p>Next, we addressed the problem of a distributed, global system. Rather than being mired in a complex web of server-to-server communications, our master move was using a Real-Time Pub/Sub system. This core message bus enabled our Edge Servers to talk to one another without ever being aware they did, building a decoupled, fault-tolerant, and highly scalable network.</p><p>Last but not least, we refined our system by incorporating a double safety net for dependability: a bulletproof REST API to retrieve channel history and a smart replay buffer to make reconnecting after a network hiccup truly seamless.</p><p>The intention of this blog series was to pull back the curtain and demystify the advanced systems we all use on a daily basis. The ideas that we’ve discussed — from sharding and WebSockets to the Pub/Sub pattern — are the building blocks of the internet as it exists today.</p><p>You’re not just a consumer of these incredible apps anymore; you’re an architect who knows the thought, the compromises, and the design that go into creating them to feel so enchanting. I hope you can take these concepts and use them in your own incredible projects.<br>Thanks for coming along on this build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cadb8234949b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Build Slack’s Realtime Communication]]></title>
            <link>https://medium.com/@jayantjoshi0001/lets-build-slack-s-realtime-communication-fdc22b0ae511?source=rss-1256aa19f108------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdc22b0ae511</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[back-end-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Jayantjoshi]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 13:57:33 GMT</pubDate>
            <atom:updated>2025-09-02T13:57:33.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! If you’re reading this, then chances are high that you used a messaging app today. Perhaps WhatsApp to catch up with family, or Messenger to pass around a meme. But in the workplace, a different name tends to dominate: Slack. For millions of companies around the globe, it’s the office in a virtual sense, plus a virtual water cooler and a central work location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*y4PRTGGS5oFHbA_dP3XXhw.png" /></figure><p>So what’s the magic ingredient that makes these applications seem so alive and instant? It’s <strong>real-time communication</strong>. And today we’ll lift the veil and take a look at how you can create it yourself.</p><p>Let’s describe what it takes to have a smooth real-time experience within an app such as Slack without digging into code. It’s not quite a case of sending a message and then waiting around to receive a response. It’s a dynamic, living system built on a few key pillars:</p><ol><li><strong>Multiple Users &amp; Channels:</strong> It’s no solo conversation. It’s a vibrant workplace where dozens or even hundreds of users can communicate across numerous public and private channels and keep discussions cohesive and readily accessible.</li><li><strong>Instant Messaging:</strong> When you send a direct message (DM) to a team member or a post within a project channel, the message shows up to others in that conversation right away. Zero refreshes needed, zero waiting.</li><li><strong>A Living History:</strong> It’s not only about right now. It’s about scrolling effortlessly back through a channel’s history to get up to date on discussions that took a path you didn’t follow. Context is always available.</li></ol><p>This sort of instant feedback loop is not only saved for work chat! You’ll know the same underlying technology behind some of your favorite online experiences:</p><ul><li>Multiplayers wherein your actions can be viewed alongside those performed by others.</li><li>Real-time poll software where the results bar changes and shifts immediately whenever a new vote is cast. Collaborative creator programs such as Figma or Google Docs in which you can observe your team-member’s cursor travel across your computer monitor.</li></ul><p>Okay, we went over “what” and “why” about real-time communication. And now’s where we get to have some fun: brainstorming how we’d realistically plan out an app’s architecture like Slack. Relax; we’re not going to write a line of code today. We’ll be architects and sketch out a blue digital blueprint of our system.</p><p>Let’s start right at the highest-level. A company has a Workspace. It’s the ultimate container to contain everything — all users, all conversations, all files. It’s all about Channels within this workspace. Chats occur within these Channels. A workspace can have tens or even dozens of channels for any number of varying projects or team initiatives or even sharing memes.</p><p>Workspace → Different Channels → Different Messages</p><p>And what about Direct Messages (DMs)? A good design can be especially helpful here. A DM between two users is simply a special kind of private channel with two members. If we want to think about everything in a “channel,” we get a uniform and graceful model.</p><h3>Sketching the Conversation</h3><p>Where does it all get stored? We need a concise plan for our database. We can think of this as our application’s floor plan. We can start out with a minimalist schema such that we organize our data into logical tables. We can conceive a structure such as this:</p><p>Let’s step through this schema. It’s a basic Workspace table; it only assigns a unique ID and a name to each workspace. It’s a table that contains all our conversation rooms. What’s important is that every channel has a reference back to a workspace_id such that we can know which workspace it’s part of.<br>Messages table is where all messages that a user posts get stored. A message has an ID, actual message content, and channel_id references it was posted in and user_id who posted it. This creates a direct chain: a user posts a message, message is part of a channel, channel is part of a workspace.</p><p>Last but not least, we have the Membership table. This is what binds it all together. It records who is a member of what channels. But check out that additional field: checkpoint. What’s going on here? This is how we provide our secret ingredient to a fantastic user experience! The checkpoint is a virtual bookmark that stores the timestamp or ID of a user’s last message read in a channel. That’s how the app can serve up that “New Messages” line or highlight unread channels. It’s a simple idea that’s central to enabling the experience to be smart and intuitive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irDpTl_2aFZBMCZb5F79zw.png" /><figcaption>Schema</figcaption></figure><p>With only these four tables, we’ve established a strong foundation for our entire real-time communication system. This is the skeleton to which we’ll add the real-time magic.</p><h3>Handling Billions of Messages</h3><p>Our four-table design is a fabulous beginning, but now we have to consider scale. A viral workspace can produce millions, or even billions, of messages in the long run. Storing all that data in one huge database is like searching through a library with no shelves and all the books stacked in the middle of the room. It becomes slow, clunky, and at some point, it will come to a stop. ????</p><p>The answer to this explosion of data is a strategy known as <strong>database sharding</strong>.</p><p>The idea is really not so complicated. We don’t have a single huge database; instead, we divide our data into many little, fast, and easy-to-manage databases referred to as shards. The catch is having an intelligent rule for determining which portion of data gets stored in which shard. Imagine it like a librarian choosing to put books in various rooms based on category. All the fantasy books are in one room, all the history books in another. This is quicker for pulling out any given book.</p><h3>Sharding by Channel ID</h3><p>For our chat app, the ideal “rule” is to shard our messages by the <strong>channel_id</strong>.</p><p>This implies that all messages in a given channel will coexist together in the same dedicated shard database. This is an incredibly powerful choice. Why? Because when a user opens up a channel and begins scrolling back through its messages, the app knows precisely which shard to go through. It doesn’t have to search through a gigantic database; it goes straight to the tiny, structured shard that holds only the messages for this particular conversation.</p><p>This strategy guarantees that our shards are exclusive of one another — each shard is an independent universe for the channels it contains. The loveliness of this strategy is that it eliminates entirely “<strong>cross-shard queries</strong>” for our most frequent action: reading a channel’s history. This directly maps to a snappy, responsive user experience with lightning-fast scrolling.</p><p>And. This is a malleable architectural design. It is compatible with most kinds of databases, even normal SQL databases, provided they can support sharding.</p><p>So now we have a firm plan for storing our data that’s both logically structured and designed to be able to handle huge scale. The next step is therefore to outline the path of a single message. How does it go from someone’s keyboard to the screens of their collaborators in real-time? Let’s follow that flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbzuegdCTCFsk-5N-AGHNA.png" /></figure><p>We’ve made our database scalable, but how does a message get from your keyboard to your co-worker’s monitor in milliseconds? It’s time to examine the complete system architecture. This diagram may appear intricate at first glance, but it gives a concise account of how a message moves through our system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lAAcJBiCFTDi2BTCP443Q.png" /><figcaption>overall architecture for real-time communication</figcaption></figure><p>Let’s follow the journey of a single message, send_message(from_user, to_channel, text), by following the numbers in the diagram.</p><h3>Overall design for real-time communication</h3><p><strong>Path 1: Storing the Message</strong> (The Purple Path ????)<br>When a user sends “send,” their application places a regular request to our system. This request initially lands on a Load Balancer, which is essentially a traffic cop that routes the request to one out of multiple available API servers.</p><p>The API server is the mind behind this process. It takes the message, checks the channel_id, and immediately knows which shard of the database to write to (thanks to our sharding plan!). It then writes the message to the appropriate partition. This is the step that commits our message into safe and permanent storage. This is the persistence part of the journey.</p><p><strong>Path 2: Announcing the News</strong> (The Green Path ????)<br>Saving just the message is not sufficient; we have to inform the rest of our system that something has changed. Once the message has been successfully saved, the API server sends an event into a message queue such as Kafka.</p><p>Imagine Kafka like a high-throughput central announcement board or a bulletin board. Our API server puts up a message reading, “New message in channel XYZ!” Other services, whose sole responsibility is real-time delivery, continuously monitor this board for new postings.</p><p><strong>Path 3: Instant Delivery</strong> (The Blue Path ????)<br>This is where the magic happens in real-time. Your app is not repeatedly querying the server, “Is there a new message yet?” That would be extremely inefficient. Rather, when you start the app, it opens up a long-lived, two-way connection to one of our Edge Servers via a WebSocket.</p><p>When the real-time services notice the “New message!” notification from Kafka, they instantly look up all the users who happen to be in that channel. They then “push” the new message information via the open WebSockets to all the channel members’ apps directly. This “push” is responsible for making the message pop up immediately on their screens, without them having to refresh anything.</p><h3>Persistence vs. Speed</h3><p>This architecture is extremely flexible and can be used for a lot of real-time applications. The key thing to keep in mind is the need for persistence — writing the data to disk.</p><ul><li><strong>Slack Style (Persistence First)</strong>: The pipeline we outlined (User → API → DB) is order-of-magnitude more concerned with storing the message. It is perfect for business chat where an auditable record is paramount.</li><li><strong>WhatsApp Speed (Speed First)</strong>: Since the app is about immediate social messaging, you would optimize for perceived speed. The workflow would be User → WebSocket → Kafka → DB. In this case, the message is propagated to other users simultaneously while it’s being stored. It appears quicker, but has a small chance of the message not getting stored if there’s a failure at that precise moment.</li><li><strong>Zoom Style (No Persistence)</strong>: In the case of a video call, only the real-time data stream is important. There’s no requirement for every frame of video to be stored. Only the real-time delivery path is important, and the persistence layer (the database) is not engaged for the primary experience.</li></ul><p>Rest based short polling is a terrible UX for something as real-time as messaging, So we need a better solution.</p><h3><strong>WebSockets and Edge Servers</strong></h3><p>So, we’ve accomplished the design of a system that can capture and store a message in the appropriate database shard. We can be sure that as soon as a message is sent, it’s saved safely. Let’s dive deep into the most thrilling part: the real-time delivery that makes the entire experience come alive. ????<br>The technology behind this is the <strong>WebSocket</strong>.</p><p>Consider a standard web request (HTTP) as sending a letter. You send the letter and then wait for a response. If you need more information, you must send another letter. It’s not an ongoing conversation. A WebSocket, however, is like opening a special phone line between the user app and our server. This connection remains open, and either end may pass data to the other at any moment without needing to hang up and dial once more. This is our lifeline in real-time.</p><p><strong>Why One Connection is King</strong><br>Each user of our app will have one WebSocket connection open to our backend. This single connection will be the conduit for all and anything real-time: new messages, typing, read receipts, online presence states, and notifications.<br>But why one and not more? There are two large reasons:</p><ul><li><strong>Browser Constraints:</strong> Browsers restrict how many connections a single tab may make at once to a domain (typically about 6). If each feature attempted to open its own connection, we’d immediately reach the limit.</li><li><strong>Server Resources:</strong> Having an open WebSocket connection is costly for a server. A million users translates to a million ongoing connections to handle! It’s much better to service one high-powered connection per user than multiple ones.</li></ul><p>To service this huge task, we can’t simply employ our usual API servers. We require a dedicated army of servers whose sole responsibility is to service these connections. These are our Edge Servers.<br>These servers are designed to service tens of thousands of simultaneous WebSocket “phone lines” each. They reside at the “edge” of our infrastructure, serving as the first point of contact for all users connected, eager to push and pull data in real time.</p><h3>The Art of Multiplexing</h3><p>So, if we have just a single pipeline, how do we put various kinds of information through it without them being confused? We do this through a code called multiplexing.</p><p>Visualize that one WebSocket connection as a pneumatic tube network, like the kind you’d find in a bank. Rather than having a separate tube for each kind of document, we put everything — cash, memos, forms — into the same tube. The trick is that there is a tag on every container: “DEPOSIT,” “MEMO,” etc. When it gets to the other end, the recipient looks at the tag and knows what to do with what’s inside.</p><p>Our WebSocket operates similarly. All of the data we transmit, from a new chat message to a “user is typing” signal, is encased in a label (an “event type”). The app on the user’s side sees the data, looks at the label, and knows exactly what to do with it. This lets us pipe a rich, detailed, real-time experience through a simple, streamlined connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*h6RgXUk7mpSnUErzvN7SIA.png" /><figcaption>architecture for sending and receiving messages</figcaption></figure><h3>The Story So Far… And What’s Next</h3><p>And there we are! We’ve traveled from a basic concept to a robust, high-level design for a real-time chat application. We’ve created a scalable database with sharding to support billions of messages and drawn out a durable delivery mechanism with WebSockets and Edge Servers to make communication truly instantaneous.</p><p>But crafting a production-quality real-time system presents many more interesting challenges. How do we handle user presence efficiently to display who’s online? What happens when a user’s connection goes down and then comes back up? How do we scale the backend service listening to Kafka so that messages are processed in the right order and in a timely manner?</p><p>The answers to these questions necessitate a far closer examination of the delicate ballet of our system’s elements. The design is complete, but the tweaking is where the magic happens.</p><p>This subject is too rich and significant to be contained in one blog post. So, do be sure to come back with me for the last installment of this series, where we will finish this architecture and take a genuine deep dive into the inner workings of real-time communication.</p><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc22b0ae511" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>