<?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 Vikas Tomar on Medium]]></title>
        <description><![CDATA[Stories by Vikas Tomar on Medium]]></description>
        <link>https://medium.com/@rare-major?source=rss-6db8d35fea89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4IcFOND_n0c-j8OZWzBENQ.png</url>
            <title>Stories by Vikas Tomar on Medium</title>
            <link>https://medium.com/@rare-major?source=rss-6db8d35fea89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 22:27:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rare-major/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[Stop Trying to Win the Competition]]></title>
            <link>https://medium.com/@rare-major/stop-trying-to-win-the-competition-44a52a5473ec?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/44a52a5473ec</guid>
            <category><![CDATA[competition]]></category>
            <category><![CDATA[peter-thiel]]></category>
            <category><![CDATA[0to1]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 18:18:48 GMT</pubDate>
            <atom:updated>2026-09-06T18:18:48.809Z</atom:updated>
            <content:encoded><![CDATA[<p>A different way to think about building something valuable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFIicyxQOVu0lWH1oyjPiQ.png" /><figcaption>Winning the race is temporary. Building your own track is the moat.</figcaption></figure><p>There is something we are taught very early in life: competition is good.</p><p>Study harder because everyone else is studying harder. Work harder because someone else wants the same promotion. Build a better product because ten companies are building the same thing.</p><p>It makes intuitive sense.</p><p>But we rarely stop to ask a slightly uncomfortable question.</p><p><strong>What if the game itself is wrong?</strong></p><p>What if the goal isn’t to become the best player in an existing game, but to build a game nobody else is playing?</p><p>That’s the idea from Peter Thiel’s 2014 essay <em>Competition Is for Losers</em> that stuck with me. He’s not literally calling competitors losers. He’s saying something sharper: if your entire business depends on beating competitors, you’ve already accepted their rules.</p><h3>Creating value isn’t the same as capturing it</h3><p>Think about airlines.</p><p>Incredibly valuable service. Millions of passengers. They shrink the world.</p><p>And they earn pennies per trip.</p><p>Thiel compares them with Google, which created less total value but kept a far bigger share of it, because nobody could offer a close substitute for what it did.</p><p>That’s the distinction that matters. A great business isn’t the one that creates the most value. It’s the one that captures a meaningful portion of the value it creates.</p><p>You can build something people genuinely want and still make almost nothing.</p><p>That’s the weird part about business, and nobody teaches it to you in college.</p><h3>We ran this experiment in India. Several times.</h3><p>Food delivery: two players burned billions fighting over the same biryani order. For years the unit economics looked like a charity with an app.</p><p>Quick commerce: at one point, half a dozen companies raced to deliver Maggi in ten minutes. All losing money on every packet. All convinced their dark stores were somehow different.</p><p>Edtech: the less said, the better.</p><p>Now look at the other side.</p><p>Zerodha never raised VC money and never ran IPL ads. It quietly became one of the most profitable startups in the country, because for a long stretch, discount broking done properly was a category of one. UPI-era fintechs fought each other for cashback users. Zerodha owned a market.</p><p>Same movie, different genre. The competitive players fought. The category-of-one players compounded.</p><h3>The problem with being “just another option”</h3><p>Imagine you open a restaurant. British food, Palo Alto. Nobody else is doing it. You’ve found a niche.</p><p>Except your market isn’t “British restaurants.”</p><p>Your market is every restaurant someone could choose instead. Indian, sushi, burgers, cooking at home, ordering in.</p><p>The moment you define your market honestly, things look much less impressive.</p><p>Startups get this wrong constantly. They define the market so narrowly that they lead it by definition.</p><p><em>“We’re the number one AI-powered platform for left-handed dentists in tier-2 cities.”</em></p><p>Of course you are. You’re the only one.</p><p>The problem isn’t that you lack differentiation. The problem is that <strong>your differentiation might not matter enough.</strong> A slightly better recipe doesn’t save you when the customer has two hundred alternatives within delivery radius.</p><h3>Being different isn’t enough</h3><p>We confuse differentiation with uniqueness. They’re not the same thing.</p><p>A different logo. A slightly better feature. A cheaper price.</p><p>You can have all of it and still be completely replaceable. If removing your company from the market just means someone else gets the customer, you haven’t built a moat. You’ve built an alternative.</p><p>And alternatives live in response mode. Someone cuts their price, you respond. Someone ships a feature, you respond. Someone raises fifty million, you respond.</p><p>Eventually your company becomes an elaborate machine for responding to everyone else.</p><p>That’s not a strategy. That’s a reflex.</p><h3>This applies to your career too</h3><p>Here’s the part nobody tells engineers.</p><p>Grinding LeetCode to clear the same interview as five lakh other people is perfect competition. You are an undifferentiated commodity, and the market prices you accordingly. It works, the way airlines work: you’ll fly, you’ll survive, you’ll make 37 cents per trip.</p><p>The alternative is to become a category of one.</p><p>The engineer who deeply understands both distributed systems and a specific business domain. The developer who codes and also writes clearly in public. The person who ships weird side projects that no bootcamp syllabus contains.</p><p>None of these are monopolies in the antitrust sense. All of them are monopolies in the Thiel sense: no close substitute exists.</p><p>The competitive path feels safer because it has a syllabus and a leaderboard. The category-of-one path feels risky because there’s no map.</p><p>Which is exactly why it’s less crowded.</p><h3>Competition keeps you busy</h3><p>This is the part I find most uncomfortable.</p><p>Competition doesn’t necessarily make you bad. It makes you <strong>busy</strong>. And busy feels a lot like progress.</p><p>Optimizing. Benchmarking. Copying. Responding. Trying to become 7% better than the guy next to you.</p><p>Worse: rivalry is a form of imitation. You end up wanting things only because the person next to you wants them, and you call that ambition. The engineer obsessing over a colleague’s promotion never stops to ask whether he even wants that job.</p><p>Thiel puts it economically: a business trapped in competition is so consumed by today’s margins that it can’t plan a future. The human version is older than economics.</p><p>The real luxury of having no close substitute isn’t the profit. It’s time. The freedom to think about something other than survival.</p><h3>So should everyone build a monopoly?</h3><p>Obviously not the rent-collecting kind. A monopoly on a static board is just ownership: you hold the best properties and charge everyone more. That’s not innovation.</p><p>But the real world isn’t a static board. IBM’s dominance gave way to Microsoft’s, Microsoft’s to Apple’s mobile era. Dominant businesses get displaced when someone creates a genuinely better way.</p><p>So the takeaway isn’t really “build a monopoly.”</p><p>It’s this: <strong>build something that is difficult to replace.</strong></p><p>Don’t ask “how do I beat them?” Ask “what can I do that they can’t?”</p><p>If the answer is nothing, you’re in a race where everyone runs in the same direction and the winner is whoever has slightly more money or slightly lower costs.</p><p>If the answer is something real, you’re not fighting over the pie anymore.</p><p>You’re making a new one.</p><h3>The question worth asking</h3><p>If ten companies look almost identical, they’re fighting over the same customers. If one company looks completely different from everyone else, pay attention.</p><p>That’s the real lesson behind the provocative title. Not that competition is bad, but that if you spend your whole life beating everyone at their game, you never stop to build something that makes the game irrelevant.</p><p>So the question, for your startup and honestly for your career:</p><p><strong>What valuable thing can I build that nobody else is building, and why are I standing in a queue instead?</strong></p><p><em>Based on Peter Thiel’s 2014 essay Competition Is for Losers, originally published in The Wall Street Journal and adapted from Zero to One by Thiel and Blake Masters. Worth reading, especially where you disagree.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44a52a5473ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Karpathy Loop Scales. The Knowledge Doesn’t.]]></title>
            <link>https://medium.com/@rare-major/the-karpathy-loop-scales-the-knowledge-doesnt-4f3a88d7e88d?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f3a88d7e88d</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[karpathy-loop]]></category>
            <category><![CDATA[karpathy]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 14:48:41 GMT</pubDate>
            <atom:updated>2026-08-26T14:48:41.822Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A plain-English guide to the loop everyone copied in March, and the piece that is still missing.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6C2dDjvTIH_3EqqK" /><figcaption>Photo by <a href="https://unsplash.com/@niloytesla?utm_source=medium&amp;utm_medium=referral">Niloy T</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In early March 2026, Andrej Karpathy pushed a 630-line Python file to GitHub and went to bed. One file, one GPU, one number to beat. A coding agent was pointed at it and told to try things.</p><p>Over two days it ran around 700 experiments and found about 20 improvements that stacked, cutting time-to-GPT-2-quality from 2.02 hours to 1.80 hours. On code he had been hand-tuning for months. One finding was a bug in his own attention implementation.</p><p>The repo crossed 40,000 stars in two weeks. People started calling it the Karpathy Loop.</p><p>Almost none of it is about machine learning.</p><h3>The shape</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpIcFHgkss5Uw-WhOJ0mbA.png" /><figcaption><em>Figure 1: five steps, run by something that does not get bored.</em></figcaption></figure><p>Read Figure 1 left to right. You write the spec once, on the far left: what to optimise, what not to touch, how long each attempt gets, when to stop. Then you are done. Everything to the right of that arrow runs without you.</p><p>The five boxes are the cycle. Read what has been tried, guess what might help and say why, change one thing, run the benchmark for a fixed time, compare against the best score. Step five splits: better means commit and the bar moves up, worse means revert and you have lost exactly one time box. The dashed line underneath is the important one. Either branch feeds straight back into step one, immediately, with no pause for a human.</p><p>Every backend engineer has run this loop by hand, badly, between meetings. The new part is that an agent runs all five steps unattended, twelve cycles an hour, all night.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpG3DpoZwYTW9QSaDUDi8g.png" /><figcaption><em>Figure 2: most dots are failures. The line never goes back up.</em></figcaption></figure><p>The graph above is why the failures do not matter. Each hollow red circle is a reverted experiment. There are far more of them than wins, and they are scattered all over the chart because most guesses are wrong. The filled dots are the ones that beat the baseline, and the green line traces the best score so far. It is a staircase, and it only steps one way. That is the whole economic argument: failures are disposable, wins are permanent, so you can afford to be wrong forty times a night.</p><h3>The three constraints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtnL_Ow27_uXZI9itPG2SQ.png" /><figcaption><em>Figure 3: file, number, clock.</em></figcaption></figure><p>Figure 3 has three columns and the bottom row of each is the one to look at. It maps Karpathy’s setup onto an ordinary service. His editable file was train.py, yours might be one service class. His number was validation loss, yours is p99 latency in milliseconds. His clock was five minutes per run, yours is a sixty second load test.</p><p><strong>One editable file.</strong> Not the benchmark, not the tests, not the config that defines a pass.</p><p><strong>One number.</strong> Computable by a script, obvious which direction is good. “Cleaner code” is not a metric.</p><p><strong>One time box.</strong> Same budget every attempt, so results stay comparable.</p><p>The metric is where it goes wrong, which is the warning strip at the bottom of the figure. A tireless optimiser will exploit any gap between the metric and the intent. Score average latency and it will shave the mean by making your worst requests worse, then report a win.</p><h3>Not an ML thing</h3><p>Within a week, Tobi Lütke pointed the pattern at Liquid, the Ruby templating engine behind Shopify storefronts, hand-tuned by hundreds of contributors over two decades. Around 120 automated experiments produced a PR with 93 commits: 53% faster parse and render, 61% fewer object allocations.</p><p>His own caveat is the useful part. He said it was probably somewhat overfit to the benchmark.</p><p>The shape fits most backend work: p99 on a hot API, GC pressure in a request path, CPU seconds per thousand requests, CI wall-clock time, a query plan everyone has avoided for a year. Anything with a number and a repeatable way to produce it.</p><h3>Now run four of them</h3><p>SkyPilot removed the single-GPU limit: 16 GPUs, eight hours, ~910 experiments at 90 an hour instead of 10, same best result nine times faster. The agent also taught itself to screen ideas on the cheap cards and validate winners on the fast ones.</p><p>Parallelism changed the search, not just the speed. One GPU forces greedy hill climbing. Sixteen let it run grids and catch interactions between parameters.</p><p>That is the good news. The bad news arrives when the parallel agents belong to different people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0_iieJHpcx0NICS6qlnBQ.png" /><figcaption><em>Figure 4: clean in isolation. Isolation is not production.</em></figcaption></figure><p>The left panel of Figure 4 is the original design: one agent, one loop, and a git log that serves as the entire memory. It works. The right panel is four loops on one platform team, chasing latency, spend, quality and compliance, all pointed at the same repo with nothing between them. The dashed red box is the gap, and the four failures listed under it all fall out of it.</p><p><strong>Duplicate discovery.</strong> Agent B spends the night proving what Agent A disproved at 2am. You paid for both.</p><p><strong>Silent contradictions.</strong> A finds a longer cache TTL improves p99. C finds it wrecks freshness under different traffic. Both true. Neither agent knows the other exists.</p><p><strong>Collisions.</strong> One file, four writers.</p><p><strong>No trail.</strong> Three weeks later, why is this value 47? The commit says “experiment 312: metric +0.4%.” The reasoning died in a context window.</p><p>Fine for a demo. Not an operating model for five teams.</p><h3>The missing layer is memory, not compute</h3><p>More GPUs are a purchase order. What you cannot buy is the thing that makes the second night smarter than the first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYirjaCuf7sz_McKolzAWw.png" /><figcaption><em>Figure 5: findings written by agents, read by agents.</em></figcaption></figure><p>Figure 5 puts a log between the agents and lets them write to it and read from it before guessing. The card in the middle is the unit: what was tried, what happened, on what, and whether it still holds. Four entries, one experiment. The panels down the right are what turns that log into memory.</p><p><strong>Searchable both ways.</strong> “Anything tried around connection pooling?” and “what happened at TTL 1800?” are different queries. Vector search alone fails the second.</p><p><strong>Clash detection.</strong> Contradictions should surface before the next agent burns a night on a settled question.</p><p><strong>Scope and trail.</strong> Who wrote it, when, against which baseline, who may read it.</p><p><strong>An expiry date.</strong> True at 100 rps is not true at 10k. Stale knowledge treated as fact is worse than none, because it steers the next hundred experiments.</p><p>Meta and several universities ran the obvious experiment: let agents rewrite not just how they solve tasks but how they generate their own improvements. Unprompted, across coding and robotics, they built persistent memory and performance tracking for themselves. The harness we keep hand-building is the one a system converges on when nobody specifies it.</p><p>The loops work. That question is settled. The open one is whether what they find survives the night that produced it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f3a88d7e88d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Caching Doesn’t Cut Your AI Bill by 90%. Cache Hits Do.]]></title>
            <link>https://medium.com/@rare-major/prompt-caching-doesnt-cut-your-ai-bill-by-90-cache-hits-do-6aed54bc12be?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aed54bc12be</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 17:37:27 GMT</pubDate>
            <atom:updated>2026-08-25T17:52:02.343Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>For software engineers, prompt caching is best understood as an incremental build cache for AI context, not a Redis cache for finished answers.</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ivuNfBPnvFM93cD5" /><figcaption>Photo by <a href="https://unsplash.com/@aiaiandai?utm_source=medium&amp;utm_medium=referral">Jacob Mindak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Stable instructions, tools, standards, and repository documentation can feed many different requests. The cached artifact is intermediate model state; each answer is still generated afresh.</em></p><p>The promise is difficult to resist: cached AI input can cost roughly one-tenth of ordinary input. Put a cache in front of your prompts, the pitch seems to say, and the AI bill falls by as much as 90%.</p><p>Software engineers should already be suspicious of that sentence.</p><p>We have seen the same mistake with CDNs, database buffers, browser caches, memoization, and incremental builds. Installing a cache is not the same as benefiting from one. The result depends on cache keys, hit rates, invalidation, expiry, storage cost, and the shape of the workload.</p><p>Prompt caching follows the same rule. A provider can offer a 90% discount on <em>cached input tokens</em> while an application saves far less overall — or even spends more. The discount is real. The implied conclusion is not.</p><p>The right mental model is simple:</p><blockquote><em>Prompt caching is an incremental build system for the beginning of an AI request.</em></blockquote><p>Once you see it that way, the mechanics and the failure modes become much more familiar.</p><h3>1. The misleading promise: “90% cheaper” is not 90% off the bill</h3><p>An AI invoice can contain several kinds of spending:</p><ul><li>Ordinary input tokens</li><li>Cache-write tokens</li><li>Cache-read tokens</li><li>Output tokens</li><li>Cache storage</li><li>Model tools such as search or code execution</li><li>In some systems, different rates for long contexts, priority service, or regional processing</li></ul><p>The large advertised discount normally applies to only one row: cache-read input.</p><p>Imagine that input represents half of an application’s original AI bill. Eighty percent of that input is reusable, and 80% of the reusable portion actually hits the cache. Even with a 90% read discount, the theoretical reduction in the total bill is only:</p><pre>50% input share<br>× 80% cacheable input<br>× 80% cache-hit rate<br>× 90% read discount<br>= 28.8% total saving</pre><p>That calculation still ignores write premiums and storage charges.</p><p>“Up to 90% cheaper cached input” is therefore a unit-price claim, much like “a CDN hit avoids 90% of origin work.” It tells you nothing about how much of your traffic will hit the CDN — or how much of your total cost was origin work in the first place.</p><h3>2. What is actually cached</h3><p>An LLM request has two simplified stages:</p><ol><li><strong>Prefill:</strong> The model reads the prompt and computes the internal attention state required to understand it.</li><li><strong>Generation:</strong> The model produces the answer, token by token.</li></ol><p>Prompt caching reuses work from the first stage. OpenAI describes the cached artifact as internal key-value, or KV, tensors rather than a stored copy of the tokens themselves. The later request still has to process anything new and generate a fresh answer. <a href="https://developers.openai.com/api/docs/guides/prompt-caching">OpenAI’s prompt-caching documentation</a> explains this distinction directly.</p><p>That makes prompt caching closer to a <strong>precompiled header</strong> than a conventional response cache.</p><p>Suppose an AI pull-request reviewer receives this context on every call:</p><pre>Reviewer instructions             3,000 tokens<br>Tool definitions                  4,000 tokens<br>Company coding standards         10,000 tokens<br>Repository documentation         20,000 tokens<br>────────────────────────────────────────────<br>Reusable prefix                  37,000 tokens</pre><pre>Current pull-request diff         5,000 tokens<br>Current reviewer question           200 tokens<br>────────────────────────────────────────────<br>Changing suffix</pre><p>The 37,000-token prefix resembles a shared header or stable build dependency. It can be processed once and reused. The current diff resembles a source file that still needs to be compiled. The final review is not retrieved from a cache; it is newly generated.</p><p>This distinction has practical consequences:</p><ul><li>Cached input still occupies context-window space.</li><li>Output generation is still chargeable.</li><li>Caching primarily improves prompt-processing cost and time to first token.</li><li>It does not make an answer deterministic.</li><li>Implicit caching may still require the application to transmit the complete prompt.</li></ul><h3>Prefixes are the cache key</h3><p>Prompt caches generally match from the beginning of the rendered request. The useful layout is:</p><pre>[stable instructions]<br>[stable tool definitions]<br>[stable examples]<br>[stable repository or policy material]<br>[dynamic user and tenant data]<br>[current question]</pre><p>Put a changing timestamp at the top, alter a tool schema, reorder an earlier message, or rewrite the conversation history, and reuse may stop at the first difference. This is the AI equivalent of changing a foundational header and triggering a much larger rebuild than expected.</p><p>The design rule is the same one engineers use for composite indexes and reusable build layers:</p><blockquote><em>Stable content first. Dynamic content last.</em></blockquote><h3>3. The three-part ledger</h3><p><em>Cache reads create the saving. Premium writes and storage consume it. Output generation remains outside the bargain.</em></p><p>Let:</p><ul><li>P be the ordinary input price</li><li>W be the cache-write price</li><li>R be the cache-read price</li></ul><p>Then the realized value of caching can be estimated from actual usage:</p><pre>Realized savings<br>= cache-read tokens × (P − R)<br>− cache-write tokens × (W − P)<br>− cache-storage cost</pre><p>This equation is more useful than any marketing percentage.</p><p>It also explains why providers with similar read discounts can produce different outcomes. If a cache miss is charged like ordinary input and storage is free, a miss is economically neutral and every hit helps. If a miss creates a cache entry at 1.25 times the ordinary price, low-reuse traffic can become more expensive. If an explicit cache is rented by the hour, a largely idle cache can lose money even though every eventual read is cheap.</p><p>For an in-band cache where the first request writes and later requests read, the repeated-prefix cost is:</p><pre>Without caching = N × P<br>With caching    = W + (N − 1) × R</pre><p>The break-even request count is:</p><pre>N ≥ (W − R) / (P − R)</pre><p>With a 1.25× write and a 0.1× read, one write followed by one hit is already cheaper than processing the prefix twice normally. But that is not a universal “second request” rule. A 2× write for longer retention needs more reuse. An explicitly created cache with hourly storage needs enough future queries to pay for both creation and rent.</p><h3>4. Three workloads, three different answers</h3><h4>Workload A: the busy code-review service</h4><p>Our pull-request reviewer has a 37,000-token shared prefix. During a busy deployment window, it reviews ten PRs with the same instructions and repository material.</p><p>Without caching, the shared context is processed ten times: ten ordinary cost units.</p><p>With a 1.25× first write and nine reads at 0.1×:</p><pre>1 × 1.25 + 9 × 0.10 = 2.15 cost units</pre><p>The shared-input component becomes 78.5% cheaper. This is the workload behind the impressive prompt-caching case study: a long stable prefix, concentrated reuse, and very little invalidation.</p><p>The PR-specific input and generated review remain fully chargeable, so the total application saving will be lower than 78.5%.</p><h4>Workload B: the quiet internal assistant</h4><p>Now imagine an overnight engineering assistant with 3,000 tokens of cached instructions and one request every eight minutes. Its cache expires after five minutes.</p><p>Every request writes a new entry. No request arrives in time to read it.</p><p>If each write costs 1.25× ordinary input, the application pays 25% more for that prefix than it would without caching. The cache is functioning technically — it is creating entries — but failing economically.</p><p>Global request volume is not the deciding number. The deciding distribution is the reuse interval for each identical cache key.</p><h4>Workload C: the growing incident-response conversation</h4><p>Consider an incident assistant whose conversation grows by roughly 2,000 tokens per turn for 30 turns. A stateless client resends the whole conversation on every request.</p><p>Without reuse, the input volume is:</p><pre>2,000 × (1 + 2 + 3 + … + 30)<br>= 930,000 tokens</pre><p>An append-only rolling cache can reuse the earlier conversation and process only the new suffix. This is where prompt caching is structurally powerful: the workload naturally grows from a stable prefix.</p><p>It is also why rewriting, summarizing, or reordering earlier conversation turns can unexpectedly increase cost. Those operations may be useful for context management, but they can reset prefix reuse.</p><h3>5. “Prompt caching” does not mean the same thing everywhere</h3><p>Provider behavior should be treated as part of the system design, not a purchasing footnote.</p><p><strong>OpenAI GPT-5.6 and later.</strong> Prompt caching is supported by default, with implicit and explicit breakpoint controls. The documented minimum is 1,024 visible input tokens, the cache-read rate is 0.1x, the write rate is 1.25x, and the current lifetime is at least 30 minutes after the latest write or reuse. Earlier models have different rules. <a href="https://developers.openai.com/api/docs/guides/prompt-caching">Documentation</a></p><p><strong>Anthropic Claude.</strong> Applications can use automatic caching or place explicit breakpoints. The default cache lasts five minutes; one-hour retention has a higher write price. Five-minute writes are documented at 1.25x, one-hour writes at 2x, and reads at 0.1x. <a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">Documentation</a></p><p><strong>Google Gemini.</strong> Gemini offers automatic implicit caching and manually managed explicit cache objects. Explicit caches have a configurable TTL and storage cost. Minimum eligible input length varies by model. <a href="https://ai.google.dev/gemini-api/docs/caching">Caching guide</a> and <a href="https://ai.google.dev/gemini-api/docs/pricing">pricing</a></p><p><strong>DeepSeek.</strong> Context caching is automatic and best-effort. It persists reusable prefix units to disk, reports hit and miss tokens, and may retain unused entries for hours to days before clearing them. <a href="https://api-docs.deepseek.com/guides/kv_cache/">Caching guide</a> and <a href="https://api-docs.deepseek.com/quick_start/pricing">pricing</a></p><p><strong>xAI.</strong> Prompt caching is automatic for matching starting messages. A stable conversation or cache key improves routing, but entries may be evicted because of load or restarts. <a href="https://docs.x.ai/developers/advanced-api-usage/prompt-caching">Documentation</a></p><p>These details change. Any article, architecture decision record, or cost model using exact provider prices should be date-stamped. The behavior summarized here was checked on <strong>25 August 2026</strong>.</p><h3>6. The invisible cache killers</h3><p><em>The usual causes look familiar: invalidation, fragmentation, expiry, idle storage, cold bursts, and configuration churn.</em></p><h4>1. Prefix drift</h4><p>A timestamp, changing instruction, reordered JSON property, modified tool schema, or request-specific value appears before the stable content. The application looks repetitive to a human, but the model sees a different prefix.<br>Canonicalize serialized structures, keep tool ordering stable, and move changing fields toward the end.</p><h4>2. High key cardinality</h4><p>Every user, repository, document, or tenant may create a separate cache population. A service handling thousands of requests per minute can still have poor locality when each cache key receives only one request.<br>Measure reuse per key. Do not use aggregate QPS as a proxy for cacheability.</p><h4>3. TTL mismatch</h4><p>The same content returns, but after the entry expires. Average traffic spacing can hide this because requests may be bursty or spread across many keys.<br>Use the distribution of time between reuses for each prefix. Compare its percentiles with the provider’s retention behavior.</p><h4>4. Storage overprovisioning</h4><p>An explicit cache is retained for a day even though it receives only a few queries. Cheap reads are overwhelmed by hourly storage charges.<br>Choose TTL from measured reuse, and delete explicit caches when the owning job, session, or document workflow ends.</p><h4>5. Cold parallel bursts</h4><p>Many requests launch before the first cache write becomes available. They all perform the expensive work, producing the AI equivalent of a cache stampede.<br>Where the provider permits it, pre-warm important prefixes or use a single-flight mechanism so one request establishes the entry before the fan-out.</p><h4>6. Minimum-length failures</h4><p>Providers impose minimum cacheable prefix lengths. A small system prompt may be marked for caching but silently processed normally because it is too short.<br>Inspect usage metadata rather than assuming that the presence of a cache setting means an entry was created.</p><h4>7. Output-dominated workloads</h4><p>Caching makes input cheaper, but the application produces large reports, extensive reasoning, or long code patches. Output remains the majority of spending.<br>Track the input and output shares of cost separately. A high input-cache hit rate can coexist with a disappointing total saving.</p><h4>8. Long-context pricing thresholds</h4><p>Cached tokens can still occupy the context window and, depending on the provider, contribute to long-context pricing or rate-limit calculations. Caching avoids some recomputation; it does not make the context disappear.<br>Include cached tokens when modeling context size, throughput, and model limits.</p><h4>9. Frequent model or configuration changes</h4><p>Changing the model, reasoning configuration, tool definitions, output schema, or earlier instructions can prevent reuse. A rapidly changing prompt framework behaves like a build whose base image is rebuilt on every commit.<br>Version stable prompt bundles deliberately and observe cache performance during migrations.</p><h4>10. Confusing caching with retrieval</h4><p>Prompt caching and retrieval-augmented generation solve different problems.</p><ul><li><strong>Retrieval</strong> decides which information should be placed in the prompt.</li><li><strong>Prompt caching</strong> avoids recomputing a prefix that has already been placed there.</li></ul><p>If an application owns ten thousand documents and each is queried once, retrieval may reduce the input much more effectively than caching all of them. If the same selected document or repository context is queried repeatedly, retrieval and caching can be combined.</p><p>Caching is compute reuse. Retrieval is context selection.</p><h3>7. What teams should measure</h3><p>An API invoice is too aggregated to explain cache performance. The necessary evidence exists in per-request usage metadata: providers report some combination of ordinary input, cache reads, cache writes, and cache misses.</p><p>At minimum, collect these metrics by model, prompt version, tenant class, workload, and cache key:</p><h4>Token-weighted cache-hit rate</h4><p>Count cached tokens, not merely requests with at least one cached token. A request that hits on 1,000 tokens and misses on 50,000 should not be considered a successful cache outcome.</p><pre>Token-weighted hit rate<br>= cache-read tokens<br>  ÷ eligible reusable-prefix tokens</pre><h4>Cache-write amplification</h4><p>Track how many tokens are repeatedly written compared with how many are later read. Frequent writes with few reads reveal expiry, drift, fragmentation, or a poorly chosen breakpoint.</p><h4>Counterfactual input cost</h4><p>Calculate what the same tokens would have cost at the ordinary input rate, then compare that figure with the actual read, write, and storage charges. This produces realized savings rather than theoretical savings.</p><h4>Input versus output spend</h4><p>Report the two independently. Otherwise, excellent input-cache performance can be hidden by growing output — or celebrated even though it barely affects the total bill.</p><h4>Time to first token</h4><p>Compare cache hits and misses at p50 and p95. Prompt caching is partly a latency feature, especially for long prefixes, and the benefit can matter even when the dollar saving is modest.</p><h4>Key cardinality and reuse distance</h4><p>Measure the number of active cache keys and the time between uses of each key. This connects traffic architecture directly to retention choice.</p><h3>8. Prompt caching is a workload property</h3><p>There is no meaningful universal answer to “Should we turn on prompt caching?”</p><p>The answer belongs to a specific combination of:</p><ul><li>Prompt structure</li><li>Reusable-prefix length</li><li>Cache-key cardinality</li><li>Reuse frequency</li><li>Retention and eviction behavior</li><li>Read, write, and storage prices</li><li>Input-output cost mix</li><li>Model and configuration stability</li></ul><p>That is ordinary caching engineering. The AI terminology is new; the operational lesson is not.</p><p>A good prompt cache resembles a good incremental build: stable foundations are processed once, changing work is appended, invalidation is deliberate, and the team measures what was actually reused. A bad prompt cache resembles every other bad cache — high cardinality, constant churn, short-lived entries, and a dashboard celebrating writes that nobody reads.</p><p>The provider determines the rate card. Your architecture determines whether it becomes a saving.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aed54bc12be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The .md Files Running Your Dev Team Now]]></title>
            <link>https://medium.com/@rare-major/the-md-files-running-your-dev-team-now-c98a963e137f?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/c98a963e137f</guid>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[sdd]]></category>
            <category><![CDATA[spec-driven-development]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Tue, 26 May 2026 03:57:37 GMT</pubDate>
            <atom:updated>2026-05-26T03:57:37.101Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Spec-Driven Development and a handful of Markdown files are replacing half the chaos in AI-assisted coding</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVOBJ4nWh2Q3S_OvjfKDnA.jpeg" /></figure><blockquote><em>You asked your AI coding assistant to “build a login system.” It wrote beautiful code. Two days later you asked it to “add Google OAuth.” It broke the login system. Again. Sound familiar?</em></blockquote><p><strong>In this article</strong></p><ol><li>Why AI coding goes wrong without specs</li><li>The SDD maturity ladder</li><li>The players: BMAD, spec-kit, OpenSpec</li><li>The MD files — what they do, when to write them</li><li>A real example from start to ship</li><li>Impact on developer productivity</li><li>Choosing your framework</li></ol><h3>The “Vibe Coding” Hangover</h3><p>There’s a name for the first generation of AI-assisted development: <em>vibe coding</em>. You paste a rough requirement into your AI chat, it generates something, you paste the output into your IDE, and you iterate until it kind of works. For a weekend hackathon? Perfect. For a production codebase with six engineers and a CTO who reads changelogs? Catastrophic.</p><p>The problem isn’t the AI. The problem is that every prompt you type is essentially a fresh conversation with a goldfish that has access to your entire codebase but remembers none of your previous decisions. Ask it to “add dark mode” and it will cheerfully invent its own component structure, ignore the one you documented in a Slack thread three months ago, and use Tailwind classes your project doesn’t have.</p><p>This is called context drift — and it’s why Spec-Driven Development (SDD) has become one of the hottest topics in engineering circles in 2025 and 2026.</p><blockquote>Context drift in a nutshell: Developers prompt AI with a mixture of requirements, assumptions, and half-remembered decisions. The context changes with every prompt, inconsistencies appear, bugs appear. Some prompts generate code, some tests, some docs — none guarantee alignment. If a developer leaves, their “AI prompting style” leaves with them.</blockquote><h3>What Is Spec-Driven Development?</h3><p>SDD is a methodology that treats the specification, not the code, as the primary artifact. Instead of code being the source of truth, a rigorously defined spec becomes the living blueprint that drives design, planning, implementation, testing, and documentation.</p><p>The spec becomes what product managers would call a “single source of truth” — except now it’s also the thing your AI agent reads before touching a single line of code.</p><p>There are three levels of SDD maturity:</p><p><strong>Level 1 · Spec-Beginner</strong></p><p>Write a spec for a specific task, use it during AI-assisted dev, possibly discard after. A real improvement over pure vibe coding. Most teams are here.</p><p><strong>Level 2 · Spec-Intermediate</strong></p><p>The spec is a <em>living document</em>, maintained throughout a feature’s lifecycle. Changes start with the spec; AI regenerates code accordingly. Most SDD tools today target this level.</p><p><strong>Level 3 · Spec-as-Source Advanced</strong></p><p>The spec is the <em>only</em> artifact humans edit. Code is a transient, compiled output — never touched by human hands. Think of it as writing HTML and having CSS generated for you, but for your entire product.</p><h3>The Three Frameworks You Should Know</h3><ol><li><strong>BMAD Method: Agentic Agile</strong></li></ol><p>Full AI persona team (PM, Architect, Scrum Master, Dev). Heavyweight but extraordinarily thorough. 19k+ GitHub stars.</p><p><strong>2. GitHub spec-kit: Enterprise</strong></p><p>GitHub-backed, phase-gated workflow. Agent-agnostic. Works with Copilot, Claude, Gemini. 39k+ GitHub stars.</p><p><strong>3. OpenSpec: Brownfield-first</strong></p><p>Lightweight, fluid, no rigid phase gates. Built for existing codebases. Supports 21 AI tools. Made by Fission-AI.</p><p><strong>All three converge on the same core idea: structure your intent before you write your code, and store that structure in Markdown files your AI can read. Where they differ is how strict, how opinionated, and how much ceremony they require.</strong></p><h3>The MD Files — A Field Guide</h3><p>Here’s the thing nobody tells you: it’s not the <em>framework</em> that matters most. It’s the individual Markdown files and when you write them. Let’s walk through each one.</p><h4>1. constitution.md — The Non-Negotiables</h4><p><strong>.specify/memory/constitution.md</strong> write once, update rarely</p><p><strong>What it is</strong>: The fixed rules of your project that no AI agent should ever violate. Think of it as the Constitution of your codebase.</p><p><strong>Used by</strong>: spec-kit · Defines project principles, coding standards, security rules, team conventions. Becomes “long-term memory” for the AI — a fixed anchor that prevents it from drifting off course between sessions.</p><pre># constitution.md</pre><pre>## Non-negotiable rules<br>- All API routes must use /v1/ prefix<br>- Never use raw SQL — use the ORM<br>- Auth is handled by the AuthService, never inline<br>- Every PR must include tests for new endpoints</pre><pre>## Stack<br>frontend: React 18, TypeScript, Tailwind CSS<br>backend:  Node.js 22, Fastify, PostgreSQL<br>infra:    AWS, deployed via CDK</pre><p>The constitution is a <em>permanent context</em>. Without it, every new AI session starts from zero. With it, the AI knows your stack, your rules, your red lines — before you type a single word.</p><p>Productivity impact: Teams report spending far less time re-explaining the same architectural decisions to AI agents. Instead of “remember, we use Fastify, not Express” in every session, it’s just… known.</p><h3>2. spec.md — The What and Why</h3><p><strong>.specify/spec.md</strong> write at feature start</p><p><strong>What it is</strong>: High-level goals, user needs, acceptance criteria. What should this feature do and for whom?</p><p><strong>Used by</strong>: spec-kit · This is declarative programming for humans. Instead of telling the AI <em>how</em> to build something, you tell it <em>what</em> the user needs and <em>why</em>.</p><pre># spec.md — User Authentication Feature</pre><pre>## Goal<br>Allow users to sign up and log in using email/password<br>or Google OAuth. Sessions should persist for 7 days.</pre><pre>## Users<br>- New visitors who want to create an account<br>- Returning users who want to log in</pre><pre>## Acceptance criteria<br>- Given a valid email+password, the user can sign up<br>- Given wrong credentials, a clear error is shown<br>- Given a session timeout, the user is redirected to /login<br>- Google OAuth must work on mobile and desktop</pre><pre>## Out of scope<br>- Two-factor authentication (planned for v2)<br>- Enterprise SSO</pre><p>Notice the <em>Given/When/Then</em> pattern. This isn’t an accident. Well-written acceptance criteria are machine-readable contracts. Your AI agent, reading this file, knows exactly what “done” means. It can write tests against these criteria before writing a single line of implementation code.</p><h3>3. plan.md — The How</h3><p><strong>.specify/plan.md</strong>, write after spec is approved</p><p><strong>What it is</strong>: Technical approach, architectural decisions, library choices, data flow. <em>How</em> will the system be built?</p><p><strong>Used by</strong>: spec-kit, BMAD · Translates human intent into technical constraints. Also generates data-model.md, api-contracts.md, and similar artifacts automatically when using AI planning agents.</p><pre># plan.md</pre><pre>## Architecture decisions<br>Auth library:  Passport.js with local + Google strategies<br>Sessions:      JWT stored in HttpOnly cookie<br>DB schema:     users table + oauth_accounts table (1:many)<br>Error format:  { code: string, message: string } — RFC 7807</pre><pre>## Data flow<br>POST /v1/auth/signup<br>  → validate input (zod schema)<br>  → hash password (bcrypt, 12 rounds)<br>  → insert users row<br>  → generate JWT<br>  → set HttpOnly cookie<br>  → return { userId, email }</pre><pre>## Constraints<br>- Password must be min 8 chars, max 72 (bcrypt limit)<br>- Google OAuth client ID is in env: GOOGLE_CLIENT_ID</pre><p>The plan.md is where engineering judgment lives. It’s the document the Architect persona in BMAD produces, and the document the spec-kit CLI helps you refine. Once it exists, a developer agent has the full context to generate correct code on the first try — not the fourth.</p><h3>4. tasks.md — The Checklist</h3><p><strong>.specify/tasks.md</strong>, auto-generated from plan</p><p><strong>What it is</strong>: Atomic, reviewable, testable units of work derived from the plan. Each task is small enough for one AI session to handle.</p><p><strong>Used by</strong>: spec-kit, BMAD, OpenSpec · This is where the rubber meets the road. AI agents iterate through tasks.md one by one, in strict mode writing a test first (red), then code (green), before moving on.</p><pre># tasks.md</pre><pre>- [ ] Create users table migration (id, email, password_hash, created_at)<br>- [ ] Create oauth_accounts table migration<br>- [ ] Implement POST /v1/auth/signup endpoint with zod validation<br>- [ ] Add bcrypt password hashing (12 rounds)<br>- [ ] Implement JWT generation + HttpOnly cookie setting<br>- [ ] Implement POST /v1/auth/login with credential check<br>- [ ] Add Passport.js Google strategy<br>- [ ] Implement GET /v1/auth/google + callback handler<br>- [ ] Write integration tests for all acceptance criteria<br>- [x] Set up Passport.js in Fastify plugin system</pre><p>The checkboxes matter. When an AI agent marks a task complete and moves to the next, you always know exactly where you are. No more “did it do the OAuth thing?” — you have a paper trail in version control.</p><h3>5. prd.md — The Product Requirements Document (BMAD)</h3><p><strong>docs/prd.md</strong>, BMAD-specific</p><p><strong>What it is</strong>: In BMAD, the PM Agent generates a full Product Requirements Document with epics, user stories, non-functional requirements, and MVP scope. It’s richer than spec-kit’s spec.md.</p><p><strong>When to use</strong>: Greenfield projects or large feature sets where you want AI to generate 20+ user stories with Gherkin acceptance criteria, dependencies, and explicit out-of-scope items.</p><p>BMAD’s PRD is produced by its PM Agent and includes functional requirements (FR-01, FR-02…), non-functional requirements (performance, security, scalability), epics grouped by feature, and detailed user stories in <em>Given/When/Then</em> format. The newly released BMAD v6 alpha rebuilds the PRD as a “lean, outcome-driven facilitator” with three modes: Create, Update, and Validate.</p><h3>6. architecture.md — The System Blueprint (BMAD)</h3><p><strong>docs/architecture.md, </strong>BMAD-specific</p><p><strong>What it is</strong>: The Architect Agent in BMAD generates a full technical architecture document — tech stack selection with justifications, API and data flow specs, security decisions, scalability considerations, and a diagram of the overall system.</p><p><strong>When to use</strong>: Enterprise or complex projects. The architecture.md becomes the authority for all downstream decisions. Developer agents check it before writing any code.</p><h3>7. proposal.md + design.md — The OpenSpec Pair</h3><p><strong>openspec/changes/feature-name/proposal.md</strong>, OpenSpec</p><p><strong>What it is</strong>: In OpenSpec, every change starts with a proposal — the <em>why</em>, <em>what</em>, and rollback plan. Once approved, a design.md is added with the technical approach. Then tasks.md is generated. On completion, the spec merges back into openspec/specs/ as the new permanent truth.</p><p><strong>Best for</strong>: Brownfield projects where you’re modifying an existing system and need an audit trail of what changed and why.</p><p>The OpenSpec approach is elegantly simple: each feature gets its own folder under openspec/changes/, goes through a fluid (not phase-locked) lifecycle, and when complete, gets archived. The main openspec/specs/ directory always reflects the current state of the world.</p><h3>8. [number].story.md — The User Story Files (BMAD)</h3><p><strong>docs/stories/01.story.md, </strong>BMAD-specific</p><p><strong>What it is</strong>: BMAD’s Scrum Master Agent breaks the PRD into individual, hyper-detailed story files. Each story has full context, implementation hints, architectural references, and a definition of done. A Developer Agent picks up one story file per session.</p><p><strong>Why it works</strong>: A developer agent working from a story file cannot drift — all the context is right there. This solves the “context window” problem that plagues long AI coding sessions.</p><h3>The Full Flow — From Idea to Shipped</h3><p>Here’s how the MD files connect in practice. Let’s use spec-kit’s model as the clearest example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IF9E-lBiBy8lZw6hNTKTpg.png" /></figure><p>And here’s the OpenSpec model for brownfield work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGXCWuf5FbKn2Lkyh8v0Ng.png" /></figure><h3>Impact on Developer Productivity</h3><p>Here’s the honest answer: done right, SDD can dramatically compress the feedback loop between idea and working code. Done wrong (over-specified, over-ceremonious), it’s just more bureaucracy.</p><p>What the community and practitioners report:</p><ul><li>Faster onboarding: New team members get up to speed by reading the spec files. The artifacts tell the story of every architectural decision.</li><li>Less re-work: Because the AI operates from a spec, it doesn’t reinvent things that were already decided. The context is persistent.</li><li>Auditable decisions: The decision-log pattern introduced in BMAD&#39;s recent releases means every architectural trade-off is documented alongside the code that implements it.</li><li>Cycle time reduction: BMAD cites roughly 30% reduction in cycle time. These numbers come from teams fully committed to the method, not casual adopters.</li><li>Better AI behavior: Specialized agents (Architect won’t write tests, Developer won’t redefine product goals) produce more consistent outputs than a single general-purpose AI session.</li></ul><blockquote>“The most valuable engineers will be those who write the best specs, not the cleverest code.”</blockquote><p>This shift is real. But it comes with an honest caveat: SDD requires discipline upfront. Writing a good spec.md takes time. Writing a good constitution.md requires genuine architectural thought. These are not activities that scale to one-off scripts or solo weekend projects.</p><p><strong>When SDD makes sense</strong></p><p>✓ You have more than one developer (or AI agent) working on a codebase</p><p>✓ Your project will live longer than one sprint</p><p>✓ You’re using AI coding assistants regularly and noticing context drift</p><p>✓ You want new team members to get productive quickly without extensive handholding</p><p>✗ Solo weekend hackathon — just vibe code, honestly</p><p>✗ Throwaway prototype you’ll rewrite anyway</p><h3>Choosing Your Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TV8IJ_z78wKM7kVE0ouXfw.png" /></figure><h3>The Quick Start You Can Do Right Now</h3><p>If you want to try spec-kit today with Claude Code or GitHub Copilot, it’s one command:</p><pre># Install the specify CLI<br>npm install -g @github/specify</pre><pre># Scaffold your project (choose your AI agent)<br>specify init</pre><pre># This creates:<br># .specify/<br>#   ├── spec-template.md<br>#   ├── plan-template.md<br>#   ├── tasks-template.md<br>#   └── memory/constitution.md<br># .github/<br>#   ├── specify.prompt.md<br>#   ├── plan.prompt.md<br>#   └── tasks.prompt.md</pre><p><strong>For OpenSpec:</strong></p><pre>npm install -g openspec<br>openspec init</pre><pre># Then in your AI tool, use slash commands:<br># /opsx:propose — start a new change<br># /opsx:verify  — check spec vs code alignment<br># /opsx:archive — merge completed change into main specs</pre><p><strong>For BMAD:</strong></p><pre>npx bmad-method install<br># Follow prompts to choose your IDE (Cursor, Claude Code, etc.)<br># Then in your IDE: @pm Create a PRD for [your project]</pre><h3>The Takeaway</h3><p>The AI coding revolution is real. But the teams winning with it aren’t the ones prompting the hardest — they’re the ones who put structure around their intent before asking AI to write a single line.</p><p>Markdown files are not glamorous. They don’t ship features directly. But a well-crafted constitution.md is worth more than three hours of prompt engineering. A clear spec.md with proper acceptance criteria is worth more than a hundred inline comments. And a tasks.md that an AI agent can work through methodically will produce more consistent code than any general-purpose chat session.</p><p>The spec is not overhead. The spec is the product.</p><h4><strong>References and further reading:</strong></h4><p><strong>1. </strong>BMAD Method docs at <a href="https://docs.bmad-method.org/">docs.bmad-method.org</a> <br>2. GitHub spec-kit at <a href="https://github.com/github/spec-kit">github/spec-kit</a> (39k+ stars) <br>3. OpenSpec at <a href="https://github.com/Fission-AI/OpenSpec">Fission-AI/OpenSpec</a> <br>4. Microsoft Developer Blog on Spec-Kit (Sept 2025) <br>5. BMAD community Discord</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c98a963e137f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kafka Offsets: The Key to Reliable Message Processing]]></title>
            <link>https://medium.com/@rare-major/understanding-kafka-offsets-the-key-to-reliable-message-processing-e6c844c84d2a?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6c844c84d2a</guid>
            <category><![CDATA[topics]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[kafka-producer]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Sat, 15 Mar 2025 17:13:00 GMT</pubDate>
            <atom:updated>2025-03-15T17:13:00.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AVaBOyOrF60FQtYt" /><figcaption>Photo by <a href="https://unsplash.com/@martinadams?utm_source=medium&amp;utm_medium=referral">Martin Adams</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction: The Fundamentals of Kafka Offsets</h3><p>Apache Kafka is a distributed event streaming platform widely used for real-time data processing. Unlike traditional message queues, where messages are removed after being consumed, Kafka retains messages for a configured period, allowing multiple consumers to read the same data independently.</p><p>A fundamental concept in Kafka is the <strong>offset</strong>, which represents a unique identifier for each message within a partition. Offsets play a crucial role in ensuring that consumers can track and resume message consumption accurately. In this article, we’ll explore how Kafka manages offsets, ensures at-least-once or exactly-once delivery, and prevents duplicate message consumption.</p><h3>How Kafka Offsets Work</h3><p>Each Kafka topic consists of multiple partitions, and messages within each partition are assigned a sequential offset. Consumers use these offsets to keep track of which messages have been read.</p><h3>Key Offset Properties:</h3><ul><li><strong>Per Partition:</strong> Offsets are unique within a partition but not across partitions.</li><li><strong>Immutable:</strong> Once assigned, an offset does not change.</li><li><strong>Retained Until Expiry:</strong> Kafka retains messages based on a time-based or size-based policy, not based on consumption.</li></ul><p>When a consumer reads messages from Kafka, it can choose to <strong>commit offsets</strong>, which means marking a message as successfully processed. These committed offsets allow consumers to restart from the last processed message if they fail or restart.</p><h4>Checking Offsets in Kafka</h4><p>You can check committed offsets for a consumer group using:</p><pre>kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group &lt;consumer-group-name&gt; --describe</pre><h3>Ensuring Exactly-Once or At-Least-Once Processing</h3><p>Since Kafka messages are <strong>not deleted upon consumption</strong>, a consumer might read the same message multiple times unless offsets are managed properly. Kafka provides two main delivery semantics:</p><h3>1. At-Least-Once Processing (Default Behavior)</h3><ul><li>The consumer fetches a batch of messages.</li><li>The messages are processed.</li><li>The consumer commits the latest offset.</li><li>If the consumer crashes before committing, it may process some messages again after restarting.</li></ul><h4>Example of At-Least-Once Processing in Java</h4><pre>KafkaConsumer&lt;String, String&gt; consumer = new KafkaConsumer&lt;&gt;(props);<br>consumer.subscribe(Collections.singletonList(&quot;orders-topic&quot;));<br>while (true) {<br>    ConsumerRecords&lt;String, String&gt; records = consumer.poll(Duration.ofMillis(100));<br>    for (ConsumerRecord&lt;String, String&gt; record : records) {<br>        System.out.println(&quot;Processing order: &quot; + record.value());<br>    }<br>    consumer.commitSync();  // Commit offsets after processing<br>}</pre><h3>2. Exactly-Once Processing (via Kafka Transactions)</h3><ul><li>Kafka transactions allow producers and consumers to ensure exactly-once processing using the <strong>idempotent producer</strong> and <strong>transactional consumer</strong> features.</li><li>Offsets are committed atomically with message processing.</li><li>Ensures no duplicates are processed, even in failure scenarios.</li></ul><h4>Transactional Producer Example</h4><pre>producer.initTransactions();<br>try {<br>    producer.beginTransaction();<br>    producer.send(new ProducerRecord&lt;&gt;(&quot;orders-topic&quot;, key, value));<br>    producer.commitTransaction();<br>} catch (ProducerFencedException e) {<br>    producer.abortTransaction();<br>}</pre><h3>How Kafka Prevents Multiple Consumption of Messages</h3><p>Kafka prevents multiple consumption of messages through <strong>consumer groups</strong> and offset management:</p><ol><li><strong>Consumer Groups:</strong></li></ol><ul><li>Each consumer group has one or more consumers reading from the same topic.</li><li>Kafka ensures that each partition is assigned to only one consumer within a group.</li><li>Different consumer groups can independently read the same data.</li></ul><p><strong>2. Offset Committing:</strong></p><ul><li>Kafka provides <strong>automatic</strong> and <strong>manual</strong> offset committing.</li><li>If offsets are not committed, messages can be read multiple times upon consumer restarts.</li><li>Using <strong>enable.auto.commit=true</strong>, Kafka commits offsets automatically, but this may lead to duplicates in failures.</li><li>Manual offset commits using <strong>commitSync()</strong> or <strong>commitAsync()</strong> provide better control.</li></ul><h4>Manually Committing Offsets</h4><pre>consumer.commitAsync((offsets, exception) -&gt; {<br>    if (exception != null) {<br>        System.err.println(&quot;Commit failed for offsets &quot; + offsets + exception);<br>    }<br>});</pre><h3>Where Kafka Stores Offset Information</h3><p>Kafka stores committed offsets in a special internal topic called __consumer_offsets. This topic is <strong>compacted</strong>, meaning older offsets are periodically removed, retaining only the latest committed offset for each partition.</p><h3>Checking Offsets in __consumer_offsets Topic</h3><pre>kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic __consumer_offsets --from-beginning --formatter &quot;kafka.coordinator.group.GroupMetadataManager$OffsetsMessageFormatter&quot;</pre><h3>Log Compaction in __consumer_offsets</h3><ul><li>Kafka removes outdated offsets and keeps only the <strong>latest committed offset</strong> per (consumer group, topic, partition) tuple.</li><li>This ensures efficient lookup while keeping storage minimal.</li></ul><h4>Example of Log Compaction:</h4><p>Before compaction:</p><pre>(order-service-group, orders-topic, 0) → Offset 100<br>(order-service-group, orders-topic, 0) → Offset 200<br>(order-service-group, orders-topic, 0) → Offset 300</pre><p>After compaction:</p><pre>(order-service-group, orders-topic, 0) → Offset 300</pre><p>This ensures that only the latest offset is retained, preventing unnecessary storage usage.</p><h3>Managing Consumer Offsets Effectively</h3><p>To ensure efficient and reliable message processing, consider these best practices:</p><h3>1. Use Proper Offset Commit Strategies</h3><ul><li><strong>Manual committing (commitSync or commitAsync)</strong> is preferred over automatic commits for better control.</li><li>Use <strong>idempotent producers</strong> and <strong>transactions</strong> for exactly-once processing.</li></ul><h3>2. Tune Offset Retention Settings</h3><ul><li>Kafka deletes offsets if a consumer group is inactive beyond offsets.retention.minutes (default <strong>7 days</strong>).</li><li>Modify this setting if long inactivity periods are expected: offsets.retention.minutes=20160 # 14 days</li></ul><h3>3. Handle Consumer Failures Gracefully</h3><ul><li>Restarting a consumer should always fetch the latest committed offset from __consumer_offsets.</li><li>Set auto.offset.reset=earliest or auto.offset.reset=latest depending on whether you want to start from the beginning or only new messages.</li></ul><h3>Conclusion</h3><p>Kafka’s offset management is a powerful mechanism that ensures reliability and flexibility in message consumption. Understanding how offsets work, how they are committed, and where they are stored is crucial for designing scalable and fault-tolerant Kafka consumers.</p><p>By properly managing offsets through consumer groups, manual commits, and log compaction, developers can prevent duplicate processing and optimize data consumption in Kafka-based systems.</p><p>Would you like to explore how to monitor and debug offset issues in Kafka? Let me know in the comments! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6c844c84d2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Hidden Patterns: How PCA Makes Sense of Messy Data]]></title>
            <link>https://medium.com/@rare-major/finding-hidden-patterns-how-pca-makes-sense-of-messy-data-fba8eaf1fb5b?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba8eaf1fb5b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pca-analysis]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 11:33:28 GMT</pubDate>
            <atom:updated>2025-03-02T11:33:28.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uSUaDRZgDiT0rTy-" /><figcaption>Photo by <a href="https://unsplash.com/@xavi_cabrera?utm_source=medium&amp;utm_medium=referral">Xavi Cabrera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Noisy Librarian and the Hidden Patterns</h3><p>Imagine you walk into an <strong>old library</strong> filled with thousands of books scattered everywhere. There are history books mixed with science fiction, medical journals lost among cookbooks, and ancient manuscripts buried under comic books. The librarian, an old man with round glasses, looks exhausted.</p><p>“I can’t find anything!” he exclaims. “Every time I try to organize these books, I get overwhelmed. I need a way to find the <strong>most important themes</strong> without sorting through every single page.”</p><p>You think for a moment and then ask, <strong>“What if we find the main topics that most books are about and group them accordingly?”</strong></p><p>That’s when the librarian’s eyes light up.</p><p>This is exactly the problem we face in <strong>data analysis</strong>. Large datasets often have <strong>too many variables</strong>, making it hard to see patterns. <strong>What if we could identify the most important trends without getting lost in all the details?</strong></p><p>This is where <strong>Principal Component Analysis (PCA)</strong> comes in. Just like finding the main themes in a messy library, PCA helps us discover the most important directions (principal components) in high-dimensional data.</p><p>In this article, we’ll explore <strong>how PCA works, why it’s useful, and how it can simplify complex datasets while preserving essential information</strong>.</p><h3>What is Principal Component Analysis?</h3><p>Principal Component Analysis (PCA) is a fundamental technique in <strong>data analysis and machine learning</strong>. It plays a crucial role in <strong>reducing the dimensionality</strong> of complex datasets, making them easier to interpret while improving computational efficiency.</p><p>At its core, PCA is a <strong>statistical method</strong> that transforms high-dimensional data into a <strong>lower-dimensional representation</strong>, all while preserving the most significant information. It does this by identifying new <strong>axes</strong>, called <strong>principal components</strong>, along which the data exhibits the most variation. These components are <strong>orthogonal (uncorrelated) to each other</strong>, making PCA a powerful tool for <strong>dimensionality reduction and feature extraction</strong>.</p><h4>How does PCA work?</h4><p>Principal Component Analysis (PCA) follows a structured process to transform high-dimensional data into a lower-dimensional form while preserving key patterns. Let’s break it down step by step with an intuitive analogy.</p><h4>Step 1: Standardize the Data</h4><p>Before analyzing, we <strong>standardize</strong> the dataset to ensure that all features have the same scale. This is crucial because variables with larger numerical ranges can dominate the principal components.</p><p>📌 <strong>Example:</strong><br>Imagine you’re comparing students based on <strong>height (cm)</strong> and <strong>weight (kg)</strong>. Since height values (e.g., 160 cm) are numerically larger than weight values (e.g., 60 kg), height might overpower the analysis. Standardizing ensures both have equal influence.</p><p>📌 <strong>Mathematical Formula:</strong></p><p>For each feature X, we transform it into a standardized form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8THT8cdBKF0JUMHZnPEgw.png" /></figure><h4>Step 2: Compute the Covariance Matrix</h4><p>The <strong>covariance matrix</strong> helps measure how different features vary together.</p><p>For <strong>n features</strong>, the covariance matrix is an <strong>n × n</strong> matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCY5dchMTcAY-yC5c00Tlg.png" /></figure><p>If two features are <strong>positively correlated</strong>, their covariance is <strong>positive</strong>. If they are <strong>negatively correlated</strong>, their covariance is <strong>negative</strong>.</p><p>📌 <strong>Example Covariance Matrix for 2 Features:</strong><br>If we have <strong>Height and Weight</strong>, the covariance matrix might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMvv7-Q000hNJo33Hk8VgQ.png" /></figure><h4>Step 3: Compute Eigenvalues and Eigenvectors</h4><p>Eigenvalues (λ)</p><p>An <strong>eigenvalue</strong> represents how much <strong>variance</strong> a corresponding <strong>eigenvector</strong> captures. In PCA:</p><ul><li>Larger eigenvalues → <strong>More important principal component</strong>.</li><li>Eigenvalues are <strong>always positive</strong> (λ&gt;0).</li><li>The <strong>sum of all eigenvalues</strong> equals the total variance in the dataset.</li></ul><h4>Eigenvectors (v)</h4><p>Eigenvectors are the <strong>directions</strong> along which the data varies the most.</p><ul><li>Each eigenvector corresponds to a <strong>principal component (PC)</strong>.</li><li>Eigenvectors are <strong>orthogonal (uncorrelated)</strong> to each other.</li><li>Eigenvectors are <strong>normalized</strong> to have length 1.</li></ul><p>📌 <strong>Mathematical Equation:</strong><br>Eigenvalues and eigenvectors are obtained by solving:</p><p><strong><em>Cv=λv</em></strong></p><p>where:</p><ul><li><strong><em>C</em></strong> is the covariance matrix</li><li><strong><em>v</em></strong> is an <strong>eigenvector</strong></li><li><strong><em>λ </em></strong>is the <strong>eigenvalue</strong> associated with <strong><em>v</em></strong></li></ul><h4>Step 4: Sorting Eigenvalues and Eigenvectors</h4><ul><li>Eigenvalues are <strong>sorted in descending order</strong> to find the <strong>most significant</strong> principal components.</li><li>The corresponding <strong>eigenvectors</strong> are also sorted accordingly.</li><li>The <strong>top k eigenvectors</strong> form the new <strong>reduced-dimensional space</strong>.</li></ul><p><strong>Example:</strong> If we have 3 principal components:</p><ul><li><strong>PC1 explains 70% of variance</strong></li><li><strong>PC2 explains 20% of variance</strong></li><li><strong>PC3 explains 10% of variance</strong></li></ul><p>We can <strong>ignore PC3</strong> and reduce the dataset from <strong>3D to 2D</strong> while keeping <strong>90% of the variance</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_g6pkTdVKDV4Y1DuQ3WbQ.png" /></figure><p>Now, we have successfully <strong>reduced dimensions</strong> while retaining the most <strong>important information</strong>!</p><h3>But how does it simplify the Complex data?</h3><p>PCA simplifies complex datasets while preserving essential information through <strong>dimensionality reduction</strong>. Here’s how it works:</p><p><strong>1. Finding the Most Important Directions (Principal Components)</strong></p><ul><li>A dataset with many features (dimensions) can have redundant or correlated information.</li><li>PCA identifies new <strong>axes (principal components)</strong> along which the data varies the most.</li><li>These new axes are ordered by importance — <strong>the first few components capture the most variance</strong> in the data.</li></ul><p><strong>2. Dropping Less Important Dimensions</strong></p><ul><li>After sorting the principal components by their variance (using <strong>eigenvalues</strong>),</li><li>We <strong>keep only the top kkk components</strong> that explain most of the variance.</li><li>The remaining lower-variance dimensions are dropped with <strong>minimal loss of information</strong>.</li></ul><p><strong>3. Transforming Data into a Simpler Representation</strong></p><ul><li>The original dataset is <strong>projected</strong> onto the selected principal components.</li><li>This <strong>reduces the number of features</strong> while keeping the important structure of the data.</li></ul><p><strong>Example: Image Compression</strong></p><p>Imagine a 1000x1000 pixel grayscale image (1 million pixels).</p><ul><li>If we apply PCA, we may find that <strong>only 100 principal components</strong> explain 95% of the image variation.</li><li>Instead of storing 1 million numbers, we now store only <strong>100</strong>, drastically reducing storage while keeping most details.</li></ul><h3>The Need for Dimensionality Reduction</h3><p>High-dimensional data can introduce several challenges, making analysis and modeling more difficult. Some key issues include:</p><ol><li><strong>Complexity in Analysis &amp; Model Training</strong> — Handling high-dimensional data increases the difficulty of interpretation, visualization, and model training.</li><li><strong>Computational Overhead</strong> — As the number of features grows, the computational resources and time required for processing scale exponentially.</li><li><strong>Risk of Overfitting</strong> — More features can lead to overly complex models that capture noise instead of meaningful patterns, reducing generalization to unseen data.</li><li><strong>Visualization Challenges</strong> — Data beyond three dimensions is difficult to comprehend and visualize effectively.</li><li><strong>Feature Redundancy</strong> — Highly correlated features add little value and can be removed without significant loss of information.</li></ol><h3>Applications of PCA</h3><p>PCA is widely used across various domains to simplify complex data while retaining essential information. Some of its key applications include:</p><ol><li><strong>Image Compression</strong> — Reduces the dimensionality of image data while preserving crucial details, optimizing storage and transmission efficiency.</li><li><strong>Bioinformatics</strong> — Analyzes high-dimensional gene expression data to uncover patterns and minimize noise, aiding in medical research.</li><li><strong>Face Recognition</strong> — Extracts essential facial features to enhance accuracy in recognition tasks, improving security and authentication systems.</li><li><strong>Recommendation Systems</strong> — Compresses user-item interaction data, enabling efficient personalized recommendations in platforms like e-commerce and streaming services.</li><li><strong>Finance</strong> — Identifies underlying trends and patterns in financial data, assisting in risk assessment, portfolio optimization, and market analysis.</li></ol><h3>Implementing PCA in Python</h3><p>Let’s implement PCA using Python and the popular library, scikit-learn. Ensure you have scikit-learn installed in your environment.</p><pre>import numpy as np<br>from sklearn.decomposition import PCA<br>from sklearn.preprocessing import StandardScaler<br><br># Sample dataset (3 observations, 3 features)<br>X = np.array([[1.0, 2.0, 3.0],<br>              [4.0, 5.0, 6.0],<br>              [7.0, 8.0, 9.0]])<br><br># Standardizing the dataset to have mean = 0 and variance = 1<br>scaler = StandardScaler()<br>X_scaled = scaler.fit_transform(X)<br><br># Initializing PCA to reduce dimensions to 2<br>pca_model = PCA(n_components=2)<br>pca_model.fit(X_scaled)<br><br># Transforming the data into the new feature space<br>X_reduced = pca_model.transform(X_scaled)<br><br># Extracting principal components and variance ratio<br>principal_components = pca_model.components_<br>variance_explained = pca_model.explained_variance_ratio_<br><br># Displaying results<br>print(&quot;Original Data:\n&quot;, X)<br>print(&quot;\nStandardized Data:\n&quot;, X_scaled)<br>print(&quot;\nPrincipal Components:\n&quot;, principal_components)<br>print(&quot;\nExplained Variance Ratio:\n&quot;, variance_explained)<br>print(&quot;\nTransformed Data (Reduced Dimensions):\n&quot;, X_reduced)</pre><h3>Closing Thoughts</h3><p>In a world overflowing with data, making sense of high-dimensional information is crucial. <strong>Principal Component Analysis (PCA)</strong> provides a powerful way to simplify complex datasets while preserving their most essential features. Whether it’s compressing images, analyzing financial trends, or improving machine learning models, PCA helps us uncover hidden patterns and make data-driven decisions more efficiently.</p><p>By reducing redundancy and computational complexity, PCA not only enhances model performance but also enables better visualization and interpretation. As we continue to generate vast amounts of data, mastering dimensionality reduction techniques like PCA will be essential for anyone working in <strong>data science, AI, and analytics</strong>. 🚀</p><p>Keep exploring, keep learning, and let PCA help you see the bigger picture — through fewer dimensions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba8eaf1fb5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preprocessing Pt. 2]]></title>
            <link>https://medium.com/@rare-major/data-preprocessing-pt-2-3fa2e555d9e8?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fa2e555d9e8</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 16:44:02 GMT</pubDate>
            <atom:updated>2025-02-23T16:44:02.804Z</atom:updated>
            <content:encoded><![CDATA[<h3>machineData Preprocessing Pt. 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjGV5syFHANeu3RVtAdDxA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@scw1217?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Suzanne D. Williams</a> on <a href="https://unsplash.com/photos/three-pupas-VMKBFR6r_jg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Taming the Data Beast: Imputation and Encoding for Machine Learning</h3><p>Data is the lifeblood of any machine learning model. But raw data is rarely perfect. It often comes riddled with missing values and non-numeric entries, which can significantly hinder our model’s performance. This blog post will explore two crucial data preprocessing techniques — imputation and encoding — that help us tame the data beast and prepare it for effective model training.</p><h3>Part 1: Imputation — Filling the Gaps</h3><p><strong>The Need for Imputation:</strong></p><p>Missing data is a common problem in real-world datasets. It can arise due to various reasons, such as data entry errors, incomplete surveys, or sensor malfunctions. Ignoring these missing values can lead to biased or inaccurate model predictions. Imputation offers a way to fill these gaps with plausible values, allowing us to utilize the complete dataset.</p><p><strong>How to Perform Imputation:</strong></p><p>Several imputation techniques exist, each with its own strengths and weaknesses. Some common methods include:</p><ul><li><strong>Mean/Median Imputation:</strong> Replacing missing values with the mean or median of the existing values in the same column. This is a simple approach but can distort the data distribution if the missing data is not missing completely at random (MCAR).</li><li><strong>Mode Imputation:</strong> For categorical features, replacing missing values with the most frequent category.</li><li><strong>K-Nearest Neighbors (KNN) Imputation:</strong> Imputing missing values based on the values of the k-nearest neighbors in the dataset. 1 This method can capture more complex relationships but is computationally more expensive.</li></ul><h3>Part 2: Encoding Independent Variables</h3><p><strong>The Need for Encoding:</strong></p><p>Many machine learning algorithms require numerical input. However, real-world datasets often contain categorical features (e.g., colors, city names). Encoding converts these categorical features into numerical representations, making them suitable for model training.</p><p><strong>Using OneHotEncoder in Scikit-learn:</strong></p><p>One-hot encoding is a popular technique for encoding nominal categorical features (where there is no inherent order). It creates a new binary column for each category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_FbYLs1cDrpAVbyF.png" /></figure><h3>Part 3: Encoding Dependent Variables</h3><p><strong>The Need for Encoding:</strong></p><p>Similar to independent variables, dependent variables (the target variable we want to predict) can also be categorical. We need to encode these as well, especially for classification tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*Kuaho237pMBOWrkV.png" /></figure><p><strong>Using LabelEncoder in Scikit-learn:</strong></p><p>LabelEncoder is used to encode categorical dependent variables into numerical labels.</p><h3>Code</h3><p>Our dataset snapshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWHjo0GHQwaxlztSrbcwdw.png" /></figure><pre># Importing necessary libraries<br>import numpy as np  # For numerical operations<br>import matplotlib.pyplot as plt  # (Not used here) Usually for data visualization<br>import pandas as pd  # For handling datasets<br><br># Loading the dataset<br>dataset = pd.read_csv(&#39;Data.csv&#39;)  # Reading the CSV file into a Pandas DataFrame<br><br># Separating independent variables (features) and dependent variable (target/output)<br>X = dataset.iloc[:, :-1].values  # Selecting all columns except the last one as input features<br>y = dataset.iloc[:, -1].values   # Selecting the last column as the target variable<br><br># Printing the extracted values<br>print(X)  # Displays feature matrix<br>print(y)  # Displays target variable<br><br># Handling missing data<br>from sklearn.impute import SimpleImputer  # Importing SimpleImputer for handling missing values<br><br># Creating an imputer object to replace missing values with the mean of the column<br>imputer = SimpleImputer(missing_values=np.nan, strategy=&#39;mean&#39;)<br><br># Fitting the imputer on columns 1 and 2 (indexing starts from 0) <br># This means we are only imputing numerical columns<br>imputer.fit(X[:, 1:3])<br><br># Replacing the missing values with the computed mean<br>X[:, 1:3] = imputer.transform(X[:, 1:3])  # Updates the feature matrix with imputed values<br><br># Displaying the updated feature matrix<br>print(X)<br><br># Encoding categorical data (converting text to numbers)<br>from sklearn.compose import ColumnTransformer  # Helps in applying transformations to specific columns<br>from sklearn.preprocessing import OneHotEncoder  # Used for One-Hot Encoding categorical variables<br><br># One-Hot Encoding the first column (index 0) if it contains categorical data<br># One-Hot Encoding converts categorical labels into multiple binary columns<br># `remainder=&#39;passthrough&#39;` ensures that other columns remain unchanged<br>if not isinstance(X, np.ndarray) or X.shape[1] == X.shape[1] - 1:  <br>  ct = ColumnTransformer(transformers=[(&#39;encoder&#39;, OneHotEncoder(), [0])], remainder=&#39;passthrough&#39;)<br>  X = np.array(ct.fit_transform(X))  # Converting transformed data into a NumPy array<br><br># Displaying the updated feature matrix after encoding<br>print(X)<br><br># Encoding the dependent variable (target column)<br>from sklearn.preprocessing import LabelEncoder  # LabelEncoder is used for encoding categorical labels<br><br>le = LabelEncoder()  # Creating a LabelEncoder object<br>y = le.fit_transform(y)  # Transforming categorical target labels into numerical format<br><br># Displaying the encoded target variable<br>print(y)</pre><h4><strong>Conclusion:</strong></h4><p>Imputation and encoding are essential steps in the data preprocessing pipeline. By handling missing values and converting categorical features into numerical representations, we prepare our data for machine learning models, leading to improved performance and more accurate predictions. Choosing the right imputation and encoding techniques depends on the specific characteristics of the dataset and the goals of the analysis. By understanding these techniques and utilizing tools like SimpleImputer, OneHotEncoder, and LabelEncoder, you can effectively tame the data beast and unlock the full potential of your machine learning models.</p><p>Ready to move beyond basic preprocessing? In the next installment, we’ll dive into the crucial steps of splitting data for training and testing, and explore the world of feature scaling — essential techniques for building robust and accurate machine learning models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fa2e555d9e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preprocessing Pt. 1]]></title>
            <link>https://medium.com/@rare-major/data-preprocessing-pt-1-36fc93250b53?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/36fc93250b53</guid>
            <category><![CDATA[machine-learning-python]]></category>
            <category><![CDATA[machine-learning-course]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 15:50:39 GMT</pubDate>
            <atom:updated>2025-02-16T16:01:29.830Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning 101: Simple, Brief, and Fun</h3><p>Machine Learning (ML) is everywhere — from recommending your next binge-watch on Netflix to detecting fraudulent transactions. But how does it actually work? If you’ve ever been curious about ML but found it overwhelming, you’re in the right place!</p><p>In this series, I’ll break down ML concepts in a simple, hands-on way, making it easier to grasp even if you’re just starting out. Whether you’re a developer, an aspiring data scientist, or simply curious, this guide will help you navigate the exciting world of ML. Let’s dive in! 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZOK1pYZNoNiZMxMHgNBqA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alvarordesign?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Alvaro Reyes</a> on <a href="https://unsplash.com/photos/vintage-adding-machine-MEldcHumbu8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Machine Learning Workflow</h3><p>Machine learning broadly consists of three steps:</p><h3>1. Data Preprocessing</h3><ul><li>Import the data</li><li>Clean the data</li><li>Split into training and test sets</li></ul><h3>2. Modeling</h3><ul><li>Build the model</li><li>Train the model</li><li>Make predictions</li></ul><h3>3. Evaluation</h3><ul><li>Calculate performance metrics</li><li>Analyze results</li></ul><h3>Data Preprocessing</h3><p>When working with a dataset, it’s advised not to use the entire dataset for training. Instead, split it into a <strong>training set</strong> and a <strong>test set</strong>. A commonly used ratio is <strong>80:20</strong>.</p><ul><li><strong>Feature:</strong> Features in a dataset are the columns used as inputs.</li><li><strong>Dependent Variable:</strong> This is the output the model needs to predict. The accuracy of the model depends on how well it predicts this value.</li></ul><h3>Feature Scaling</h3><p>Feature scaling ensures that all features contribute equally to the model. Why is it important?</p><ol><li><strong>Speeds up convergence</strong> — Optimization algorithms like gradient descent converge faster when features are on a similar scale.</li><li><strong>Prevents dominance</strong> — Distance-based algorithms (e.g., K-Nearest Neighbors, K-Means, Support Vector Machines) can be biased toward features with larger values.</li><li><strong>Enhances model performance</strong> — Helps maintain numerical stability and prevents exploding/vanishing gradients in deep learning.</li></ol><h3>Common Feature Scaling Techniques</h3><h4>1. Normalization (Min-Max Scaling)</h4><p>Scales features between a fixed range, usually <strong>[0,1]</strong> or <strong>[-1,1]</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yjfuQkCnnOYWvxKviNO6w.png" /></figure><h4>2. Standardization</h4><p>Rescales data to have a <strong>mean of 0</strong> and a <strong>standard deviation of 1</strong>. Unlike Min-Max Scaling, it does not squash values into a fixed range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*K3h6EVXndlxt18yUWdFXkg.png" /></figure><h4>3. Robust Scaling</h4><p>Uses the <strong>median</strong> and <strong>interquartile range</strong>, making it effective for handling outliers.</p><h3>Handling Missing Data</h3><p>One major issue in datasets is missing values, which can occur due to various reasons (e.g., data source issues, faulty sensors).</p><ul><li>If missing values <strong>affect less than 1%</strong> of the dataset, it’s often fine to drop those rows.</li><li>If a large number of values are missing, dropping them might reduce the dataset too much. In such cases, <strong>imputation techniques</strong> (e.g., replacing with mean, median, or mode) are preferable.</li></ul><p>We’ll explore these imputation techniques in detail in the upcoming articles!</p><p>Stay tuned! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36fc93250b53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lean Product Management — Dan Olsen]]></title>
            <link>https://medium.com/@rare-major/lean-product-management-dan-olsen-93c8741b2a4c?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/93c8741b2a4c</guid>
            <category><![CDATA[lean-product-proces]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[lean-startup]]></category>
            <category><![CDATA[lean-product-development]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 10:38:46 GMT</pubDate>
            <atom:updated>2020-03-28T10:38:46.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lean Product Management — Dan Olsen</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mVo5FwWdmPFdm_-F" /><figcaption>Photo by <a href="https://unsplash.com/@alex_andrews?utm_source=medium&amp;utm_medium=referral">Alexander Andrews</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Got a chance to through the Lean Product Playbook, by Dan Olsen. He’s one of the well-known faces when it comes to Product Management. He has been a Product Management consultant for famous tech giants like Box, Facebook, Microsoft and Medallia. He’s the founder of Lean Product and Lean UX Meetup at Silicon Valley. In his book he some of the great insights for product development and testing and how you can achieve an all-rounder product by following the Lean Product Process. So without further adieu, let’s begin with it.</p><h3>What Is Lean Startup all about?</h3><p>Too many startups begin with an idea for a product what they think people want. They then spend months and at times years perfecting their product without knowing their customer’s opinion on it. Well, this approach worked out for some but proved out to be a reason for failure for many.</p><p>In contrast, over the past years, the term Lean Startup began to get famous among the entrepreneur community. Lean Startup is a methodology which revolves around coming up with hypotheses, figuring out how to articulate those, then finding out the fastest way to test those hypotheses and learning from the outcomes. It further involves knowing the customer’s opinions and needs by interviewing then and an optimized way to invest while keeping their scope small so that they don’t invest significantly before realizing that they are headed in the wrong direction and there’s a need to change direction. It involves testing their products with a customer and learning from their finding to update their current version. The cycle continues until a Product-Market Fit is achieved.</p><h3>What Is Product-Market Fit?</h3><p>Product-Market Fit is a wonderful term because it captures the essence of what it means to build a great product. PMF was initially defined as being in a good market with a product that can satisfy that market. This can be rephrased as, building a product which is capable of creating significant customer value. <br>It can be best explained by a PMF pyramid which hierarchically divides it into five components, each layer of the pyramid. The product is the top two sections of the pyramid. And the market is the bottom two. Within these layers, each layer depends on the layer immediately beneath it. The Product Market Fit lies between the Product and Market sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*kGB1YZvXSTQ8aRihkwxDrg.png" /><figcaption>Fig 1: Product-Market Fit Pyramid</figcaption></figure><p><strong>Market</strong>: A market will involve a set of target customer whose problem we are trying to solve, and obviously from these customers, we’ll be driving their need which will act like problem statements for our product. The needs should be such, that they are not being served by the products available in the market. You probably don’t’ want to enter a market where the customers are extremely happy with how the existing solutions meet their needs.</p><p><strong>Product: </strong>Product is nothing but a solution/approach intended to solve the underserved needs of our target customers. A typical difference between a product and service is the same as that between hardware and software that is a product is a physical good while a service is intangible. In recent times, with the upcoming terms like software as a service(SaaS), this difference seems to blur out. <br>The UX is what brings a product’s functionality to life for the user. It involves the ease of using the product and how well the product is serving its purpose. The functionality that product provides is majorly based on the customer’s needs and together they form the product’s feature set. The essence of product strategy lies in determining how your product will be better than others in the market. The value proposition is the layer above the customer needs and fundamentally determines how will the needs addresses by your product match up with the customers.</p><p><strong>Product-Market Fit: </strong>In the context of the model above, PMF is the measure of how well your product(top 3 layers) satisfies the market(the bottom 2 layers). To achieve PMF, your product should meet underserved needs better than the competition.</p><h3>The Lean Product Process</h3><p>Once we have understood what a PMF model is, the next problem is to implement it. How do we achieve it? Following is the same PMF pyramid with one additional step to illustrate the complete process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*5UQNaaOANt06Oe4cE5E7yg.png" /><figcaption>Fig 2: The Lean Product Process</figcaption></figure><p>The Lean Product Process or LPP can be described in six steps as follow:</p><ol><li>Determine the target customers.</li><li>Identify underserved customers needs</li><li>Define your value propositions</li><li>Specify your minimum viable product (MVP) feature set</li><li>Create your MVP prototype</li><li>Test your MVP with customers</li></ol><p>The last three steps reference the important Lean concept of a minimum viable product (MVP). A minimum viable product is a product that contains a minimum amount of functionality that your target customer considers viable, that is, providing enough value. While building a product it is preferred to build an MVP to test your hypotheses with customers as less investment is required.</p><h3>Determine Your Target Customer</h3><p>The first and the foremost step to begin with Lean Product Process is to identify the target customer for your product (the bottom-most section of PMF pyramid)</p><h4>Fishing for Customers</h4><p>Many companies launch their product without explicitly discussing it with their target customers. This at times leads into a complete disaster. Matching a product with a customer is like fishing. The product is the bait that you put out there and the target customer is the fish that gets caught. That is why in LPP, having an MVP or prototype plays an important role as once you have the product to show to your customers you can gain clarity about the target market that you’re attracting. And of course, your bait can attract more that one type of customers.</p><h4>How to segment your target market?</h4><p>Dividing a broad market into specific subsets based on attributes is called market segmentation. Following are few of the common segmentations that can be done:</p><ul><li><strong>Demographic Segmentation: </strong>Demographics are quantifiable statistics of groups of people, such as age gender, marital status, income, and education level. If you’re targeting businesses, you’ll use firmographics instead; these are to organizations what demographics are to people, and include traits such as company size and industry.</li><li><strong>Psychographic Segmentation: </strong>Psychographics are the statistics that classify a group of people according to psychological variables such as attitude, opinions, values, and interest. These are often more useful than demographics for many products.</li><li><strong>Behavioural Segmentation: </strong>You can classify your customers based on their behaviour, i.e., whether a person takes a particular action or how often they do. If you were working on a stock trading app for active investors, you might define your target market as investors who place 10 or more stock trades per week.</li><li><strong>Needs-Based Segmentation: </strong>This proves out to be another useful metric to classify your customers. With this approach, you divide the market into customers segments that each have distinct needs. When demographics and psychographics fail, needs-based segmentation comes to rescue.</li></ul><h3>Identify Underserved Customer Needs</h3><p>Once we have identified our target customers, or at least have set hypotheses about them, we should focus on figuring out what needs they have that your product could satisfy. At times the customer’s needs seem to be quite fuzzy, therefore we’re required to clear them out.</p><p>One of the suggested ways to do so is to separate things into a problem space and solution space. The problem space will contain all the problems that our target customer is facing. Corresponding to each of the problems the solution space will contain a proposed solution by us. These kinds of needs/problems can be discussed by directly interviewing our customer. However, one thing to keep in mind is that the customers are generally not skilled at discussing the problem space; they are better at telling you what they dislike or like about a particular solution.<br>Now the items in the problem space become the user benefits, i.e., what user is expecting in a product and the solution space provides you with the features that your product is going to have.</p><h4>Prioritizing Needs: Importance vs. Satisfaction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*IoOSxxdQ0YqqK203-Bzxqw.jpeg" /><figcaption>Fig 3: Importance vs Satisfaction</figcaption></figure><p>The graph above essentially depicts the way you should be prioritizing the needs of the customer.</p><p>Let’s start from the bottom, the low importance and low satisfaction type and the low importance and high satisfaction type. Well clearly the importance of these features for the user is low, so we can simply assign the low priority to these features or problems. <br>The high importance task can’t be ignored unless you’re looking into the High Importance and High Satisfaction Market. It’s already a highly competitive market and this is where the 10x product concept comes into play. For example, Google search, a person wants to look up for things on the internet and these days searching is an important task and Google has exceptionally created a monopoly in the field. Hence a tough nut crack.</p><p>However, when you’re looking at the High Importance and Low Satisfaction features, you see a window of opportunity. That’s where you should focus the majority of your resources at and give it a high priority. For example, Uber tried to solve the problem of getting a taxi. The problem of finding a taxi was of high importance, however other alternatives of Uber were not performing well as the time for the taxi to get the person who booked it was uncertain. To curb this, Uber started its taxi service which provided a timely service to the customer.</p><h3>Define Your Value Proposition</h3><p>The next step in the LPP is defining the product value proposition. Once you have identified several customers needs that you could potentially address. Now you need to decide which ones your product will address. A good product is designed with the focus on the set of need that are important and that make sense to address together. Focus is critical while defining a new product as you don’t want to risk wasting useful resources.</p><p><strong>Strategy means saying “No”. </strong>Being an entrepreneur, it’s natural to feel the inability to address all the needs of the target customer. Hence, it becomes important to figure out the needs that you’re going to address and saying <em>No </em>to others. Saying <em>No </em>to which ones is the strategy. Saying <em>Yes </em>to everything at once seems impractical especially when you’re product is trying to solve multiple problems. Focus is the key.</p><blockquote>People think focus means saying yes to the thing you’ve got to focus on. But that’s not what it means at all. It means saying no to the hundred other good ideas that there are. You have to pick carefully. I’m actually as proud of the things we haven’t done as the things I have done. Innovation is saying no to 1,000 things.</blockquote><h4>Building Your Value Propositions</h4><p>Value propositions of a product can be simply divided into three categories:</p><ol><li><strong>Must Haves: </strong>These are the values which each of the product of the category should always have. For example, a door should always have a latch.</li><li><strong>Performance Benefits:</strong> These are the values which you add to the product to compete with your competitors. For example, a door having a double cylinder lock is considered to safer than a door having a single cylinder lock.</li><li><strong>Delighters:</strong> These are the values which the customers are not expecting and they come to them as a pleasant surprise. For example, a door with a viewer peephole is a delighter.</li></ol><h4>Kano Model</h4><p>Kano model depicts how the user’s satisfaction vary as the needs are met by various value propositions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*4qY4oi9QXgVeHGUQbIZADQ.jpeg" /><figcaption>Fig 4: Kano’s Model</figcaption></figure><p>There are three observations that we can make from the graph:</p><ul><li>Presence of must-have is expected by the people. Not having a must-have piss off the customer. For example, a car must have a seat belt.</li><li>Performance benefits vary linearly with the user’s satisfaction, the more the better. A company must always try to improve upon them. For example, a car having more mileage is preferred most of the times.</li><li>Absence of delighters isn’t much of an issue, however, if present, they increase the user’s satisfaction greatly. For example, when companies began to roll out cars with inbuilt GPS navigation systems it became a delighter to the customers who bought them. On the other hands, it didn’t affect other users much because they were still able to navigate with the help of their smartphones.</li></ul><p>As time passes, all companies will start rolling out cars with GPS navigation systems and having a good mileage will become a must-have. These three terms are circumstantial and the value propositions that come under will keep on changing from time to time.</p><blockquote>Yesterday’s delighters are today’s performance benefits and are tomorrow’s must-haves</blockquote><h3>Specify Your MVP Feature Set</h3><p>Minimum Viable Product or the MVP is the prototype of your product that contains the minimal feature set which is efficiently able to transmit the idea of your product. It’s based on the hypotheses regarding the market and is subjected to change with subsequent testings. It helps you in validating that you’re headed in the same direction. Various methods can be used to determine what feature sets to use for developing an MVP.</p><p>One of the common mistakes that people tend to do is that they only focus on the feature set and not on the reliability, usability and delightfulness of the service or their service/product. Working on these is equally important else we’re failing the whole purpose of the MVP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*GW8GEhkZi9VlpzryziJNpg.png" /><figcaption>Fig 5: How the MVP should be designed</figcaption></figure><p>The figure above depicts the difference between the incorrect way of interpreting the MVP and the correct interpretation.</p><h3>Create Your MVP Prototype</h3><p>Until now we have identified our target customers, figured out their needs and expectations, defined the value proposition for our product and have also finalised the feature set of our MVP. Next step is to create our MVP. To test the MVP with customers, we need a UX that we can show to our customers and get their feedback. Now the kind of UX depends on the way we want to test our products with our customers.</p><p>To start with, we can have 5 kinds of UX, which are as follows:</p><ul><li>Sketches: These are the most primitive way to start with the UX and are mostly used while you’re brainstorming the ideas. You’d want to draw out the architecture of your product before jumping onto the software. They faintly resemble with our product.</li><li>Wireframes: These are the low fidelity representation of our products. They are devoid of the visual design details such as colours, images, and fonts. They are mostly placeholders. Clickable wireframes provide more immersive user experience for the use. Also, they help in figuring out how a particular feature’s presence or absence affects the customer and how.</li><li>Mockups: These are the high fidelity representation of the product. They contain visual design details and mimic the flow of our product. These necessarily don’t contain any code in the background and simply lets the customer interact with the product by clicking elements on the screen.</li><li>Live Product: Test your live product with your customers is also considered fine. While using firebase for my android application, I stumbled upon various testing features that let you test your product. It provides various analytics based on demographics and behavioural patterns of the users. The insights are quite useful.</li></ul><h3>Test Your MVP with Customers</h3><p>To complete the Lean Product process the final step is to test your product with your customers. There are various techniques available out there and it’s up to you to decide which one to choose that can give you the insights and results that you are looking for. User tests allow you to verify your hypotheses and lets you know that if you’re headed in the right direction. Customer feedbacks are incredibly valuable as after all those are the ones whom we’re trying to serve and often provide insights that you didn’t think of.<br>Multiple iterations of testing have to carried out depending upon that feedback that you receive which ultimately leads to refining and improvement of your product.</p><h3>Summary</h3><p>To summarise everything, starting with an assumption that you believe that you know everything the customer wants and straight away pooling all your resources to build a product is not a good idea. Following a Lean Product Process will lead to better utilization of your resources and better results can be expected via customer feedback and interactions.</p><h3>References</h3><ol><li><em>The Lean Product Playbook: How to Innovate with Minimum Viable Products and Rapid Customer Feedback</em>, Book by Dan Olsen</li><li>The Lean Product Playbook with Author Dan Olsen, <a href="https://www.youtube.com/watch?v=m_c-B_MrxQU">https://www.youtube.com/watch?v=m_c-B_MrxQU</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93c8741b2a4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consistent Hashing]]></title>
            <link>https://medium.com/@rare-major/consistent-hashing-e25b0c1a9b9c?source=rss-6db8d35fea89------2</link>
            <guid isPermaLink="false">https://medium.com/p/e25b0c1a9b9c</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[consistent-hashing]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Vikas Tomar]]></dc:creator>
            <pubDate>Fri, 13 Mar 2020 04:20:12 GMT</pubDate>
            <atom:updated>2020-03-13T04:24:06.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7KLEXd2sYsQkh56d" /><figcaption>Photo by <a href="https://unsplash.com/@barkernotbaker?utm_source=medium&amp;utm_medium=referral">James Barker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>Previous Article:</em></strong><a href="https://medium.com/@rootonelab/system-design-101-getting-started-a65401634d3a"><strong><em> System Design Getting Started</em></strong></a></p><p>In the last article, I explained what are system design interviews all about, and how to go about them. <br>In this article, I’ll be writing about an important topic from the Distributed System perspective. I’ll try to keep them short and crisp.</p><h3>Consistent Hashing</h3><p>Distributed Hash Table (DHT) is one of the fundamental component used in distributed systems for mapping requests to various caches across the system. Hash tables, as we know, need a hash function to map keys to values. Suppose we want to design a distributed caching system. Given ’n’ cache servers, an intuitive hash function is ‘key%n. It’s a simple hash function and commonly used but has few drawbacks:</p><ul><li>It is not horizontally scalable. By horizontal scalability, I mean, adding a new server or cache host. It is very costly to scale the system horizontally if the hash function used is a simple one as all the mappings have to be changed since the number of cache servers has increased or decreased.</li><li>It may not be load balanced, especially for non-uniformly distributed data.</li></ul><p>In such a situation, Consistent Hashing is the way to go.</p><h4>What is Consistent Hashing?</h4><p>Consistent hashing is a useful technique to minimize the reorganization of the mapping when a new node is added or removed. Thereby making the caching system easier to scale up or scale down.</p><p>In consistent hashing when the hash table is resized i.e., a new cached node is added or removed, only<strong><em> k/n </em></strong>keys need to be remapped, where <em>k</em> is the total number of keys and <em>n</em> is the total number of servers. (Note that while using the simple hashing function, using the <em>mod </em>hash function, all the keys had to remapped.)</p><h4>How does it work?</h4><p>As a typical hash function, consistent hashing maps a key to an integer. Suppose the output of the hash function is in the range of [0, 256). Imagine that the integers in the range are placed on a ring such that the values are wrapped around.</p><p>Here’s how consistent hashing works:</p><ol><li>Given a list of cache servers, hash them to integers in the range.</li><li>To map a key to a server:</li></ol><ul><li>Hash it to a single integer.</li><li>Move clockwise on the ring until finding the first cache it encounters.</li><li>That cache is the one that contains the key.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLJ4p1AUuJASzOKFx9uzXQ.jpeg" /><figcaption>Consistent Hashing (Source: ably.io)</figcaption></figure><p>For example, in the diagram, we have 5 nodes. Now suppose we have to find a mapping for the value ‘Deyan’, we pass it through the hash function and get it’s hashed value somewhere between the values of Node 1 and Node 2. Since Node 2 will be encountered first upon moving in the clockwise direction, ‘Deyan’ will be mapped to Node 2.</p><p><strong>Node is Added: </strong>Now let us suppose we want to introduce a new Node 6 in the system. We place Node 6 between Srushtika and Freddie. Now instead of changing all the mappings of the system, only the keys lying between Node 6 and Node 2, i.e., Freddie will change. The mapping of other keys will remain unchanged and they will remain mapped to their old nodes.</p><p><strong>Node is Deleted: </strong>Let us now suppose that due to some fault the Node 1 has to be taken down. Therefore in order to keep the system working we simply map the keys mapped to Node 1 to the next node that we encounter on moving clockwise. That is we’ll map John to Node 2.</p><p>The above solves the issue of horizontal scalability, but what about the non-uniformity of data?</p><p>For load balancing, the real data is essentially randomly distributed and thus may not be uniform. It may make the keys on caches unbalanced, i.e., distributing an uneven number of keys to all cache servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*tbv0w1AbRGl3STRUdTtbig.png" /></figure><p>To handle this issue, we add “virtual replicas”, for caches. Instead of mapping each cache to a single point on the ring, we map it to several points on the ring, i.e., replicas. This way, each cache is associated with multiple portions of the ring.</p><p>That’s it for this article guys. In case you have any doubts, please post in the comment section. In case, you find any inconsistency in the article, feel free to point it out. <br>Have a nice day!</p><p><strong><em>Link to next article:</em></strong></p><h3>References</h3><ol><li><a href="https://github.com/immo2300576/SystemDesign/blob/master/consistenthashing.md">https://github.com/immo2300576/SystemDesign/blob/master/consistenthashing.md</a></li><li><a href="https://www.ably.io/blog/implementing-efficient-consistent-hashing/">https://www.ably.io/blog/implementing-efficient-consistent-hashing/</a></li><li>Karger, David, et al. “Consistent hashing and random trees: Distributed caching protocols for relieving hot spots on the world wide web.” <em>Proceedings of the twenty-ninth annual ACM symposium on Theory of computing</em>. 1997. <a href="https://www.akamai.com/es/es/multimedia/documents/technical-publication/consistent-hashing-and-random-trees-distributed-caching-protocols-for-relieving-hot-spots-on-the-world-wide-web-technical-publication.pdf">https://www.akamai.com/es/es/multimedia/documents/technical-publication/consistent-hashing-and-random-trees-distributed-caching-protocols-for-relieving-hot-spots-on-the-world-wide-web-technical-publication.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e25b0c1a9b9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>