<?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 Arun Dobriyal on Medium]]></title>
        <description><![CDATA[Stories by Arun Dobriyal on Medium]]></description>
        <link>https://medium.com/@arundobriyal_33904?source=rss-6baf11c0707e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0qBbtT4SUKIya_4TMLJQBQ@2x.jpeg</url>
            <title>Stories by Arun Dobriyal on Medium</title>
            <link>https://medium.com/@arundobriyal_33904?source=rss-6baf11c0707e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:45:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arundobriyal_33904/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to bring down your AI bill when building agents?]]></title>
            <link>https://medium.com/@arundobriyal_33904/how-to-bring-down-your-ai-bill-when-building-agents-0e5e5790d316?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e5e5790d316</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[prompt-caching]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 18:15:14 GMT</pubDate>
            <atom:updated>2026-09-15T18:15:14.781Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A practical guide to Agentic builders on what cost savings actually work for production agents.</em></h4><p>Every team building Agents has the same meeting eventually. The bill crosses a threshold that makes someone uncomfortable, a spreadsheet appears, and the first suggestion is always the same one: <em>can we just use a cheaper model?</em> Sometimes yes. More often it’s the fourth or fifth best lever available, and the four ahead of it don’t cost you a point of accuracy.</p><p>One note, before we deep dive. Almost every production agent I’ve looked at is input-token dominated. A triage agent with a 3,000-token system prompt, six tool schemas, and a retrieved context block emits a 40-token classification. That’s 100:1, and it means the optimizations you usually read about — shorter responses, tighter output formats — are insignificant. Go where the tokens are.</p><h3>Before you do anyting…</h3><p>If your provider dashboard shows one number for the whole org, you are guessing. Tag every request — most providers support metadata or custom headers — with feature, tenant, agent_name, environment. Then build one dashboard broken down those four ways.</p><p>And change the headline metric. Cost-per-token is a vanity number that goes down when quality goes down. Cost per resolved ticket is the one that tells you whether an optimization was a win or a quiet regression. A team I worked with cut token spend 30% and found out two months later that deflection had dropped enough to add headcount to the support queue. Net negative, invisible on the token dashboard.</p><p>Let’s now get into various way that you can bring down your AI bill.</p><h3>Part 1 — Model choice</h3><h3>1. Downgrade, but only with an eval in hand</h3><p>Haiku instead of Sonnet, mini instead of full. Works more often than anyone would admit, especially for classification, extraction, and routing — tasks with a narrow output space.</p><p>You <strong>don’t get to downgrade without an eval </strong>that proves the tradeoff for cost vs accuracy. The eval is also what lets you say if bumping down is fine e.g. let’s say you bump down from opus to Sonnet, and the cost goes half, but the accuracy drops only 20 basis points, most likely this is a tradeoff worth taking, and you can take the data with your business / product and make that decision with numbers.</p><h3>2. Sometimes you upgrade to a higher reasoning model — and it gets cheaper</h3><p>It’s counterintuitive, isn’t it!</p><p>Newer model generations are frequently cheaper on input tokens than the generation they replace, while being better at reasoning. GPT-5 versus GPT-4 is the clearest example, but it’s a general pattern — providers have pushed input pricing down hard lately.</p><p>Now put that next to the 100:1(input vs output) ratio . If your agent does intake or classification behind a heavy system prompt, almost all of your bill is input tokens, and a model that’s cheaper on input and pricier on output is a straight cost reduction with better reasoning thrown in. The condition is explicit: this works when input ≫ output.</p><h3>3. Set reasoning budgets explicitly</h3><p>If you are agentic frameworks to build your agents, almost all of them have some variation of max_tokenswhich prevents an agent going rogue and rack up a high bill. Do configure this as a guardrail.</p><h3>4. Use open-weight embedding models unless you can justify otherwise</h3><p>Open-weight embedding models are genuinely competitive especially for embeddings related usecases. No need to call OpenAI and have it generate embeddings when SBERT or other MTEB embeddings are free to use and comparable to proprietary ones.</p><p>While you’re there, check dimensionality: many models support truncated dimensions(e.g. <a href="https://huggingface.co/blog/matryoshka">https://huggingface.co/blog/matryoshka</a>) with minimal recall loss, which cuts vector store cost too.</p><h3>Part 2 — Input tokens, where the money actually is</h3><h3>5. Prompt caching is a default, not an optimization</h3><p>Cache reads bill at roughly 10% of base input rate; writes carry about a 25% premium. Any conversation past 2 turns is a net win.</p><p>There’s no configuration where you should run a multi-turn agent without caching headers. If you aren’t today, that’s the highest-ROI hour available to you. Most agentic platforms provide a way to turn it ON, go check out how it’s done for yours.</p><h3>6. Order your system prompt so the prompt cache is leveraged</h3><p>Caching works by exact prefix match. Any change anywhere in the prefix invalidates everything after it — a timestamp, a user’s name, two capital letters.</p><p>So this is a bug:</p><pre># ❌ Dynamic content at the top. Cache hit rate: approximately zero.<br>system = f&quot;&quot;&quot;Today is {datetime.now().isoformat()}.<br>User: {user.name}, tier {user.tier}, {user.open_ticket_count} open tickets.</pre><pre># Prefix is static, best for Prompt caches<br>You are a support triage agent for Acme.<br>[... 2,400 tokens of policy, taxonomy, few-shot examples ...]<br>&quot;&quot;&quot;</pre><p>Every request has a different first line, so every request is a full cold ingestion of all 2,400 tokens. You pay write premiums forever and never read. Push everything stable to the top, set the breakpoint after it, inject the volatile bits below:</p><pre># ✅ Stable prefix, breakpoint, then dynamic content.<br>messages = [<br>    {<br>        &quot;role&quot;: &quot;system&quot;,<br>        &quot;content&quot;: [<br>            {<br>                &quot;type&quot;: &quot;text&quot;,<br>                &quot;text&quot;: STATIC_SYSTEM_PROMPT,   # 2,400 tokens, byte-identical every call<br>                &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;},<br>            },<br>        ],<br>    },<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: [<br>            {<br>                &quot;type&quot;: &quot;text&quot;,<br>                &quot;text&quot;: f&quot;&lt;context&gt;Today is {today}. User tier: {user.tier}.&lt;/context&gt;\n\n{user_message}&quot;,<br>            },<br>        ],<br>    }<br>]</pre><p>Same information. One bills you 10% on the bulk of it, the other 125%.</p><p>Related trick worth stealing from the Claude Code team: when state changes mid-session, inject it as a tagged block inside a user message rather than editing the system prompt. Editing detonates the cache. Appending doesn’t.</p><h3>7. Trim extraneous tool definitions from your context</h3><p>Your tool definitions are part of the request — all of them, on every step of every ReAct loop. Thirty tools with thoughtfully-written descriptions is 4,000–6,000 input tokens attached to calls that will use exactly one.</p><pre># One agent, every tool the platform team ever wrote.<br>agent = Agent(model, tools=ALL_TOOLS)                              # 34 tools, ~5.8k tokens of schema</pre><pre># The same agent, scoped to what this workflow actually needs.<br>agent = Agent(model, tools=[read_ticket, search_kb, escalate])    # ~600 tokens</pre><p>In a ten-step loop that’s 52,000 tokens versus 6,000, on one user turn. Scope tool sets per agent. If you genuinely have a large surface, do progressive disclosure (e.g. search_tool, list_tool) so the cacheable prefix stays identical across users.</p><h3>8. Keep Tool result tight</h3><pre># ❌ Returns ~6,000 tokens. The agent needed four fields.<br>def get_order(order_id: str) -&gt; str:<br>    return json.dumps(api.get_order(order_id))<br>    # ... 40 shipping scan events, per-line-item tax breakdown,<br>    #     internal audit trail, three nested address objects,<br>    #     a `_links` block nobody has ever read</pre><pre># ✅ Returns ~80 tokens.<br>def get_order(order_id: str) -&gt; str:<br>    o = api.get_order(order_id)<br>    return json.dumps({<br>        &quot;status&quot;: o[&quot;status&quot;],<br>        &quot;placed_at&quot;: o[&quot;created_at&quot;],<br>        &quot;total&quot;: o[&quot;totals&quot;][&quot;grand_total&quot;],<br>        &quot;items&quot;: [{&quot;sku&quot;: i[&quot;sku&quot;], &quot;qty&quot;: i[&quot;qty&quot;]} for i in o[&quot;line_items&quot;]],<br>    })</pre><p>Use Pydantic models as output type schema, and keep the output tight.</p><h3>9. For RAG agents, Retrieve wide, rerank, before sending to LLMs</h3><p>Retrieve generously, run a cheap reranker over the candidates, there are bunch of openweight rerankers out there to be used (select the ones you like once you do test based on your domain data), pass only what survives. The reranker costs a fraction of what you save by not stuffing seven irrelevant chunks into every prompt. Tune chunk size too — oversized chunks are a quiet multiplier on the same problem. Chunking strategies, saving that for another blog.</p><h3>10. Isolate context with subagents</h3><p>When a subtask needs to chew through a lot of material — read forty files, scan a log, summarize a long document — don’t do it in the main agent’s context. Spawn a subagent with its own scoped prompt and fresh transcript, let it do the messy work, return only the conclusion. Added benefits of this subagent separation is that you can use a cheaper LLM model for your subagent, and you can run subagents in parallel.</p><p>The main context stays slim and its cache stays intact.</p><h3>11. Downscale images before you send them</h3><p>A full-resolution screenshot can be 1,500–2,000 tokens, and most of the time the agent just needs to read some text or identify a layout element. Downscale before encoding, crop to the region when you know it. And for PDFs, extract text rather than rendering pages as images unless the visual layout itself carries meaning — skipping the image render is often a 10x reduction in tokens for that call. Use Heirarchical RAG to improve accuracy vs plain chunking for agent to be effective with tokens. It should improve Token/case processed metrics.</p><h3>Part 3 — How you’re billed</h3><h3>12. Provisioned throughput → pay-as-you-go, by default</h3><p>Provisioned capacity makes sense for sustained, predictable, high-volume load. Almost no agent workload looks like that. Real agent traffic follows business hours, deploys, and whatever campaign marketing just launched. You provision for peak and pay for peak around the clock, including the sixteen hours a day when your internal tool has four users on it.</p><p>Make pay-as-you-go the default for every agent you build.</p><h3>13. Use the batch tier if your workload is batch</h3><p>Both major providers offer batch at roughly half price with a turnaround window measured in hours. Nightly classification, backfills, bulk enrichment, eval runs, document processing — if nobody is waiting on the response, you’re paying double for latency you don’t need.</p><h3>Part 4 — Making the model waste fewer tokens</h3><h3>14. Structured outputs. Still. Please.</h3><p>Generally available for years and I still find agents parsing free-form text with regex in 2026.</p><p>Without a schema the model spends tokens narrating its way to a format — preamble, explanation, markdown fencing, a closing summary nobody reads. With one, it emits the object. You also stop burning retries on malformed JSON, which is its own line item. <strong>No excuse for not doing this in 2026.</strong></p><h3>15. Optimize the prompt itself with a framework</h3><p>DSPy and similar frameworks help you build an effective prompt e.g. by instruction phrasing, few-shot selection, workflow structure — and consistently beat a human iterating by feel. I’ve done this in bunch of agents and the wins were real.</p><p>The hard requirement is that this only works with a <strong>solid eval</strong>. It does sort of AB test with the ground truth and give the system prompt that does better than what most of us can type ourselves. The optimizer needs a signal to climb; without one you’ll happily optimize toward something you didn’t want.</p><h3>Part 5 — Blast radius</h3><p>The sections above are about reducing steady-state spend. This one is about the incidents that make a Friday afternoon very bad — the agent that goes sideways overnight and nobody notices until the bill lands.</p><h3>16. Rate limits with alerting, at every window</h3><p>Daily, weekly, and monthly caps on invocations, per agent and per tenant, with alerts. Use observabilty tools and setup alerts.</p><p>We had an incident earlier this year where a limit was breached and the alert was routed to a channel nobody was watching. The detection lag was the expensive part, not the burn rate. Set the limits, route the alerts somewhere a human will see them, and test that the alert actually fires.</p><h3>17. Budget your retries and cancel on disconnect</h3><p>Naive exponential backoff on a 40,000-token prompt doubles the bill on a bad afternoon, and retries after a timeout can bill you for the original generation anyway. Do smart retries based on the http status code that you receive.</p><h3>The one thing not to do: model routing in custom code</h3><p>At some point someone will propose a routing layer — start on the big model, detect when things get simple, swap down mid-flight. It sounds thrifty. It is, in almost every case, a bad idea, and I’ve written the long version: <a href="https://medium.com/@arundobriyal_33904/stop-swapping-models-mid-conversation-97f54605774d">Stop Swapping Models Mid-Conversation!</a> Check out the article on the whys.</p><h3>Part 6 — Make it stick</h3><h3>18. Turn this list into a skill, then into a gate</h3><p>Write all of what’s in this article as an AI cost savings skill for your org — the checks, the thresholds, the code patterns, the questions to ask.</p><p>Then fork the same skill into a production-readiness gate: same content, different mode. Instead of advising during development, it audits before shipping. Is caching on? Is the prefix stable? Are tool schemas scoped? Are there per-session budgets and a circuit breaker? Is billing mode PAYG, and if not, where’s the utilization number in the ADR? Is there an eval, and does the model choice reference it?</p><p>That becomes a required check on the path to production.</p><h3>The bottom line</h3><p>Agentic building is much more than just knowing ReAct, Tool calling, MCP/A2A, Sub-agents and knowing agent building patterns.</p><p>Cost plays a big role. Don’t ignore it, be smart about it. It stands to save your org quite a bit if you make it into a discipline.</p><h3>References</h3><ul><li>Anthropic engineering — <em>Lessons from building Claude Code: prompt caching is everything.</em> <a href="https://claude.com/blog/lessons-from-building-claude-code-prompt-caching-is-everything">https://claude.com/blog/lessons-from-building-claude-code-prompt-caching-is-everything</a></li><li>Anthropic API docs — <em>Prompt caching.</em> <a href="https://docs.claude.com/en/docs/build-with-claude/prompt-caching">https://docs.claude.com/en/docs/build-with-claude/prompt-caching</a></li><li>Anthropic API docs — <em>Batch processing.</em> <a href="https://docs.claude.com/en/docs/build-with-claude/batch-processing">https://docs.claude.com/en/docs/build-with-claude/batch-processing</a></li><li>Anthropic Agent SDK — <em>Subagents.</em> <a href="https://docs.claude.com/en/api/agent-sdk/subagents">https://docs.claude.com/en/api/agent-sdk/subagents</a></li><li>Arun Dobriyal — <em>Stop Swapping Models Mid-Conversation!</em> <a href="https://medium.com/@arundobriyal_33904/stop-swapping-models-mid-conversation-97f54605774d">https://medium.com/@arundobriyal_33904/stop-swapping-models-mid-conversation-97f54605774d</a></li><li>DSPy — <em>Optimizers.</em> <a href="https://dspy.ai/">https://dspy.ai/</a></li><li>OpenAI — <em>Structured Outputs.</em> <a href="https://platform.openai.com/docs/guides/structured-outputs">https://platform.openai.com/docs/guides/structured-outputs</a></li><li>OpenAI — <em>Batch API.</em> <a href="https://platform.openai.com/docs/guides/batch">https://platform.openai.com/docs/guides/batch</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e5e5790d316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Swapping Models Mid-Conversation!]]></title>
            <link>https://medium.com/@arundobriyal_33904/stop-swapping-models-mid-conversation-97f54605774d?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/97f54605774d</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 15:17:05 GMT</pubDate>
            <atom:updated>2026-09-07T18:24:46.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why “just downgrade to Sonnet halfway” is one of the worst routing ideas — and the narrow set of times it actually works.</h3><p><em>Tldr: Don’t switch out models for stateful conversations (which are most conversations in Agents)</em></p><p>Model routing is everywhere. Every team building on top of LLM APIs eventually looks at their bill, notices that most turns in a conversation are “easy,” and reaches the same conclusion: <em>why don’t we just start the session on a big model and bump it down to a smaller one once things get simple?</em></p><p>A friend of mine pitched this exact idea last week. It sounds thrifty. It is, in almost every case, a bad idea — and the reasons are how LLM inference, prompt caching, and agentic tool loops actually work.</p><p>You may have already hit this while using web based or desktop AI assistants like Claude e.g. if you try switching the model in the dropdown in an intense conversation, Claude will often push back and tell you that switching mid-conversation may degrade the response. Check the pic below. It is Anthropic surfacing the exact problem this post is about: the cache and the context you have built are pinned to the model you started with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*sjrzHv4XrYVSRbNxSNq0Xw.png" /></figure><p>I’ll cover what breaks, show it in code with a Pydantic AI ReAct agent, go one layer deeper into how inference frameworks make this work, and name the specific conditions where switching is fine.</p><p>Following are 4reasons why you should be very careful with switching models and in fact avoid it if you can.</p><h3>1. Prompt caches are per-model. Switching detonates them.</h3><p>The single biggest hidden cost in a long conversation — especially an agentic one with tools — is <em>input tokens</em>. Every turn, the entire prior history is re-sent to the provider. Without caching, you pay full input rates on the whole growing transcript, every single call.</p><p>Prompt caching is what keeps this affordable. Anthropic’s engineering post on Claude Code puts it bluntly:</p><blockquote><em>“Any change anywhere in the prefix invalidates everything after it.”</em></blockquote><p>The cache works by prefix matching. The API stores the KV state of everything from the start of the request up to a cache_control breakpoint and reuses it on the next call if the prefix is byte-for-byte identical. Cache reads are billed at roughly 10% of the base input rate; cache writes at about 125%. Any conversation past two turns is a net win — <em>if</em> the prefix stays stable.</p><p>Caches are keyed to a specific model. Anthropic’s post on lessons from building Claude Code states this directly. The KV representations are architecture-specific and, in most cases, checkpoint-specific. Sonnet’s cache is not Haiku’s cache. Opus’s cache is not Sonnet’s cache.</p><p>So when you “downgrade” mid-conversation, the new model has to:</p><ol><li>Ingest the entire prior transcript as plain, uncached input tokens.</li><li>Pay full input pricing on all of it (plus the ~25% cache-write premium as it warms a fresh cache).</li><li>Rebuild a fresh KV cache from scratch under the new model’s key.</li></ol><p>The turn where you switch is often <em>more expensive</em> than if you had just stayed on the bigger model — a cached Opus turn on a 100K-token transcript can be cheaper than an uncached Haiku turn on the same transcript. The math inverts exactly when you didn’t want it to.</p><p>And it’s not a one-turn hit. Until the new prefix re-warms and stabilizes, every following turn pays elevated input costs. Anthropic’s cache also has a ~5-minute idle TTL on the standard tier, so an interrupted session compounds the problem.</p><h3>2. Why switching model means you need to switch out the System prompt and other configurations</h3><p>Most serious routing setups don’t just swap the model name — they swap the whole configuration. And the reason is simple: Haiku needs <strong>more explicit, shorter instructions </strong>— it doesn’t infer as well from sparse prompts. Opus can handle complex multi-part system prompts. So a good router often ships different system prompt variants per model tier.</p><p>Different models often get slightly different system prompts, different tool descriptions tuned to their behavior, sometimes different tool sets entirely.</p><p>That’s another cache invalidation stacked on top of the model swap. One detailed Claude Code caching write-up shows it vividly: “changing capitalization of two letters broke the entire cache. 2,727 tokens of computation, thrown away because of two capital letters.” Adding or removing an MCP tool mid-session, or nudging a single word in the system prompt, nukes the whole downstream cache.</p><p>This is why Anthropic’s Claude Code team goes to significant lengths to avoid it. They inject state changes as &lt;system-reminder&gt; tags inside user messages rather than editing the system prompt. They use plan-mode toggles instead of adding or removing tools mid-session. They defer-load tool schemas so the cacheable prefix stays identical across users. A routing layer that quietly rewrites the system prompt or tool list to fit the new model is compounding an already expensive mistake.</p><h3>3. It impacts your Eval</h3><p>If you change the model in the middle, your system can significantly degrade without you having done any Benchmarking against it.</p><p>Think of a scenario, where you built a classification agent hitting 90% of accuracy with Opus 4.7, now your model routing layer decides to switch it out in the middle, but how does it impact the effectiveness of your agent, what’s the new blended Accuracy of your agent? You won’t have answers to simpler questions like this with such a setup.</p><h3>4. Tokenizers, context limits, and rate limits shift too.</h3><p>Some providers use different tokenizers across model families; even within one provider, per-model context windows and rate limits differ. A conversation that fits comfortably in one model’s window can truncate on another. A routing layer unaware of these ceilings turns mid-conversation swaps into a source of hard-to-reproduce failures.</p><h3>Let me explain with a code example</h3><p>Agentic frameworks make this bad too. A single “turn” from the user’s perspective is <em>many</em> model calls under the hood — one per tool step in the ReAct loop. Each call re-sends the full growing history: user turn, assistant thought, tool call, tool result, and so on. Prompt caching was designed for exactly this shape. A mid-conversation model swap ruins it the most.</p><p>Here’s the anti-pattern. Start on a big model, warm the cache over several tool-using turns, then “downgrade” on what looks like a simple follow-up:</p><pre> from pydantic_ai import Agent, Tool<br><br>def read_file(path: str) -&gt; str:<br>    ...<br><br>def grep(pattern: str, path: str) -&gt; list[str]:<br>    ...<br><br>def run_tests(target: str) -&gt; str:<br>    ...<br><br>TOOLS = [Tool(read_file), Tool(grep), Tool(run_tests)]<br>SYSTEM = &quot;You are a senior engineer working in a large codebase. Use the tools.&quot;<br><br># ---- Phase A: real work on the big model ----<br>big = Agent(&quot;anthropic:claude-opus-4-7&quot;, system_prompt=SYSTEM, tools=TOOLS)<br><br>result = big.run_sync(&quot;Investigate the failing auth tests and propose a fix.&quot;)<br>history = result.all_messages()<br><br># Several follow-ups. Under the hood this is dozens of tool-call round trips.<br># Each round trip re-sends everything so far. Cache is warm on Opus.<br>for followup in followups:<br>    result = big.run_sync(followup, message_history=history)<br>    history = result.all_messages()<br><br># ---- Phase B: &quot;cheap&quot; follow-up on the small model ----<br>small = Agent(&quot;anthropic:claude-haiku-4-5&quot;, system_prompt=SYSTEM, tools=TOOLS)<br><br># This single call pays the cold-start tax on the ENTIRE prior transcript:<br>#   - every user message<br>#   - every assistant thought<br>#   - every tool call and every tool result<br># All of it re-tokenized and re-processed by Haiku as uncached input,<br># then written into a fresh Haiku cache at the ~25% write premium.<br># And Haiku is now trying to continue a reasoning trace written by Opus.<br>result = small.run_sync(&quot;Now just apply the fix.&quot;, message_history=history)</pre><p>Two things happen in that last block, and neither shows up in a log at first glance.</p><p>Economic inversion. The transcript at this point might be 60–120K tokens — tool outputs are heavy. Reading those tokens from Opus’s warm cache is cheap. Ingesting them cold into Haiku is not. Depending on the ratio, the “cheap” model call can cost more than the “expensive” one would have.</p><p>Behavioral drift inside the ReAct loop. The next tool call Haiku makes has to conform to the cadence and format Opus established earlier in the transcript. If Haiku deviates — calls a tool with slightly different argument phrasing, produces a differently structured scratchpad, misreads an earlier assistant assumption — the loop can spiral: bad tool call, confused tool result, another bad tool call. The failure looks like “the small model is dumb,” but it is really “the small model is doing cold-read comprehension on someone else’s transcript.”</p><p>The same shape shows up in conversational products — ChatGPT, Claude.ai, opencode, Cursor — where the UI lets you change the model mid-thread. Looks like a harmless preference toggle. Under the hood it is the same cache detonation.</p><h3>When mid-conversation switching is actually fine</h3><p>The constraint is not “never route.” It is “don’t swap the model inside a single stateful conversation.” Routing at the right boundary is entirely legitimate:</p><ul><li><strong>Between conversations, not within them</strong>. Route at session start based on user intent, task complexity, or prior signals. Once the conversation begins, stick with the chosen model. The cache warms, quality stays consistent, and pricing behaves the way you modeled it.</li><li><strong>Sub-agents with their own scoped context.</strong> Spawning a <em>separate</em> agent — its own system prompt, its own fresh transcript, its own cache namespace — to handle a well-defined subtask on a cheaper model is fine. The parent conversation keeps its cache intact and consumes only the sub-agent’s result. This is exactly how Claude Code’s sub-agents and the Anthropic Agent SDK’s subagents primitive are designed to work.</li><li><strong>Explicit compaction and handoff</strong>. If you genuinely need a different model mid-session, do it deliberately: summarize the prior state into a compact handoff prompt, start a <em>new</em> conversation on the new model with that summary as the seed, and treat the switch as a hard boundary. You trade cache reuse for a clean start under the new model’s dialect — defensible, not silent.</li><li><strong>Fallback on hard failure</strong>. If the primary model is down or rate-limited, failing over is a reliability call, not a cost optimization. Accept the cache miss. Just don’t keep flapping — pin the fallback for the rest of the session.</li><li><strong>Short conversations</strong>. Two or three turns with no tools: cache economics barely apply and dialect drift barely matters. Route however you like.</li><li><strong>When the cache is already cold and likely Invalidated on the servers</strong>. This one gets skipped in most discussions. Anthropic’s standard tier expires the cache after roughly 5 minutes of inactivity, and each cache hit resets the timer. If you walked away from a conversation — lunch, a meeting, overnight — the cache under your original model is already gone. Coming back and switching to a different model at that point costs nothing extra in cache terms. The next turn was going to be a full cold ingestion regardless. This is actually the free window to reconsider your model choice. The dialect-drift argument still applies to the transcript content, but at least you’re not paying to re-warm a cache under a new key.</li></ul><h3>How LLM providers do Prefix / Prompt / KV caching</h3><p>The reason “same model + same prefix” is so much cheaper than “different model + same prefix” is not accounting — it is the shape of the inference stack. Modern open-source serving frameworks make this concrete, and the major providers are almost certainly running something analogous.</p><p>SGLang implements RadixAttention: it stores the KV cache for every processed prefix in a radix tree in GPU memory, and any new request whose tokens share a prefix with something in the tree gets those KV entries reused instead of recomputed. A shared system prompt across thousands of concurrent users gets computed once per model replica and read many times.</p><p>vLLM does prefix caching on top of PagedAttention, where KV blocks are managed like OS pages and shared across requests with the same prefix hash.</p><p>TensorRT-LLM and llama.cpp both expose prefix / KV reuse as first-class features.</p><p>Once you have per-prefix KV blocks pinned to specific GPUs, you also want incoming requests to land on the GPU that already has the relevant KV cache resident. That is what many inference platforms call KV-cache-aware routing (sometimes “prefix-aware routing” or “session affinity routing”): the load balancer hashes the request’s prefix, looks up which replica most recently served that prefix, and preferentially routes the request there. Fireworks, Together, Deepinfra, Baseten, and community projects like LMCache have all publicly described variants of this. It is what makes the cache hit rate on paper actually show up in production.</p><p>Anthropic and OpenAI have not said which framework backs their APIs — heavily modified vLLM, an internal descendant of TensorRT-LLM, SGLang, or something bespoke. But the observable behavior — dramatic cost and latency savings from stable prefixes, per-model cache keying, sensitivity to even single-byte prefix changes, ~5 minute idle expiry — matches a radix-tree / paged-KV serving stack with prefix-aware routing exactly. Change the model, and you are asking a different replica pool, with different weights, to rebuild the whole thing from scratch.</p><h3>The bottom line</h3><p>Long conversations have a working cache. That cache is model-specific, prefix-specific, and replica-specific. Mid-conversation model swaps kill it — and in agentic tool loops, where one user turn is dozens of model calls, the hit compounds with every step.</p><p>Route by all means. Do it before the session starts, or inside a separately-scoped sub-agent where a fresh cache is expected anyway. Don’t do it silently in the middle of a running conversation, where you pay for the cold start twice: once on the bill, and once in output quality.</p><h3>References</h3><ul><li>Anthropic engineering — <em>Lessons from building Claude Code: prompt caching is everything.</em> <a href="https://claude.com/blog/lessons-from-building-claude-code-prompt-caching-is-everything">https://claude.com/blog/lessons-from-building-claude-code-prompt-caching-is-everything</a></li><li>Anthropic API docs — <em>Prompt caching.</em> <a href="https://docs.claude.com/en/docs/build-with-claude/prompt-caching">https://docs.claude.com/en/docs/build-with-claude/prompt-caching</a></li><li>Anthropic API docs — <em>Models overview</em> (per-model context windows and pricing). <a href="https://docs.claude.com/en/docs/about-claude/models/overview">https://docs.claude.com/en/docs/about-claude/models/overview</a></li><li>Anthropic Agent SDK — <em>Subagents.</em> <a href="https://docs.claude.com/en/api/agent-sdk/subagents">https://docs.claude.com/en/api/agent-sdk/subagents</a></li><li>Google AI Developers Forum — <em>Changing models mid-chat destroys your project.</em> <a href="https://discuss.ai.google.dev/t/changing-models-mid-chat-destroys-your-project/172090">https://discuss.ai.google.dev/t/changing-models-mid-chat-destroys-your-project/172090</a></li><li>Claude Code Camp — <em>How prompt caching actually works in Claude Code.</em> <a href="https://www.claudecodecamp.com/p/how-prompt-caching-actually-works-in-claude-code">https://www.claudecodecamp.com/p/how-prompt-caching-actually-works-in-claude-code</a></li><li>MindStudio — <em>Why not switch models mid-conversation in AI coding agents.</em> <a href="https://www.mindstudio.ai/blog/why-not-switch-models-mid-conversation-ai-coding-agents">https://www.mindstudio.ai/blog/why-not-switch-models-mid-conversation-ai-coding-agents</a></li><li>Pydantic AI docs — <em>Agents.</em> <a href="https://ai.pydantic.dev/agents/">https://ai.pydantic.dev/agents/</a></li><li>SGLang — <em>RadixAttention and structured generation.</em> <a href="https://docs.sglang.ai/">https://docs.sglang.ai/</a></li><li>vLLM — <em>Automatic prefix caching.</em> <a href="https://docs.vllm.ai/en/latest/features/automatic_prefix_caching.html">https://docs.vllm.ai/en/latest/features/automatic_prefix_caching.html</a></li><li>NVIDIA TensorRT-LLM — <em>KV cache reuse.</em> <a href="https://nvidia.github.io/TensorRT-LLM/advanced/kv-cache-reuse.html">https://nvidia.github.io/TensorRT-LLM/advanced/kv-cache-reuse.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97f54605774d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contrastive Learning, InfoNCE, and Why Two-Tower Systems Train Their Own Embeddings]]></title>
            <link>https://medium.com/@arundobriyal_33904/contrastive-learning-infonce-and-why-two-tower-systems-train-their-own-embeddings-3c16d38257a0?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c16d38257a0</guid>
            <category><![CDATA[contrastive-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 12:44:37 GMT</pubDate>
            <atom:updated>2026-08-29T12:44:37.382Z</atom:updated>
            <content:encoded><![CDATA[<p>Every search or recommendation system hits the same wall eventually. You’ve got a query, ten million documents, and you need the top twenty back in under fifty milliseconds.</p><p>Obvious first move: grab a pretrained encoder — BERT, SBERT, whatever’s on top of MTEB this month — embed everything, dump it in a vector DB, done. Sometimes that works. Usually it half-works, which is worse, coz you burn three weeks tuning the vector store before figuring out the embeddings were never right for your domain.</p><p>In this post, I cover: why cross-encoders can’t do retrieval, why two-tower exists, why it trains its own embeddings instead of borrowing open-weight ones, and what InfoNCE actually is once you strip the jargon away.</p><h3>Two Tower vs Cross Encoder</h3><p>Two-Tower is used for candidate generation. Cross-Encoder is used for ranking.</p><p>A Two-Tower dot product is a cheap matrix multiply, so it scales to billions of items. A Cross-Encoder needs a full transformer forward pass — millions of FLOPs — for every single pair, so it’s fine for ranking a shortlist but can’t touch retrieval at scale.</p><p>Here’s the naive idea I had before I understood why cross-encoders exist: take query and doc, concatenate them, feed a regular neural net, put a binary classification head on top — yes/no, does this doc match this query. Train with cross-entropy, negative sample by pairing queries with random docs.</p><p>The intuition’s fine. The architecture is wrong.</p><p>A plain feedforward net over concatenated text doesn’t use any of the properties that make transformers good at language — no attention, no token-level interaction across query and doc. You’re asking a bag of weights to learn syntax and semantics from your click logs alone.</p><p>The fix: keep the idea, swap in a BERT-style architecture. Feed [CLS] query [SEP] doc [SEP], classification head on the CLS output, backprop through the whole thing. That&#39;s a Cross-Encoder.</p><p>The important bit: query and doc tokens attend to <em>each other</em> inside the network. “Jaguar speed” in the query can attend directly to “cat accelerates to 80km/h” in the doc, at every layer. That cross-attention is where the accuracy comes from.</p><p>It’s also why you can’t use it for retrieval.</p><h3>Why not just use this for search</h3><p>Because you can’t feed 1M documents + a query into a cross-encoder at runtime. Score is not reusable — change the query, every doc score has to be recomputed from scratch, since the doc representation depends on the query.</p><p>Rough numbers: BERT-base forward pass ≈ 2 × params × tokens FLOPs. 110M params, 512 tokens → ~113 GFLOPs per pair. Score 1M docs for one query:</p><pre>1e6 pairs × 113 GFLOPs = 1.13e17 FLOPs</pre><p>H100 does ~990 TFLOPS dense BF16 at peak (you never actually hit peak, but let’s be generous):</p><pre>1.13e17 / 990e12 ≈ 114 seconds</pre><p>~2 minutes, per query, on an H100. For a corpus most companies would call small.</p><p>Two-tower: embed the query once (~113 GFLOPs), doc embeddings were already computed offline days ago. Scoring is a dot product:</p><pre>1e6 docs × 768 dims × 2 = 1.5 GFLOPs</pre><p>~75,000x less query-time compute. And that’s still overstating it, coz ANN never touches all million vectors — HNSW visits a few thousand.</p><p>Cross-encoders aren’t worse, they’re unaffordable at retrieval scale.</p><p>Cross-EncoderTwo-TowerInputQuery + doc togetherQuery and doc separatelyInteractionFull cross-attentionOne dot product at the endDoc embeddingsCan’t precomputePrecomputed offlineQuery-time cost1 forward pass per doc1 forward pass total + ANNScale~100s of candidatesMillions to billionsAccuracyHigherLowerUsed forRerankingRetrieval</p><p>So production systems use both. Two-tower prunes 10M down to ~100. Cross-encoder reranks those 100.</p><blockquote><em>10M corpus → ANN retrieval → 100 candidates → cross-encoder rerank → 20 results → business rules → shown to user</em></blockquote><h3>Why won’t generic BERT/SBERT work for this?</h3><p>You <em>can</em> use them. Embed query and doc with SBERT, index, retrieve. Works fine for a demo.</p><p>Problem 1 — raw BERT embeddings are bad at similarity. BERT was pretrained on masked language modeling + next-sentence prediction (NSP got dropped later — RoBERTa found it wasn’t helping, but it’s part of the original recipe). Neither objective asks the model to produce whole-sentence vectors that are geometrically comparable. The SBERT paper actually measured this: cosine similarity over raw BERT CLS vectors performs <em>worse</em> than averaging GloVe. 2018 transformer loses to 2014 static vectors, coz the transformer was never trained for the thing you’re asking it to do.</p><p>Problem 2 — SBERT fixes similarity, but for a generic domain. SBERT adds a siamese setup and a sentence-level objective. So now the vectors are built for similarity — but it doesn’t always work for specific domian usecases? SBERT learned it off of the text that it used to train from open web. Your domain has its own notion of “related”: two contracts differing by one indemnity clause aren’t similar in legal retrieval, but generic SBERT will think they’re near-identical. “iPhone 15 case” and “iPhone 15” are lexically close and commercially unrelated.</p><p>Problem 3 — it doesn’t do multimodal at all. Text-to-image retrieval, audio, video — a text encoder has no path there. If you’re doing text-to-image, you need your own multimodal embeddings, full stop.</p><p>So what’s the solution, train your own embeddings for query and Document, putting them close into vector space whenever they should be using Contrastive learning, and then use those in Two tower in production for efficient candidate generation.</p><p>Won’t training your own embeddings from scratch be expensive? No — you don’t do it from scratch. Take a pretrained transformer (BERT, or better, something already contrastively trained like E5/BGE) and fine-tune it with InfoNCE on your own pairs. Thousands of examples, hours on one GPU.</p><p>If you’re going to use an open-weight model <em>without</em> fine-tuning, use SBERT/E5/BGE, not raw BERT — BERT was trained for masked word prediction and isn’t good at similarity out of the box. And use the prefixes those models were trained with (&quot;query: &quot; / &quot;passage: &quot;) — skipping it quietly costs you real recall.</p><h3>Two-Tower: how it’s trained</h3><p>We know from above that we need query and doc embeddings trained so that matching pairs end up close in vector space. This is very different from cross-encoder, where you just want yes/no out — that’s expensive at runtime.</p><p>So the idea:</p><ul><li>Train query and doc embeddings so similar pairs are closer in vector space</li><li>Since you now have embeddings, drop them in a vector store, use ANN to prune millions of docs fast</li></ul><p>To train this you need InfoNCE, and here’s why.</p><p>Say you have (q1,D1), (q2,D2), (q3,D3), (q4,D4), and the first pair is positive, the rest negative (for q1). You <em>could</em> train 4 independent binary classifiers — is (q1,D1) a match, is (q1,D2), etc. Instead InfoNCE trains on all 4 together as one softmax: given these candidates, which document is correct.</p><h3>The math</h3><p>Batch of N pairs. Encode, L2-normalize (so dot product = cosine). Score between query i and doc j:</p><pre>s_ij = qᵢ · dⱼ / τ</pre><p>τ is temperature, more on that below.</p><p>Stack into an N×N matrix. Diagonal = positives, off-diagonal = negatives:</p><pre>d₁     d₂     d₃     d₄<br>  q₁  [ ✓  ]   ✗      ✗      ✗<br>  q₂    ✗    [ ✓  ]   ✗      ✗<br>  q₃    ✗      ✗    [ ✓  ]   ✗<br>  q₄    ✗      ✗      ✗    [ ✓  ]</pre><p>Softmax each row, take negative log-likelihood of the diagonal:</p><pre>L = -(1/N) Σᵢ log[ exp(sᵢᵢ) / Σⱼ exp(sᵢⱼ) ]</pre><p>That’s InfoNCE. Cross-entropy over a similarity matrix, where the label is always the diagonal. In code:</p><pre>def info_nce(q, d, temperature=0.05):<br>    q = F.normalize(q, dim=-1)<br>    d = F.normalize(d, dim=-1)<br>    logits = q @ d.T / temperature<br>    labels = torch.arange(q.size(0), device=q.device)  # diagonal = answer<br>    return F.cross_entropy(logits, labels)</pre><p>5 lines.</p><h3>How is this different from a regular NN doing softmax + cross-entropy?</h3><p>Fair question — InfoNCE looks almost identical to plain softmax cross-entropy, coz in this form it basically is that, applied to a similarity matrix.</p><p>The difference: in a regular NN, your logit for class k is w_kᵀx — w_k is a learned weight vector, a fixed column of the output layer, and the number of classes is fixed before training.</p><p>In InfoNCE, the logit is qᵀd. d isn&#39;t a parameter — it&#39;s computed by the <em>other tower</em>, at runtime, from whatever docs got sampled into the batch. Both sides of the dot product are model outputs. The &quot;class weights&quot; get regenerated every batch, and the number of &quot;classes&quot; is just your batch size.</p><p>So the model can’t memorize per-class weights the way a normal classifier partly can — there’s nothing fixed to memorize, the target changes every step. It’s forced to learn a general metric instead. And it generalizes to items it’s never seen: a softmax classifier over 1M products needs a 1M-wide output layer and can’t score product 1,000,001; a two-tower model just encodes the new item, zero-shot. Both towers get gradient from the same loss, so query tower and doc tower negotiate a shared space together.</p><p>So yeah — it is cross-entropy + softmax underneath. The actual difference is the two-tower setup feeding it: query embedding layer, doc embedding layer, dot product, then the same old cross-entropy. Both towers get trained during this, obviously.</p><h3>Do we need to find negatives ourselves?</h3><p>No — if you have click logs, e.g. user clicked (q1,D1), (q2,D2), (q3,D3), you get negatives for free by pairing q1 with D2, D3, D4, and so on. That’s in-batch negatives.</p><h3>Temperature</h3><p>τ scales the logits before softmax. Since normalized dot products live in [-1, 1], without it the softmax is nearly flat and gradients barely move anything.</p><p>Too high (0.5) — everything looks equally plausible, no separation. Too low (0.01) — loss fixates on the single hardest negative, training gets unstable. 0.02–0.07 is the usual working range. CLIP learns it as a parameter, clamped.</p><h3>Hard negatives</h3><p>In-batch negatives are random, so they’re mostly easy — for “how do I reset my password,” a random doc about shipping is trivially wrong, model nails it immediately, gradient goes to ~zero. The examples that actually teach are close-but-wrong ones — a doc about changing your password, or resetting your username.</p><p>Standard loop: train a round with in-batch only → encode the corpus, retrieve top-50 per training query → take ranks ~10–50 as hard negatives (skip the very top ones, often unlabeled positives) → retrain with those added to the pool → repeat 2–3x.</p><p>Skipping the top-rank warning is the mistake people make and then debug for a week — if a mined “negative” is actually relevant but unlabeled, you’re training the model to push apart things that belong together.</p><h3>Is two-tower the main use case for InfoNCE?</h3><p>No — it’s the main use case for contrastive learning (similar things closer, dissimilar things farther), and two-tower is just one place that applies. InfoNCE more generally is for learning representations by saying “this thing should match this thing, and not these other things.”</p><p>CLIP uses it — text encoder, image encoder, contrastive loss during training so it learns to discriminate text-image pairs well. Same N×N matrix trick, just image/caption pairs instead of query/doc.</p><p>You can also do this self-supervised, without any labels — for image embeddings, take one image, apply two different augmentations (crop, color jitter, blur), and those two views become your (query, doc) pair. Same idea works for audio (two segments of the same clip) and video (adjacent frames).</p><h3>How production retrieval actually looks — search, recommendations</h3><ul><li>Retrieval, two-tower: you can use open-weight embeddings but they may not scale to your domain — or train your own with InfoNCE, using in-batch negatives and your q/D pairs.</li><li>Store the resulting embeddings in a vector DB, use ANN for retrieval. FAISS is the usual pick in production coz it’s in-memory and fast — you can go cloud-based but it’s slower, and that time is better spent on reranking.</li><li>Retrieve, then rerank with something like a cross-encoder — again, train your own for the domain or use an open-weight one (BGE-reranker, ms-marco-MiniLM). Under the hood it’s BERT, learning to output true/false for query-doc similarity.</li><li>Finally, business-level reranking — freshness, novelty, business rules. Note: MRR and nDCG aren’t reranking methods, they’re evaluation metrics — how you measure whether the pipeline got better. The actual reranking here is heuristics/rules, not the metric itself.</li></ul><blockquote><em>horizontal pipeline — corpus → ANN → cross-encoder → business rules → results, latency budget under each stage</em></blockquote><h3>Takeaways</h3><p>Cross-encoders are more accurate and structurally can’t scale. Two-tower is less accurate and scales to billions. Production uses both, at the stage each one can afford.</p><p>Off-the-shelf embeddings encode generic similarity, not yours — fine for a baseline, not for a destination.</p><p>You don’t train from scratch — fine-tune a pretrained encoder with InfoNCE on your own pairs.</p><p>InfoNCE is cross-entropy over a similarity matrix. What makes it different from a normal classifier is that the logits come from two encoders instead of a fixed weight matrix — which is exactly what forces it to learn a metric space instead of memorizing classes.</p><p>Batch size is your negative sampling strategy. Bigger batch → more negatives → better model, before you reach for a fancier loss.</p><p>Hard negatives are the round-2 upgrade — mine from your own model’s mistakes, skip the top-ranked ones, iterate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c16d38257a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why do transformers use sine and cosine for positional encoding?]]></title>
            <link>https://medium.com/@arundobriyal_33904/why-do-transformers-use-sine-and-cosine-to-know-where-a-word-is-20f505cb5a3e?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f505cb5a3e</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[positional-encoding]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 23:52:28 GMT</pubDate>
            <atom:updated>2026-08-27T00:15:28.757Z</atom:updated>
            <content:encoded><![CDATA[<p>A friend of mine asked me a question I thought I’d internalized earlier this year:</p><p><em>Why do transformers use sin and cos for positional encoding? Why not just… number the words 1, 2, 3?</em></p><p>I thought about it, and realized my mental model was less clearer than I anticipated. So I spent last evening working through the intuition. If you’ve stared at the positional encoding formula from “Attention Is All You Need” and thought <em>why is there trigonometry in my language model</em>, hopefully this saves you the same evening.</p><h3>The problem: attention doesn’t care about order</h3><p>Attention, as an operation, is a bag of words. That sounds like a strong claim, but it’s just true. If I hand a transformer:</p><blockquote><em>cat eats mouse</em></blockquote><p>and:</p><blockquote><em>mouse eats cat</em></blockquote><p>with no positional info, the attention layer sees the same three vectors either way. It has no idea which came first. The Q · K dot products don’t change.</p><p>That’s obviously bad. “Cat eats mouse” is dinner. “Mouse eats cat” feels unreasonable. We need to inject position somehow before the first attention layer runs.</p><h3>The naïve fix (and why it doesn’t work)</h3><p>Let’s ground this in an actual sentence: “cat and dog”. Three tokens — cat at position 1, and at position 2, dog at position 3.</p><p>Real word embeddings aren’t 2 or 3 numbers. Production transformers use 512, 768, sometimes higher-dimensional vectors. So cat and dog actually look something like this (768 numbers each — showing the first 6 and the last one so you get the shape of the thing):</p><pre>cat ≈ [ 0.82, -0.14, 0.36, 0.05, -0.71, 0.29, ... , -0.18 ]   (768 numbers)<br>dog ≈ [ 0.77, -0.09, 0.41, 0.11, -0.68, 0.24, ... , -0.15 ]   (768 numbers)</pre><p>Notice cat and dog sit pretty close to each other — makes sense, they’re both animals, and embedding space puts semantically similar words near each other. But nothing in either vector says where the word sits in a sentence. That’s the gap we need to close.</p><p>The first thing you’d try: just add the position number, as a scalar, onto every entry of the embedding.</p><pre>cat at position 1 → cat + 1 → [ 1.82, 0.86, 1.36, 1.05, 0.29, 1.29, ... , 0.82 ]</pre><p>Looks harmless at position 1. Now imagine this same word showed up later, at position 500, in a longer document:</p><pre>cat at position 500 → cat + 500 → [ 500.82, 499.86, 500.36, 500.05, 499.29, 500.29, ... , 499.82 ]</pre><p>1st problem, and it’s the big one: the values blow up, identically across every dimension. cat’s entire identity — the specific pattern of 0.82, -0.14, 0.36… that made it recognizably “cat” and distinguishable from “dog” — is now a rounding error sitting next to 500. You’ve drowned the signal.</p><p>You could normalize by dividing by max sequence length. But then you don’t know the max sequence length at inference time, and a 10-token sentence and a 10,000-token document end up on incompatible scales.</p><p>2nd problem, more subtle: even before it blows up, adding one shared scalar to every dimension is a thin way to represent position. The model has a single shared offset to work with — not enough surface area to build relative-position machinery like “attend to the word two positions back.”</p><p>So we need position to be its own vector — same shape as the word embedding, so we can just add them — and one that stays well-behaved without needing outside context like sequence length.</p><p>Let’s shrink the problem down to see the idea clearly: forget 768 dimensions for a second, and say we only had 2. cat at position 1 would need some vector [x, y], and <em>and</em> at position 2 would need a different vector [p, q]. Fine — but what are x, y, p, q actually supposed to be?</p><p>You could just pick numbers by hand:</p><pre>position 1 → [0.2, 0.8]<br>position 2 → [0.4, 0.6]<br>position 3 → [0.6, 0.4]</pre><p>That technically works — every position gets a distinct pair. But it’s arbitrary. Nothing connects position 4 to position 3 the way 4 is mechanically related to 3 on a number line. And if I asked “what’s the vector for position 4,857?” you’d have no rule to apply — you’d just have to have hand-picked it already, forever, for every position anyone might ever use.</p><p>What we actually want is a function: feed in an integer position, get back an [x, y] pair, where nearby positions land close together and the numbers never blow up no matter how large the position gets.</p><p>Geometry already solved this problem. It’s called a circle.</p><h3>Enter the clock</h3><p>Put a point on a circle. As it moves around, its (x, y) coordinates are (cos θ, sin θ). Every angle gives you a unique 2D coordinate. And — this is the important part — nearby angles give you nearby coordinates. The representation is smooth.</p><p>So instead of saying “position 17,” we could say:</p><pre>position 17 → (sin 17, cos 17)</pre><p>Two dimensions, encoding one position. Better than a scalar. Bounded to [-1, 1], so it doesn’t blow up. Smooth, so position 17 and 18 look almost the same.</p><p>There’s one problem: a single clock repeats. After a full cycle, position 1 and position 1 + 2π look identical. If your sentence has 500 tokens and your clock has a period of ~6, you’ll get collisions everywhere.</p><h3>Multiple clocks, at different speeds</h3><p>The fix is what makes the whole thing click: use many clocks, ticking at different speeds — one cycling every ~10 tokens, another every ~100, another every ~1000, another every ~10000. At any given position, you write down the reading from every clock at once. Two positions might agree on the fast clock, but they won’t agree on all of them simultaneously — the combined reading is a fingerprint. Same trick GPS uses with multiple satellites, or a barcode encodes an ID across stripes of different widths.</p><p>In the actual formula, if d is your embedding dimension (say 12), you get d/2 clock pairs. Pair i ticks at frequency 1 / 10000^(2i/d). Small i = fast clock. Large i = slow clock. So:</p><pre>PE(pos, 2i)   = sin(pos / 10000^(2i/d))<br>PE(pos, 2i+1) = cos(pos / 10000^(2i/d))</pre><p>That’s the whole formula.</p><h3>A worked example: “cat and dog” in 12 dimensions</h3><p>Let’s actually compute this, because staring at the math abstractly never worked for me.</p><p>d = 12, so we get 6 clock pairs, each ticking at its own frequency — pair 1 fastest, pair 6 slowest:</p><pre>pair 1: 10000^0/12  ≈ 1        (fastest)<br>pair 2: 10000^2/12  ≈ 21.54<br>pair 3: 10000^4/12  ≈ 464.16<br>pair 4: 10000^6/12  ≈ 1000<br>pair 5: 10000^8/12  ≈ 2154.43<br>pair 6: 10000^10/12 ≈ 4641.59  (slowest)</pre><p>For pair 1 and cat at position 1, the formula is literally sin(1/1) = 0.8415 and cos(1/1) = 0.5403. Same mechanical step for every other pair, and every other word — divide the position by that pair’s frequency, take sin and cos. Doing that across all three words and all six pairs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5UKB62CvF196NfmRsVhkg.png" /></figure><p>Read a column and you get a word’s full 12-dim PE vector. Read a row and the story gets interesting:</p><ul><li>Row 1 swings hard between words — 0.84 → 0.91 → 0.14. The fast clock is spinning through most of a rotation in just two ticks.</li><li>Row 6 barely moves — 1.0000 three times in a row. The slow clock hasn’t ticked meaningfully yet; it’s reserved for telling apart positions that are far apart, like position 3 vs. position 3000.</li><li>Every entry is completely deterministic. Nothing here is learned.</li></ul><p>The final input to the transformer is just element-wise addition:</p><pre>input = word_embedding(cat) + PE(1)</pre><p>Same shape, no fancy fusion. Let’s actually do that addition and see the real output. To keep the arithmetic sane, I’ll shrink cat’s and dog’s word embeddings down to the same 12 dimensions as our toy PE (a real model would use its actual 768-dim embedding here — these numbers are invented, just to illustrate the mechanism):</p><pre>cat_embedding ≈ [ 0.20,  0.70, -0.10,  0.40,  0.15, -0.30,  0.55,  0.10, -0.20,  0.05,  0.30, -0.15]<br>dog_embedding ≈ [ 0.18,  0.68, -0.05,  0.35,  0.20, -0.25,  0.50,  0.15, -0.18,  0.08,  0.28, -0.10]</pre><p>Like the 768-dim versions earlier, cat and dog start out close to each other — both animals. Now add each word’s PE from the table above, dimension by dimension:</p><pre>cat_final = cat_embedding + PE(1)<br>          = [1.0415, 1.2403, -0.0536, 1.3989, 0.1522, 0.7000, 0.5510, 1.1000, -0.1995, 1.0500, 0.3002, 0.8500]</pre><pre>dog_final = dog_embedding + PE(3)<br>          = [0.3211, -0.3100, 0.0888, 1.3403, 0.2065, 0.7500,           <br>             0.5030, 1.1500, -0.1786, 1.0800, 0.2806, 0.9000]</pre><p>cat_final and dog_final are what actually enter the first attention layer. Look at dimension 2: cat and dog started nearly identical there (0.70 vs 0.68), but after adding position they land at 1.24 vs -0.31 — worlds apart. That’s the fast clock (pair 1, position 1 vs position 3) doing exactly what we wanted: injecting enough of a positional signature that “cat, early in the sentence” and “dog, later in the sentence” are now clearly distinguishable vectors, even though the underlying words are semantically similar.</p><h3>“But how does the transformer know [0.84, 0.54, …] means position 1?”</h3><p>It doesn’t. There is no dimension in that vector that says “1.” Nothing decodes it.</p><p>The thing that actually clicked for me: the transformer never needs to recover the position number. That’s not the job.</p><p>The job is: when the query for dog dot-products against the key for cat, does the resulting attention score reflect the fact that they’re two positions apart? That’s it. That’s all “understanding position” means at this layer.</p><p>And because the positional encoding is structured — it’s not random noise, it’s a smooth combination of sinusoids at known frequencies — the Q and K projection matrices can learn transformations that respond to those patterns. The model can learn to write a query that says “attend strongly to whatever key is one position before me” without ever having a variable called position.</p><p>The face-recognition analogy: a 512-dim face embedding for me doesn’t have one dimension labeled “Arun.” The whole vector, collectively, is me. Same idea. The 12-dim PE(1) vector, collectively, is position 1.</p><h3>Bonus: why sine AND cosine (not just use sine only)?</h3><p>This is the part I always used to hand-wave. The real reason: sine and cosine together give you a rotation-friendly representation of position.</p><pre>sin(x + Δ) = sin(x)cos(Δ) + cos(x)sin(Δ)<br>cos(x + Δ) = cos(x)cos(Δ) − sin(x)sin(Δ)</pre><p>If you know [sin(x), cos(x)], this identity lets you compute [sin(x+Δ), cos(x+Δ)] with a fixed linear transformation that depends only on Δ — not on x. In other words, shifting position by Δ is the same transformation no matter where you start. That’s what lets attention learn “look Δ tokens back” as one reusable operation, instead of memorizing a separate rule for every position pair.</p><p>Sine alone can’t give you this — you need the pair to pin down the full rotation.</p><h3>What happens during backprop?</h3><p>So — when we train our Neural network, do the positional encodings get updated by gradient descent?</p><p>For sinusoidal PE — no. There are no learnable parameters. The formula is fixed. Gradients flow through the addition (input = embedding + PE), but there’s nothing to update on the PE side. It’s the same as writing y = x + 5 and asking whether 5 gets updated.</p><p>The word embedding table, on the other hand, does get updated. Every time cat appears in a batch, its row in the embedding table gets a gradient and moves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEcg74QAnBZEo3MQgveCEw.png" /></figure><p>That last row is worth calling out, because it’s what most modern models actually use. Instead of the sinusoidal formula, they allocate a parameter table of shape [max_seq_len, d_model] and let the model learn what “position 17” should look like. Simpler to reason about, works well within the trained range, but doesn’t extrapolate to longer sequences the way sinusoidal PE does. That tradeoff — and the newer approaches like ALiBi and RoPE — is a whole other post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f505cb5a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100K concurrent Virtual threads on 1 CPU core]]></title>
            <link>https://medium.com/@arundobriyal_33904/100k-concurrentvirtual-threads-on-1-cpu-core-3844b8892869?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3844b8892869</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 04:31:24 GMT</pubDate>
            <atom:updated>2026-08-24T04:32:26.569Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve read the Project Loom (Java virtual threads) pitch a dozen times. I wanted to confirm how far I could go with Virtual threads and confirm its efficacy.</p><p>So I built the simplest test I could: one Java HTTP server, one endpoint that blocks for a second (simulating a DB call), and exactly one CPU core. If virtual threads only look good when you throw hardware at them, that’s not really the pitch.</p><p>Platform threads (one OS thread per request) hit a wall around 4,700 requests/second and started failing outright past a few thousand concurrent.</p><p>Virtual threads held a clean ~18,500 requests/second — roughly 4x — and kept answering correctly out to 100,000 concurrent connections (25x).</p><h3>The setup</h3><p>macOS has nothing like Linux’s taskset — no way to pin a process to a physical core. So &quot;one CPU core&quot; needed a different mechanism: Docker&#39;s --cpus=1, a hard CPU quota enforced by cgroups. I like this better than affinity anyway — it&#39;s the same mechanism a Kubernetes pod uses for resources.limits.cpu: 1. A real production constraint, not a toy one.</p><p>I ran it through Colima (a lightweight, CLI-only Linux VM manager) rather than Docker Desktop — gave it 6 cores and 32GB, then split that across two containers on the same network: the server, hard-capped to --cpus=1, and a separate load-generator container with its own CPU budget, so the thing generating load never competes with the thing I&#39;m measuring.</p><p>The handler:</p><pre>server.createContext(&quot;/work&quot;, exchange -&gt; {<br>    Thread.sleep(1000);  // pretend this is a DB call<br>    exchange.sendResponseHeaders(200, body.length);<br>    exchange.getResponseBody().write(body);<br>});</pre><p>And the entire experiment lives in one line — the executor:</p><pre>// classic model: one OS thread per request<br>Executors.newThreadPerTaskExecutor(Thread.ofPlatform().factory());</pre><pre>// virtual threads: one JVM-managed thread per request<br>Executors.newVirtualThreadPerTaskExecutor();</pre><p>Same handler, same server, same container, same CPU quota. That one line is the only thing that changes.</p><h3>What a “thread” costs</h3><p>The standard Java server model: accept a connection, hand it a dedicated OS thread, let it block for as long as the request takes. Simple, but an OS thread isn’t free — each reserves roughly a megabyte of stack, and it’s a real entity the kernel has to schedule, even while it’s just sitting in Thread.sleep().</p><pre>platform-thread model — one real OS thread per in-flight request</pre><pre>request 1 ──▶ OS thread 1   (~1MB stack, a kernel scheduling entity,<br>request 2 ──▶ OS thread 2    fully &quot;alive&quot; even while just sleeping<br>request 3 ──▶ OS thread 3    on a DB call that hasn&#39;t replied yet)<br>   ...<br>request N ──▶ OS thread N</pre><p>Fine at a few hundred concurrent requests. Push toward tens of thousands and the OS is tracking tens of thousands of real threads that are mostly just waiting.</p><p>Virtual threads (stable since JDK 21) change what a “thread” is made of. Not an OS thread — a cheap JVM-managed object sitting on a small pool of real OS threads called carriers. The trick is what happens when one blocks:</p><pre>virtual-thread model — many cheap JVM threads, few real carrier threads</pre><pre>request 1 ──▶ virtual thread 1  ─┐<br>request 2 ──▶ virtual thread 2   │   thousands of these. Each one a<br>request 3 ──▶ virtual thread 3   │   cheap object with a small, resizable                        |<br>   ...                           │   stack, multiplexed onto a much<br>request N ──▶ virtual thread N  ─┘   smaller pool of real carrier threads</pre><pre>when a virtual thread calls something blocking (Thread.sleep, blocking I/O):<br>  → it unmounts from its carrier thread entirely<br>  → the carrier is free to run a DIFFERENT virtual thread<br>  → when the block ends, it remounts onto whichever carrier is free</pre><p>You still write Thread.sleep(1000) — the code doesn&#39;t change. What changes is the JVM stops wasting a real OS thread on the wait. I wanted to see that hold up under load, on hardware that couldn&#39;t brute-force past a bad design.</p><h3>They’re identical until they aren’t</h3><p>Same low-concurrency levels for both, mostly to confirm my setup wasn’t lying to me:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*8U5Kx_PDYOoOp68Xe8dfBg.png" /></figure><p>Identical, as expected — nowhere near either model’s limits yet. Good, boring, exactly what I wanted before pushing harder.</p><p>The split starts at 6,000 concurrent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cECKn5DEUuU2ddMbUraW_Q.png" /></figure><p>Platform threads are already plateauing. Virtual threads are still climbing linearly.</p><h3>Why platform threads actually break</h3><p>My first guess: the JVM couldn’t <em>create</em> enough OS threads — some ulimit, memory for all those stacks. I checked instead of assuming:</p><pre>threads-max (kernel)     : 255,886<br>pid_max                  : 4,194,304<br>ulimit -u (nproc)        : 200,000  (set generously myself)<br>cgroup pids.max          : unlimited</pre><p>Nothing close to binding.</p><p>Then I noticed something that looked like a real limit: across several runs, no matter how high I pushed concurrency — 25,000, even 50,000 — the server’s in-flight counter topped out at exactly 9,990, every time. Three runs, same number. I was fairly convinced I’d found a hard-coded cap in the JDK’s HTTP server.</p><p>So I dug instead of writing it down as fact. Fresh server container, no prior traffic, hit directly at 25,000 concurrent. Peak in-flight this time: 7,560. A different number.</p><p>That killed the “hard cap” theory. What I was looking at was a scheduling equilibrium — the point where the rate the server can accept new requests balances the rate it finishes them, which drifts with timing noise. 9,990 three times in a row was coincidence wearing a pattern’s clothes.</p><p>The actual failures, once I looked:</p><pre>error_breakdown: 451x HttpConnectTimeoutException: HTTP connect timed out<br>                | 123x IOException: HTTP/1.1 header parser received no bytes</pre><p>Java’s built-in com.sun.net.httpserver.HttpServer accepts connections through essentially a single dispatcher thread, separate from the pool running your handlers. On one CPU core, that dispatcher competes for scheduling time against thousands of platform threads the OS has to context-switch between — even though most are just sleeping. Past a certain concurrency, the dispatcher gets starved badly enough that it can&#39;t accept and read new connections in time. Not out of threads, not out of memory. Its front door is too busy to answer.</p><h3>How far can virtual threads actually go?</h3><p>My first pass reused the same single load-generator container from the platform-thread test. It reported a clean plateau around 10,300 rps at 12,000 concurrent, then a “collapse” to ~5,481 rps at 25,000 — latency climbing, but zero errors. I wrote that down as the ceiling.</p><p>Except it nagged at me. 0 errors, but throughput cut in half? An overwhelmed server usually starts refusing or timing out requests before throughput drops that cleanly. So I looked for a boring explanation instead of an exciting one.</p><p>The boring explanation: an HTTP/1.1 connection needs a dedicated local source port. A single Linux container’s ephemeral range defaults to roughly 32,768–60,999 — about 28,000 ports. My load generator was trying to hold 25,000 simultaneous connections open from one container, one IP. A TCP connection is a 4 tuple (Source IP, source Port, Target IP, Target Port), the first 3 were same since I am running locally on my machine, only the Target Ports can change, and ports are 16 bit, so if we need to run a load test with a lot of connections, 65,536 ports are not enough. And this is precisely what I was running into.</p><p>The fix: don’t push all the load through one client. Split it across four driver containers, each its own IP, its own port budget, running in parallel:</p><pre># split concurrency across N clients, each with its own IP —<br># so no single client&#39;s port budget becomes the bottleneck<br>per_shard = total_concurrency // len(drivers)<br>results = [run_shard(driver, per_shard) for driver in drivers]  # in parallel</pre><p>Same 25,000-concurrency test, rerun this way. The “collapsed” number wasn’t 5,481 rps — it was 18,559 rps, at 0.1% errors. My first measurement hadn’t found the server’s ceiling. It had found my load generator’s ceiling and mistaken it for the server’s — roughly half the real number.</p><h3>The real ceiling</h3><p>With the load generator out of the way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*R8xeZuCKTQpIo-VlUeehzQ.png" /></figure><p>25,000 through 100,000: throughput doesn’t move — within 2% of itself across a 4x jump in concurrency. That’s the actual ceiling. What moves is latency, roughly doubling at each step, because requests queue up while the completion rate stays flat — textbook queueing behavior, until wait time exceeds my load generator’s 5-second connect timeout and starts registering as failures.</p><p>By 200,000, real collapse: throughput falls off a cliff, most requests time out, median wait past 20 seconds.</p><p>The server never crashed.</p><pre>status=running   oom=false   restarts=0<br>memory: 5.08GB / 20GB cap<br>peak concurrent in-flight virtual threads: 82,220<br>server-side exceptions: 0</pre><p>Never — not once, including the run with an 84.8% client-side error rate. At its worst it had 82,220 virtual threads alive at once, using a quarter of its memory budget, and every failure was a client giving up waiting, not the server throwing.</p><h3>What I’d actually tell you</h3><p>Roughly 25x more throughput on identical hardware, from one changed line. Platform threads plateaued around 4,700 rps and started failing past a few thousand concurrent. Virtual threads held ~18,500 rps flat to 100,000 concurrent, and degraded by getting slow rather than crashing.</p><p>Part of what broke platform threads was specific to com.sun.net.httpserver&#39;s single-threaded dispatcher — a tuned Netty or Tomcat would likely push platform threads further. I used the JDK&#39;s built-in server on purpose, to isolate the threading model as the variable, not to recommend it for production.</p><p>The workload is a best case for virtual threads — pure I/O wait, zero CPU per request. If your handler does real computation, <strong>one CPU core is one CPU core either way; virtual threads eliminate the cost of waiting, not compute</strong>.</p><p>Lastly, if your benchmark involves a client generating serious concurrent load, check whether the client can actually produce that load before trusting what it reports.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3844b8892869" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10K Threads Took Down My Mac. 1M Coroutines Didn’t Notice.]]></title>
            <link>https://medium.com/@arundobriyal_33904/10k-threads-took-down-my-mac-1m-coroutines-didnt-notice-7927ebed253f?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7927ebed253f</guid>
            <category><![CDATA[non-blocking-io]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 17:58:19 GMT</pubDate>
            <atom:updated>2026-08-22T17:58:19.803Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I set out to answer a boring question: if I have a lot of things to wait on, what primitives should I use?</blockquote><p>My machine is an M5 Max with 128GB of RAM. I intentionally designed a very simple program doing nothing but IO — wait 1 sec, do nothing, finish. I ran 10K programs as OS threads. The fans came up, the cursor started skipping, and then I saw a black screen. Hard reboot.</p><p>Subsequently, I modified my approach, I ran a million of programs as coroutines. It took 6.11 seconds and 1.6GB, and the machine did not notice.</p><p>This post is about the gap between those two sentences, because the gap is not a small constant factor.</p><h3>The thing being measured</h3><p>Every unit of work is identical and deliberately stupid:</p><pre># coroutine version<br>async def work():<br>    await asyncio.sleep(1)<br><br># thread version<br>def work():<br>    time.sleep(1)</pre><p>One second of waiting. No CPU, no disk, no network. I picked sleep on purpose — it strips out every variable except the one I care about: what does it cost to have one more thing waiting?</p><p>That question has a name I didn’t have when I started: per-unit cost. If a unit of waiting is cheap, you can have a lot of them and your concurrency limit is whatever your problem needs. If a unit of waiting is expensive, your concurrency limit is set by your runtime, not your problem, and you will find that limit by falling off it.</p><p>A thread pool with max_workers=n will happily recycle threads if the work finishes fast, and then you&#39;ve measured a pool, not n threads. The barrier forces all n to be simultaneously alive.</p><pre>def run_threads(n):<br>    done = threading.Barrier(n + 1)<br><br>    def work():<br>        time.sleep(1)<br>        done.wait()<br><br>    threads = [threading.Thread(target=work) for _ in range(n)]<br>    for t in threads:<br>        t.start()   # every start() is a clone() syscall + a fresh kernel stack<br>    done.wait()     # all n are alive at the same instant, not recycled</pre><p>The barrier matters. A thread pool with max_workers=n will happily recycle threads if the work finishes fast, and then you&#39;ve measured a pool, not n threads. The barrier forces all n to be simultaneously alive.</p><h3>The ladder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IDxceNHB4rUZq3ANOsEIw.png" /></figure><p>A coroutine costs about <strong>1.6KB</strong> and that number does not move from a thousand units to a million units. A thread costs about 36KB resident, 22x more, and that number doesn’t move either. Now, look at the wall-clock column for threads.</p><p>The job takes 1 sec. At 1,000 threads it takes 1.16 seconds — fine, 160ms of overhead, whatever. At 2,000 threads it takes 3.17 seconds. At 4,000 it takes 7.31 seconds. The work did not get harder. Nothing is CPU-bound. Every one of those threads is asleep in the kernel doing precisely nothing, and yet doubling the count more than doubles the time.</p><p>That’s not a memory problem. That’s the <strong>cost of <em>creating</em> the thread</strong>, and it’s getting worse per thread as you add more: roughly 0.16ms each at 1K, 1.1ms each at 2K, 1.6ms each at 4K. Extrapolating that curve to 10,000 gets you somewhere north of 16 seconds of pure spawn overhead before a single second of useful sleeping happens — assuming the curve stays that polite, which, judging by my reboot, it does not.</p><p>I stopped the thread ladder at 4,000 deliberately. I already know what 10,000 does.</p><h3>What I got wrong about why</h3><p>My first theory was stack memory, because that’s the folklore. Every thread gets an 8MB stack; ten thousand threads is 80GB of address space; of course it fell over.</p><p>That’s Linux folklore, and I was on a Mac. Checking instead of repeating:</p><pre>$ ulimit -s<br>8176<br>$ pthread_attr_getstacksize(&amp;default_attrs, &amp;s)<br>pthread default stacksize: 524288 bytes (512 KB)</pre><p>So what actually broke? Spawn cost and the kernel bookkeeping behind it. Every Thread.start() is a syscall into the kernel that allocates a task structure, a kernel stack, a scheduler entry, and signal state. <strong>macOS caps a single process at 16,384 threads </strong>(kern.num_taskthreads), so 10,000 is legal — it&#39;s just that &quot;legal&quot; and &quot;survivable&quot; are different words. 10K threads means 10K scheduler entries, and when their timers all expire at the same moment, 10K wake-ups land on the run queue in the same instant. The scheduler is now the workload.</p><p>The honest version of the folklore is: threads are expensive because they are kernel objects, and you are asking the kernel to do something at a scale it was not designed around. The stack is a symptom, not the cause.</p><h3>What a coroutine actually is</h3><p>A coroutine isn’t a lightweight thread. It isn’t a thread at all, and that’s why the number is 1.6KB.</p><p>asyncio.sleep(1) does not call nanosleep(). Nothing is put to sleep, because there&#39;s nothing that could be — there&#39;s one thread and it has other things to do. What actually happens is that the coroutine creates a Future, registers a callback with loop.call_later(1, ...), and <em>returns control to the event loop</em>. The coroutine&#39;s local state stays on the heap as a suspended frame. That&#39;s the 1.6KB: a Python object graph, not a kernel object.</p><p>The event loop keeps every pending timer in one heap, computes min(remaining) across all of them, and passes that as the timeout to a single epoll_wait() / kqueue() call. A million pending sleeps is 1<strong> data structure</strong> and one blocking syscall — not a million of anything at the kernel level. The kernel doesn&#39;t know your program has a million things in flight. From where it&#39;s standing, you have one thread that keeps asking what time it is.</p><p>This is why the per-unit cost stays flat from 1K to 1M while the thread number is already curving upward at 2K. You didn’t make waiting cheaper. You moved it out of the kernel.</p><p>And that’s also the catch.</p><h3>The rule you cannot break</h3><p>The event loop is one thread. Every bit of the leverage above depends on that thread never, ever stopping.</p><pre>async def work():<br>    time.sleep(1) </pre><p>That’s a two-character difference from the working version and it undoes everything. time.sleep() calls nanosleep(), the kernel parks the calling thread on a timer wait-queue — the same mechanism as a blocking recv(), just triggered by a clock instead of a packet. But that thread is <em>the event loop</em>. There is no other thread. Your million concurrent tasks are now a million tasks queued behind one sleeping thread, executing strictly one after another, and your program is not concurrent, it&#39;s a for-loop with extra syntax.</p><p>With threads, this mistake is invisible — that’s the entire point of threads. One thread blocks, the OS preempts it, the other 999 keep running. Preemptive multitasking means the scheduler doesn’t need your cooperation.</p><p>asyncio is cooperative multitasking. await is where the cooperation happens, and it&#39;s the only place. A coroutine that never awaits never yields, and a coroutine that calls a blocking function yields nothing and takes the whole loop down with it. Every library you call inside a coroutine has to be non-blocking too — requests will do this to you, psycopg2 will do this to you, an innocent open().read() on a slow disk will do this to you.</p><p>Non-blocking I/O is not a performance optimization you sprinkle on. It’s the load-bearing assumption.</p><h3>What workloads break Coroutines</h3><p><strong>CPU-bound work</strong> poisons the queue. Cooperative scheduling has no answer for a task that never yields. Say you have 200 tasks, 199 of which take 1ms, and the first one does 20 seconds of JSON parsing. There’s no await in a parsing loop, so nothing yields, so all 199 fast tasks wait 20 seconds. Your p99 is now 20 seconds for work that takes a millisecond. With threads this doesn&#39;t happen — the fat thread gets preempted whether it likes it or not. The fix isn&#39;t cleverness, it&#39;s run_in_executor or a separate process; and if the work is <em>all</em> CPU-bound, asyncio is the wrong tool entirely and the GIL means threads are too.</p><p>Fairness is not on offer. asyncio gives you throughput at scale, not latency guarantees. If you want both — genuinely high concurrency <em>and</em> a bounded tail — that’s the argument for a runtime that preempts its own green threads. <strong>Erlang’s scheduler gives each process a reduction budget</strong> (roughly a couple thousand function calls) and forcibly preempts when it runs out, at about 1KB per process. That’s cooperative-scale cost with preemptive-scale fairness, and it’s the one thing asyncio structurally cannot give you.</p><h3>Summary</h3><p>Pick the primitive by what one unit of waiting costs, and know which costs you’re actually paying.</p><ul><li>I/O-bound, high concurrency → asyncio. 1.6KB and flat. Nothing else in Python competes at this scale, and the ceiling is high enough that you’ll hit a file-descriptor limit or the far end of the network long before you hit the runtime.</li><li>I/O-bound, modest concurrency, blocking libraries you can’t replace → threads. A few hundred is completely fine; the overhead is real but it’s not the thing that will hurt you, and it works with code that knows nothing about await.</li><li>CPU-bound → processes. The GIL means threads buy you nothing and asyncio buys you less than nothing, because at least threads get preempted.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7927ebed253f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add 3M entries in 1 second in a single Redis node!]]></title>
            <link>https://medium.com/@arundobriyal_33904/how-to-add-3m-entries-in-1-second-in-a-single-redis-node-78bd9f57e735?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/78bd9f57e735</guid>
            <category><![CDATA[key-value-store]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[memcached]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 07:35:49 GMT</pubDate>
            <atom:updated>2026-08-20T07:35:49.218Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve used Redis for years — cache here, session store there, rate limiter somewhere else. Never once had I sat down and asked: how fast can this thing actually go, on hardware I already own, with nothing exotic?</p><p>So, this weekend I did try. No cluster, no cloud bill, just my M5 Max, a local redis-server, and Python.</p><p>I started at <strong>12K writes/sec</strong>. That felt slow for something people call “in-memory.” I ended at <strong>3M writes/sec</strong> — two million keys landing in 0.65 seconds.</p><p><strong>251x</strong>. But that’s not really the story. The story is that halfway through, I almost published a number that was wrong, and figuring out <em>why</em> it was wrong taught me more than the optimization did.</p><h2>What I was actually testing</h2><p>Write 2 million keys — key:0 through key:1999999 — each with a small string value, into a local Redis instance. Persistence off (--save &#39;&#39; --appendonly no), because I wanted to isolate the write path and network path, not benchmark disk fsync. Every run does a flushdb first so nothing carries over.</p><p>Machine: Apple M5 Max, 6 efficiency cores + 12 performance cores, 128GB RAM. Redis 8.10.0. Python 3.13, redis-py 7.4.0.</p><p>Everything below is a median of three runs.</p><p>Quick sanity check before diving in: 2 million of these keys use 119MB in Redis. About 60 bytes per key once you include Redis’s own bookkeeping, for keys and values that are each under a dozen bytes. If you’re doing this math for a real dataset, that overhead adds up fast.</p><h2>Attempt 1: just loop and set it</h2><p>This is what I’d write on autopilot if someone asked me to “put some data in Redis”:</p><pre>r = redis.Redis(host=&quot;localhost&quot;, port=6379, db=0)<br>for i in range(N):<br>    r.set(f&quot;key:{i}&quot;, f&quot;value:{i}&quot;)</pre><pre>2,000,000 keys in 163.7780s  →  12,212 ops/s</pre><p>Two minutes and forty-four seconds. For a database that’s supposedly all in RAM. My first instinct was that Redis must be slow at this — until I actually thought about what that loop is doing.</p><p>Every single r.set() call opens a round-trip: write to the socket, block, wait for Redis to say +OK, come back, do it again. Two million times. At 81.9 microseconds per call, almost none of that time is Redis actually working — a SET on a real Redis server takes a fraction of a microsecond. What I was measuring was loopback latency and syscall overhead, over and over, one operation at a time.</p><p>Redis wasn’t my bottleneck. My loop was.</p><h2>Attempt 2: stop waiting after every command</h2><p>Here’s the thing that was actually killing me in Attempt 1: I wasn’t waiting on Redis, I was waiting on the <em>network round-trip</em>. Every r.set() sends bytes down the socket, then just sits there doing nothing until Redis&#39;s reply comes back. On localhost that round-trip is maybe 5-10 microseconds — tiny — but I was paying it two million separate times, back to back, with the client idle for the whole wait each time.</p><p><strong>Pipelining is the fix, and the idea is almost dumb-simple once you see it: stop waiting after each command.</strong> Instead of send → wait → send → wait → send → wait, you write several commands into the socket back-to-back with no waiting in between, and only <em>then</em> start reading the replies — which by that point are mostly already sitting in the buffer waiting for you.</p><pre>without pipelining                    with pipelining (batch of 3)<br>─────────────────────                 ──────────────────────────<br>client: SET a          ─┐             client: SET a  ─┐<br>        (wait for OK)    │                    SET b   │  all three<br>client: SET b            │ 3 round trips      SET c  ─┘  written at once<br>        (wait for OK)    │                    (wait for 3 replies)<br>client: SET c            │<br>        (wait for OK)   ─┘</pre><p>Nothing about <em>what</em> Redis does changes — it still executes three individual SET commands, in order, one after another. What changes is that your client isn’t burning time sitting idle between them. You’re trading three round-trips for one. This is redis-py’s pipeline(): it queues commands client-side and doesn&#39;t actually send anything over the wire until you call .execute().</p><pre>pipe = r.pipeline(transaction=False)<br>for i in range(N):<br>    pipe.set(f&quot;key:{i}&quot;, f&quot;value:{i}&quot;)<br>    if (i + 1) % 1000 == 0:<br>        pipe.execute()          # flush the queued batch — 1 round-trip for 1000 commands</pre><pre>2,000,000 keys in 7.5264s  →  265,730 ops/s</pre><p><strong>21.8x</strong>, and I hadn’t touched Redis at all. Same commands, same server. I just stopped waiting after each one.</p><p>(transaction=False because I don&#39;t need MULTI/EXEC atomicity for a bulk load, and there&#39;s no reason to pay for two extra commands per batch when I don&#39;t.)</p><h2>Attempt 3: stop sending so many commands</h2><p>Pipelining fixed the <em>waiting</em>, but look again at that diagram above — Redis is still parsing SET a, then SET b, then SET c, as three separate commands. I’d removed the idle time between them, but I hadn’t removed the commands themselves. 2 million keys meant two million individual SET commands for Redis to receive, parse, and reply to, no matter how efficiently I shipped them over the wire.</p><p>MSET attacks that other half of the problem: instead of SET key1 val1, SET key2 val2, SET key3 val3 as three commands, MSET key1 val1 key2 val2 key3 val3 is <strong>one command</strong> that sets all three at once.</p><pre>three SETs (three commands, three parses, three replies)<br>   SET a 1<br>   SET b 2<br>   SET c 3<br> <br>one MSET (one command, one parse, one reply — same three keys land)<br>   MSET a 1 b 2 c 3</pre><p>Same end state in Redis — three keys get written either way — but Redis only has to do the command-dispatch work (parse the command, look it up, send back a reply) once instead of three times. Stack this with pipelining and you’re compounding two different savings: MSET shrinks the <em>number</em> of commands, pipelining shrinks the <em>number</em> of round-trips those commands need.</p><pre>pipe = r.pipeline(transaction=False)<br>for base in range(0, N, 1000):<br>    pipe.mset({f&quot;key:{base+j}&quot;: f&quot;value:{base+j}&quot; for j in range(1000)})<br>pipe.execute()</pre><pre>2,000,000 keys in 2.4013s  →  832,897 ops/s</pre><p>Another <strong>3.1x</strong>. Now there are only 2,000 commands total, batched into one round-trip. Two multipliers stacked on top of each other: MSET cuts the command count by 1000x, pipelining cuts the round-trips to one.</p><h2>The sweep that taught me nothing (and that’s the point)</h2><p>Naturally I wanted to know: what’s the <em>ideal</em> number of keys to cram into one MSET? Too few and you’re back to lots of small commands. Too many and Redis has to chew through one giant command serially while your client holds a massive buffer. There has to be a sweet spot in the middle, right?</p><p>I swept it. Then, because the result looked suspiciously flat, I swept it again to see if it’d hold up.</p><pre>keys/MSET   #MSETs   time(s)      ops/s (run A)    ops/s (run B)<br>         1 2,000,000    6.74             296,522          292,151<br>        10   200,000    2.71             738,814          737,890<br>        50    40,000    2.44             820,331          826,507<br>       100    20,000    2.40             833,649          830,777<br>       500     4,000    2.42             827,182          831,746<br>     1,000     2,000    2.36             847,939          842,108<br>     5,000       400    2.33             858,775          860,633<br>    10,000       200    2.35             852,498          854,265<br>    50,000        40    2.34             854,937          858,579<br>   100,000        20    2.36             846,405          846,194</pre><p>There’s a real effect from 1 to 50 keys per MSET — 296K climbing to 820K, exactly the command-count amortization you’d expect. Past that, it’s flat. Everything from 50 to 100,000 keys per MSET sits in an 820K–860K band, a spread of about 5%, which is basically noise on a 2.3-second measurement.</p><p>My script dutifully printed best: 5,000 keys/MSET — both times, which almost fooled me into thinking it meant something. But 5,000 is within 1% of 10,000 and within 1% of 50,000. That&#39;s not a sweet spot, that&#39;s rounding error wearing a sweet spot&#39;s clothes. (At a smaller dataset size I&#39;d tested earlier, the same script picked a <em>different</em> &quot;best&quot; value on the second run. That&#39;s usually how you catch yourself — run it twice.)</p><p>I almost wrote a paragraph explaining <em>why</em> 5,000 was optimal. Glad I didn’t. A flat curve isn’t a failed experiment — it’s the data telling you that whatever you’re tuning isn’t what’s actually holding you back. Which sent me looking for what was.</p><h2>Attempt 4: stop asking one process to do it alone</h2><p>My working theory: the bottleneck had moved into Python itself. Building all those f-string keys and serializing the Redis wire protocol is CPU work, and it happens under the GIL — meaning threads wouldn’t help, but separate processes would.</p><pre>def worker(start_key, count, barrier):<br>    r = redis.Redis(host=&quot;localhost&quot;, port=6379, db=0)<br>    r.ping()                    # connect before the timed section<br>    barrier.wait()              # all workers start together<br>    pipe = r.pipeline(transaction=False)<br>    for base in range(start_key, start_key + count, 1000):<br>        pipe.mset({f&quot;key:{base+j}&quot;: f&quot;value:{base+j}&quot; for j in range(1000)})<br>    pipe.execute()</pre><p>Each of my 18 CPU cores gets its own process, its own Redis connection (they aren’t fork-safe to share), and a contiguous slice of the keyspace. I used a Barrier so every worker connects and is ready <em>before</em> the clock starts — I didn&#39;t want connection setup time leaking into my measurement.</p><pre>2,000,000 keys in 0.6511s  (3,071,677 ops/s)<br>2,000,000 keys in 0.6432s  (3,109,357 ops/s)<br>2,000,000 keys in 0.6511s  (3,071,780 ops/s)</pre><p><strong>3.07 million writes a second. 251x where I started. </strong>And that my friend is a<strong> </strong>headline number.</p><blockquote><strong>If I had to summarize what I actually walked away with, it’s less “here’s how to make Redis fast” and more: batch your round-trips before anything else, don’t trust a benchmark that finishes before you can blink, and measure your assumptions.</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78bd9f57e735" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is Redis so fast?]]></title>
            <link>https://medium.com/@arundobriyal_33904/why-is-redis-so-fast-f5ef416de27b?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5ef416de27b</guid>
            <category><![CDATA[memcached]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[message-broker]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 15:08:01 GMT</pubDate>
            <atom:updated>2025-04-23T15:08:01.999Z</atom:updated>
            <content:encoded><![CDATA[<p>𝗟𝗲𝘁’𝘀 𝗱𝗲𝗳𝗶𝗻𝗲 𝗳𝗮𝘀𝘁, are we talking about latency, throughput?</p><p>In the context of Redis, it means high read and write IOps. It’s not uncommon for one Redis node to do more than 100–500K write qps, and 500K-2M qps for reads.</p><p>𝗦𝗼 𝘄𝗵𝗮𝘁 𝗺𝗮𝗸𝗲𝘀 𝗥𝗲𝗱𝗶𝘀 𝗳𝗮𝘀𝘁?</p><p>* Redis is single threaded, which means that it’s inherently thread safe, doesn’t do context switching and doesn’t need synchronization overhead. This also means adding more CPU cores doesn’t speed it up.</p><p>* Redis is primarily in-memory (though it can be tweaked for persistence). All data is mutated and read in RAM. Main memory access is ~100ns. Sequential read from RAM is over 100 times faster than HDD.</p><p>𝗖𝗮𝗻 𝗥𝗲𝗱𝗶𝘀 𝗯𝗲 𝘁𝘄𝗲𝗮𝗸𝗲𝗱 𝘁𝗼 𝗽𝗲𝗿𝘀𝗶𝘀𝘁 𝗱𝗮𝘁𝗮?</p><p>Yes, Redis can be configured with fsync config to tweak how frequently it flushes data to the disk. Data is flushed in append-only file which is again a fast operation.</p><p>𝗖𝗮𝗻 𝗥𝗲𝗱𝗶𝘀 𝗯𝗲 𝘁𝘄𝗲𝗮𝗸𝗲𝗱 𝗶𝗻 𝗰𝗹𝘂𝘀𝘁𝗲𝗿 𝘀𝗲𝘁𝘂𝗽?</p><p>Yes, Redis can have multiple redis nodes in a cluster which will shard the key space using a hash slot algorithm. This enables to get higher read/write throughput, also increases fault tolerance with secondary replicas.</p><p>𝗗𝗼𝗲𝘀 𝗥𝗲𝗱𝗶𝘀 𝘀𝘂𝗽𝗽𝗼𝗿𝘁 𝘁𝗿𝗮𝗻𝘀𝗮𝗰𝘁𝗶𝗼𝗻𝘀?</p><p>Yes, can be done via either Lua scripts(registered and executed on Redis nodes, thus atomic) or using MULTI/EXEC/WATCH (this causes higher latench though because of round trip).</p><p>𝗦𝗼𝗺𝗲 𝗥𝗲𝗱𝗶𝘀 𝗱𝗮𝘁𝗮 𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝘀, showing its versatility:</p><p>* 𝙋𝙪𝙗-𝙨𝙪𝙗: used as a pure broadcast, has channels which can be subscribed by clients e.g. Live comments, webhooks, chat applications<br>* 𝙎𝙤𝙧𝙩𝙚𝙙 𝙨𝙚𝙩: A set which has a score, can act as distributed priority queue e.g. top K videos, sliding/token-bucket rate limiting.<br>* Set: Useful to know unique values at scale e.g. total video views, DAU<br>* 𝙍𝙚𝙙𝙞𝙨 𝙜𝙚𝙤: works on top of Redis sorted sets, does Geo spatial queries e.g. users/drivers/businesses near my lat/long<br>* 𝘿𝙞𝙨𝙩𝙧𝙞𝙗𝙪𝙩𝙚𝙙 𝙡𝙤𝙘𝙠𝙨: can be done via SET ns ex, basically a key is only created if it doesn’t exist. Alternatively can be done via Redlocks for resilience across nodes.<br>* 𝙃𝙖𝙨𝙝: to store dictionaries<br>* 𝙋𝙧𝙤𝙗𝙖𝙗𝙞𝙡𝙞𝙨𝙩𝙞𝙘 𝙙𝙖𝙩𝙖 𝙨𝙩𝙧𝙪𝙘𝙩𝙪𝙧𝙚𝙨 like Count min sketch and Hyperloglog, to find approximate (with an error tolerance of &lt;.5%) Total count and Unique counts at scale. <br>* 𝙇𝙞𝙨𝙩/𝙌𝙪𝙚𝙪𝙚: to support distributed queues e.g. storing tasks to be done.</p><p>𝗜𝗳 𝗥𝗲𝗱𝗶𝘀 𝗶𝘀 𝘀𝗼 𝗽𝗼𝘄𝗲𝗿𝗳𝘂𝗹, 𝘄𝗵𝘆 𝗱𝗼 𝗗𝗮𝘁𝗮𝗯𝗮𝘀𝗲𝘀 𝘀𝘁𝗶𝗹𝗹 𝗲𝘅𝗶𝘀𝘁?</p><p>Because Redis is not as durable as a regular DB, which of course comes at a tradeoff of lower write/read qps. One can do fsync=all in Redis to persist every update much like any DB does but that compromises high throughput that Redis is known for.</p><p>Armed with this info, if you are working on your next project, do consider Redis.<br>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5ef416de27b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model Context Protocol and how it works]]></title>
            <link>https://medium.com/@arundobriyal_33904/model-context-protocol-and-how-it-works-3e33de5a9e7e?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e33de5a9e7e</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 16:09:03 GMT</pubDate>
            <atom:updated>2025-04-15T16:09:46.752Z</atom:updated>
            <content:encoded><![CDATA[<p>Anthropic recently launched Model Context Protocol, which has led to a lot of frenzy. Thist post is set out to explain how it works.</p><p>I have seen a lot of hyperboles around its capability, causing a lot of FOMO, so hopefully this post helps you understand how it works and inspires you to create and integrate your own use cases. Also, like all of my posts, I will share an easy to understand example for comprehensibility.</p><p>𝗙𝗶𝗿𝘀𝘁, 𝘄𝗵𝘆 𝗱𝗼𝗲𝘀 𝗠𝗖𝗣 𝗲𝘅𝗶𝘀𝘁? For anyone using LLMs, a very common problem has been to identify when/how to call your backend service e.g. query data from db or call remote endpoints.</p><p>𝗧𝗵𝗲 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻𝘀 that I have seen for this have been to structure the prompts in a way that helps your business logic to know when to call these resources. It’s often monkey patched by using multiple prompts, and doesn’t scale as usecases expand.</p><p>𝗠𝗖𝗣 𝘀𝗲𝘁𝘀 𝗼𝘂𝘁 𝘁𝗼 𝘀𝘁𝗮𝗻𝗱𝗮𝗿𝗱𝗶𝘇𝗲 this by enforcing an abstraction called MCP servers (think backend apis which does a certain action) and then letting you register those in your LLM Host (e.g. Claude/ChatGPT Desktop). You also provide context on what your MCP server does. Once done, if a user query comes, &amp; if your LLM finds out that the response can be served by calling MCP server, it does via a standardized interface.</p><p>Its expected that all LLMs with adopt MCP, and it becomes the standard interface to query resources.</p><p>𝗟𝗲𝘁’𝘀 𝘁𝗮𝗸𝗲 𝗮𝗻 𝗲𝘅𝗮𝗺𝗽𝗹𝗲:<br>* Let’s say you have an LLM host like Claude desktop &amp; you want to find out the weather for different cities in the USA.<br>* Now this info is not available to Claude or any other LLM, but can be obtained by NPS weather service. <br>* So how do we modify Claude Desktop to find this info?</p><p>𝗪𝗲 𝘀𝗼𝗹𝘃𝗲 𝗶𝘁 𝗯𝘆 creating a MCP server that finds and returns this info.</p><p>In this setup, 𝗠𝗖𝗣 𝗵𝗼𝘀𝘁 𝗶𝘀 𝗖𝗹𝗮𝘂𝗱𝗲/<strong>ChatGPT</strong> Desktop app which you are interacting with as a user. 𝗠𝗖𝗣 𝘀𝗲𝗿𝘃𝗲𝗿 𝗶𝘀 𝗴𝗼𝗶𝗻𝗴 𝘁𝗼 𝗯𝗲 𝘆𝗼𝘂𝗿 𝘀𝗲𝗿𝘃𝗲𝗿 which exposes an api(much like a REST api server) to get the weather info. It gets this info by calling the nps weather service. So MCP server here acts as an abstraction on top of weather service, but you can think of other abstractions too e.g. querying google drive, querying postgres db, using boto to query S3, calling stripe via REST etc.</p><p>Once MCP server is built, 𝘆𝗼𝘂 𝗯𝘂𝗶𝗹𝗱 𝗮 𝗷𝘀𝗼𝗻 𝗳𝗶𝗹𝗲 that explains what is the location of the code for MCP server and how your LLM should run this server. MCP servers runs like a typical application server and listens on a 𝗧𝗖𝗣 𝗽𝗼𝗿𝘁. You restart your Claude desktop to have the 𝗿𝗲𝗴𝗶𝘀𝘁𝗿𝗮𝘁𝗶𝗼𝗻 be picked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*uQ05j0CMxIlfz-eOp4P5mA.jpeg" /></figure><p>Now, if you type and ask Claude the weather in San Francisco, it will look at MCP servers registered with it, it knows that one of the MCP servers can find out the weather info, so invokes it, gets the weather response and formulates a natural language response back to user.</p><p>If 𝘆𝗼𝘂 𝘄𝗮𝗻𝘁 𝘁𝗼 𝘀𝗲𝗲 𝗮 𝗰𝗼𝗱𝗲 for this example, check out</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e33de5a9e7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two tower model for Content basse]]></title>
            <link>https://medium.com/@arundobriyal_33904/two-tower-model-for-content-basse-624ca12478f3?source=rss-6baf11c0707e------2</link>
            <guid isPermaLink="false">https://medium.com/p/624ca12478f3</guid>
            <category><![CDATA[ránking]]></category>
            <category><![CDATA[two-tower-model]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Arun Dobriyal]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 17:55:05 GMT</pubDate>
            <atom:updated>2025-03-20T17:55:27.407Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two towers model for Content based Ranking with examples</h3><p>How does Two tower model in Content ranking (used by the likes of Meta, Youtube, Netflix, Amazon, Snap, TikTok) work?</p><p>At its heart, it relies on two separate towers of embeddings to find the most similar vector embeddings. Some real life examples:<br>* Query tower &amp; Document tower, in the case of Google search.<br>* Query Tower &amp; Product tower, in the case of Amazon.<br>* User Tower &amp; Video tower, in the case of Snap or Tiktok or IG Reels.<br>* User Tower &amp; Places tower, in the case of Airbnb.</p><p>To understand how the Two tower works, let’s go through a very naive but very pragmatic example.</p><p>𝗡𝗼𝗼𝗯 𝗧𝘄𝗼 𝘁𝗼𝘄𝗲𝗿𝘀: <br>Imagine that you have been tasked with designing Youtube recommendations. We have a list of user’s past watched videos, and are trying to recommend the videos that the user is most likely to interact with:</p><p>* First tower: User’s past N watched videos can be first used to create an averaged vector embeddings, symbolizing the content affinity that a user has.</p><p>* Second tower: Whole Youtube video corpus which is stored in some vector database e.g. pgvector in Postgres / Open search / Chroma DB / Elasticearch.</p><p>* Candidate retrieval: You employ ANN(approx. nearest neighbor with cosine similarity) to prune through billions of vector embeddings very efficiently to find the videos with most similar vector embeddings. We can’t use k-NN (which is accurate) because it’s very expensive to do with billions of vector embeddings.</p><p>* Reranking: Retrieved candidates are finally re-ranked with user based features to form a fully personalized feed.</p><p>So how do we take this approach a notch higher, and make it more real world?</p><p>𝗧𝘄𝗼 𝘁𝗼𝘄𝗲𝗿𝘀 𝗮𝘀 𝘀𝗲𝗲𝗻 𝗶𝗻 𝗺𝗼𝘀𝘁 𝘀𝘁𝗮𝘁𝗲 𝗼𝗳 𝗮𝗿𝘁 𝗥𝗮𝗻𝗸𝗶𝗻𝗴 𝘀𝘆𝘀𝘁𝗲𝗺𝘀:<br>We will take an example of Amazon product search to illustrate it. We also assume that we have access to labeled data (Sample queries and ideal Product response).</p><p>* Our first tower is the Query tower which would be converted into a reshaped lesser dimension vector embedding using a sentence embedding like BERT. Reshaping is important because BERT produces very sparse 768 dimensional embedding and impractical to use for generating dense embeddings.</p><p>* For our second tower, we use product features like product name, description, sku which can be flattened and reshaped into a lesser dimensional vector embedding.</p><p>* Since the Query and Product vectors have mismatched dimensions, it’s essential to pass it through a dense Neural network layer trained with the training dataset. After this step, both set of embeddings have same number of dimensions, and the embeddings have lot more context baked into them.</p><p>* Last step is to again employ ANN and do reranking to get a Product response feed that is very relevant to the input query.</p><p>Similarly, this Two tower approach can be transposed to other Content based ranking scenarios as well.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=624ca12478f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>