<?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 Srivatsa.k on Medium]]></title>
        <description><![CDATA[Stories by Srivatsa.k on Medium]]></description>
        <link>https://medium.com/@srivatsa4123?source=rss-150d91553aea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aCh1vKdWExF898nD</url>
            <title>Stories by Srivatsa.k on Medium</title>
            <link>https://medium.com/@srivatsa4123?source=rss-150d91553aea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:30:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srivatsa4123/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[Prompt Caching Is a Layout Discipline, Not a Feature Flag]]></title>
            <link>https://medium.com/@srivatsa4123/prompt-caching-is-a-layout-discipline-not-a-feature-flag-0684c48feed1?source=rss-150d91553aea------2</link>
            <guid isPermaLink="false">https://medium.com/p/0684c48feed1</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[prompt-caching]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <dc:creator><![CDATA[Srivatsa.k]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 15:41:00 GMT</pubDate>
            <atom:updated>2026-07-14T15:41:00.970Z</atom:updated>
            <content:encoded><![CDATA[<p>How to cut LLM cost and latency by structuring your prompt — and when caching will quietly cost you more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v0i8QlBxAioXqhfE.png" /></figure><p>If you run an LLM-backed product at any real volume, a big slice of your bill and latency goes to re-reading text the model has already seen: your system prompt — persona, rules, tool definitions — is nearly identical on every request, yet it’s re-processed every time. Prompt caching fixes this, but it’s not a switch you flip. Turn it “on” while laying your prompt out wrong and you get a cache that never hits — all the complexity, none of the savings, and sometimes a bill <em>higher</em> than not caching at all.</p><h3>A quick note on providers</h3><p>Caching comes in two flavors, which change <em>how</em> you turn it on but not <em>what makes it work</em>:</p><ul><li><strong>Explicit / opt-in</strong> (Anthropic’s Claude): you mark what gets cached. Precise control, but you opt into a small write cost.</li><li><strong>Automatic / implicit</strong> (OpenAI): the provider caches for you — no code changes and no write cost, but no explicit control over the boundary.</li></ul><p>The examples below use Anthropic and OpenAI, the two you’re most likely running. (Gemini offers both models; everything here still applies.) Discounts and lifetimes change, so treat the figures as ballparks and check the provider’s pricing page.</p><p>The one idea to hold onto: <strong>whether caching is explicit or automatic, it only works on a stable prefix.</strong> Both match from the very start of the prompt — so the layout discipline below applies identically to both.</p><h3>What prompt caching actually is</h3><p>The model must process every input token before it can respond — and your system prompt is nearly identical every request. Prompt caching lets the provider <strong>store the processed state of a prefix</strong> and reuse it on later requests that start with the exact same prefix. On a hit:</p><ul><li><strong>Cost drops.</strong> On Claude, cache reads are roughly <strong>10% of the normal input price</strong>; on OpenAI, cached tokens are discounted too (the rate varies by model).</li><li><strong>Latency drops.</strong> The model skips re-prefilling the cached prefix, so time-to-first-token falls — often dramatically for long prompts.</li></ul><p>One constraint governs everything else:</p><blockquote><strong><em>Caching only works on an exact, stable prefix.</em></strong><em> It’s matched from the very start of the prompt. The moment one byte changes, everything from that byte onward is a cache miss.</em></blockquote><h3>Two ways it gets turned on</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6C95En6SSdmPf5szsqeIA.png" /></figure><blockquote><strong><em>Verify the numbers for your model.</em></strong><em> Minimums, discounts, and TTLs vary by model and change over time. Check the source: Anthropic’s </em><a href="https://docs.claude.com/en/docs/build-with-claude/prompt-caching"><em>prompt caching guide</em></a><em>, OpenAI’s </em><a href="https://platform.openai.com/docs/guides/prompt-caching"><em>prompt caching guide</em></a><em>, and Google’s </em><a href="https://ai.google.dev/gemini-api/docs/caching"><em>Gemini context caching docs</em></a><em>.</em></blockquote><p>Read the bottom row twice: the mechanics differ; the discipline is identical. (Gemini fits both — automatic out of the box, plus optional explicit caching where you save a stable chunk and reuse it by name. Still prefix-based.)</p><h3>Anthropic: you draw the boundary</h3><p>With Claude, a cache_control marker makes everything up to and including that block cacheable:</p><pre>response = client.messages.create(<br>    model=&quot;claude-sonnet-4-6&quot;,<br>    system=[<br>        {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: LONG_STABLE_SYSTEM_PROMPT,        # persona, rules, format spec<br>            &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;},   # &lt;-- cache up to here<br>        },<br>    ],<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input}],<br>)</pre><p>On the first call you pay a small surcharge to <em>write</em> the cache (~25% over normal input price); every later call within the ~5-minute lifetime reads that prefix back at the ~10% rate, and each hit refreshes the timer.</p><p><strong>Rule of thumb:</strong> the 5-minute cache pays for itself on the second repeat request; the pricier 1-hour cache needs a third. OpenAI has no write surcharge, so any hit is a win.</p><h3>OpenAI: the provider draws it for you</h3><p>With OpenAI there’s no marker and no flag: for any prompt over ~1,024 tokens, the platform automatically reuses the longest matching prefix it has already processed, and a miss simply costs the normal price. There’s no code to add — pass an optional prompt_cache_key and read usage...cached_tokens to confirm hits. Your only real lever is the <em>shape</em> of the prompt: make sure the stable material actually forms a stable prefix — which is the discipline the next sections are about.</p><h3>The mistake almost everyone makes</h3><p>The natural way to build a chat-agent system prompt — and it’s wrong, on <strong>both</strong> providers:</p><pre>system_prompt = f&quot;&quot;&quot;<br>You are {persona}.<br>Current step: {current_step}          # &lt;-- changes every turn<br>Known user details: {user_profile}    # &lt;-- changes every turn<br>Previous state: {previous_state}      # &lt;-- changes every turn<br>{the_long_static_rulebook}<br>{tool_definitions}<br>&quot;&quot;&quot;</pre><p>It reads fine. It also defeats the cache completely. current_step, user_profile, and previous_state change every turn, and because they sit near the <strong>top</strong> of the prompt, the prefix differs on every request. On Anthropic the hit rate is zero and you pay the write surcharge for nothing; on OpenAI the matcher finds no reusable prefix and you simply never get the discount. Either way the savings never materialize — because they depend on <strong>layout</strong>, not the flag.</p><h3>The fix: order your prompt by volatility</h3><p>Stop organizing your prompt by <em>topic</em> and start organizing by <em>how often each part changes</em>. Stable material first, cache boundary after it, volatile material last.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9fOEWqTfZyl_mWH9.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FO9QnNWSYjY9OnPu.png" /></figure><p>The same prompt, laid out correctly for Anthropic:</p><pre>system=[x<br>    {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;text&quot;: PERSONA_AND_RULEBOOK,            # stable: never changes per turn<br>    },<br>    {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;text&quot;: active_role_instructions,        # semi-stable: changes only on role switch<br>        &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;},  # &lt;-- cache boundary AFTER the stable part<br>    },<br>]<br># Everything volatile goes in the user message, NOT the system prompt:<br>messages=[<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: (<br>            f&quot;Current step: {current_step}\n&quot;<br>            f&quot;Known user details: {user_profile}\n\n&quot;<br>            f&quot;{user_input}&quot;<br>        ),<br>    },<br>]</pre><p>On OpenAI it’s the same layout with the marker removed — stable text in instructions, volatile text in input, and the automatic matcher does the rest.</p><p>Two rules do all the work:</p><ol><li><strong>Order from least-volatile to most-volatile,</strong> so the cacheable prefix stays byte-identical and hits every time after the first.</li><li><strong>Exile per-request data into the user message</strong> — it’s naturally different every turn and naturally uncached, the correct home for anything dynamic.</li></ol><p>Follow those and your hit rate jumps from ~0% to near-100% after the first request.</p><h3>When you should NOT cache</h3><p>The part the “turn on caching!” posts skip. On an explicit provider like Anthropic, caching costs something — the write surcharge — and it isn’t always recovered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zblMecu8CWtP0sXG.png" /></figure><p>Skip caching (or don’t count on it) when:</p><ul><li><strong>The prompt is short</strong> — below the ~1,024–2,048-token minimum (model-dependent), the marker does nothing.</li><li><strong>It’s a one-shot call</strong> — caching only pays back on reuse; sent once, you pay the surcharge and collect nothing.</li><li><strong>Traffic is too sparse for the TTL</strong> — if requests for a prefix arrive more than ~5 minutes apart, every call re-writes and never reads.</li><li><strong>The prefix genuinely churns</strong> — no stable chunk above the minimum means there’s nothing to cache.</li></ul><p>On OpenAI the downside is milder: with no write surcharge you don’t <em>lose</em> money, you just don’t <em>save</em> any. The remedy is the same either way — get more stable material into a longer, stabler prefix, or accept this workload isn’t a caching candidate.</p><h3>Don’t trust it — measure it</h3><p>Because caching depends on layout, it’s easy to <em>believe</em> it’s working when it isn’t. Verify with the token counts the provider returns.</p><p>Claude reports two numbers — cache_creation_input_tokens (written, surcharged) and cache_read_input_tokens (served from cache, discounted). A healthy prompt shows a burst of creation on the first call, then mostly reads. Creation on every call with reads near zero means your prefix is unstable — something volatile crept above the boundary.</p><pre>usage = response.usage<br>print(&quot;cache_creation:&quot;, usage.cache_creation_input_tokens)  # surcharged write path<br>print(&quot;cache_read:    &quot;, usage.cache_read_input_tokens)      # discounted read path</pre><p>OpenAI reports a single cached-token count, since writes are free:</p><pre>print(&quot;cached:&quot;, response.usage.input_tokens_details.cached_tokens)</pre><p>Track the creation-vs-read ratio (or cached-token share) in your metrics. Don’t assume.</p><h3>The takeaway</h3><p>Prompt caching isn’t a flag you flip — it’s a way of <strong>laying out your prompt</strong>, whether your provider makes you draw the boundary (Anthropic) or draws it for you (OpenAI):</p><ol><li>Order content from least-volatile to most-volatile.</li><li>Put the cache boundary after the stable part.</li><li>Push every per-request value into the user message.</li><li>Don’t count on caching for short, one-shot, or sparsely-repeated prompts.</li><li>Verify with the provider’s cache token counts. Never assume.</li></ol><p>Get the layout right and a large, repetitive system prompt goes from a per-request tax to a near-free, fast-to-process asset. Get it wrong and you’ve added complexity — and, on some providers, cost — for a cache that never hits. The difference is entirely in the structure. So structure it on purpose.</p><p>If you’d like a more detailed version of this with the full breakeven math, multi-provider nuances, and measurement gotchas, <a href="https://medium.com/@srivatsa4123/prompt-caching-is-a-layout-discipline-not-a-feature-flag-374a711ac01b">you can check this blog</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0684c48feed1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Caching Is a Layout Discipline, Not a Feature Flag]]></title>
            <link>https://medium.com/@srivatsa4123/prompt-caching-is-a-layout-discipline-not-a-feature-flag-374a711ac01b?source=rss-150d91553aea------2</link>
            <guid isPermaLink="false">https://medium.com/p/374a711ac01b</guid>
            <category><![CDATA[prompt-caching]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Srivatsa.k]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 10:07:52 GMT</pubDate>
            <atom:updated>2026-07-14T07:09:15.813Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to cut LLM cost and latency by structuring your prompt — and when caching will quietly cost you more.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhYVY5JJ8FZ2FuiOJSoIkQ.png" /></figure><p>If you run an LLM-backed product at any real volume, a large slice of your bill and your latency is spent re-reading text the model has already seen. Your system prompt — the persona, the rules, the tool definitions — is mostly identical on every single request. The model dutifully re-processes all of it, every time, and you pay for the privilege.</p><p>Prompt caching fixes this. But it’s not a switch you flip. Turning it “on” while laying your prompt out the wrong way gets you a cache that never hits — all of the complexity, none of the savings. And in some cases, caching actively costs <em>more</em> than not caching.</p><p>This post covers what prompt caching really is, how the two big providers differ, how to lay out a prompt so the cache actually works, the one mistake almost everyone makes, and — the part most articles skip — when you should <strong>not</strong> cache.</p><h3>A quick note on providers</h3><p>Caching exists in two flavors, and which one you’re using changes <em>how</em> you turn it on but not <em>what makes it work</em>:</p><ul><li><strong>Explicit / opt-in</strong> (Anthropic’s Claude): you decide what gets cached by placing a marker in the prompt. You get precise control, but you also opt into a small write cost.</li><li><strong>Automatic / implicit</strong> (OpenAI): the provider caches for you, with no code changes. There’s nothing to switch on and no write cost — but you also have no explicit control over the boundary.</li></ul><p>This post uses <strong>Anthropic and OpenAI</strong> for the concrete examples, since they’re the two you’re most likely to be running. The underlying principle is provider-agnostic — other providers implement one of these two models, and everything here transfers. (Google Gemini is a mild exception in that it offers both — more on that once the two models are clear.) Figures like discounts and cache lifetimes are current at the time of writing and do change, so treat them as ballparks and check the provider’s pricing page for exact numbers.</p><p>The one idea to hold onto: <strong>whether caching is explicit or automatic, it only works on a stable prefix.</strong> The provider decides what’s cached differently, but <em>both</em> match from the very start of the prompt. So the layout discipline below applies identically to both.</p><h3>What prompt caching actually is</h3><p>When you send a prompt, the model can’t generate anything until it has processed every input token — tokenizing it and running attention across the whole sequence. That processing is the “prefill” phase, and it’s a real chunk of both your cost and your time-to-first-token.</p><p>Prompt caching lets the provider <strong>store the processed internal state of a prefix of your prompt</strong> and reuse it on later requests that start with the exact same prefix. On a cache hit:</p><ul><li><strong>Cost drops.</strong> Cached input tokens are billed at a steep discount — on Claude, cache reads are roughly <strong>10% of the normal input token price</strong>; on OpenAI, cached input tokens are discounted too (the exact rate varies by model).</li><li><strong>Latency drops.</strong> The model skips re-prefilling the cached prefix, so time-to-first-token falls — often dramatically for long prompts.</li></ul><p>There’s one constraint that governs everything else:</p><blockquote><strong><em>Caching only works on an exact, stable prefix.</em></strong><em> The cache is matched from the very start of the prompt. The moment one byte changes, everything from that byte onward is a cache miss.</em></blockquote><p>Hold onto that sentence. Every rule that follows is a consequence of it.</p><h3>Two ways it gets turned on</h3><p>Here’s how the two models compare in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6C95En6SSdmPf5szsqeIA.png" /></figure><blockquote><strong><em>Verify the numbers for your model.</em></strong><em> Minimums, discounts, and TTLs vary by model and change over time. Confirm against the source before you rely on them: Anthropic’s </em><a href="https://docs.claude.com/en/docs/build-with-claude/prompt-caching"><em>prompt caching guide</em></a><em> and </em><a href="https://docs.claude.com/en/docs/about-claude/pricing"><em>pricing</em></a><em>, OpenAI’s </em><a href="https://platform.openai.com/docs/guides/prompt-caching"><em>prompt caching guide</em></a><em>, and Google’s </em><a href="https://ai.google.dev/gemini-api/docs/caching"><em>Gemini context caching docs</em></a><em>.</em></blockquote><p>Read the bottom row twice. The mechanics differ; the discipline is identical.</p><p><strong>Where does Gemini fit?</strong> It offers both. Its newer models do OpenAI-style automatic caching out of the box, and it <em>also</em> lets you cache on purpose like Anthropic — the only real difference being that you save a stable chunk once and reuse it by name, rather than marking it inline each call. Either way it’s still prefix-based, so everything below applies to Gemini too.</p><h3>Anthropic: you draw the boundary</h3><p>With Claude, you mark a cache breakpoint with cache_control on a content block. Everything up to and including that block becomes cacheable:</p><pre>response = client.messages.create(<br>    model=&quot;claude-sonnet-4-6&quot;,<br>    system=[<br>        {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: LONG_STABLE_SYSTEM_PROMPT,        # persona, rules, format spec<br>            &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;},   # &lt;-- cache up to here<br>        },<br>    ],<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input}],<br>)</pre><p>On the first call you pay a small surcharge to <em>write</em> the cache (~25% over the normal input price). On every subsequent call within the cache lifetime, that prefix is read back at the ~10% rate. The default cache lifetime is short — about <strong>5 minutes</strong>, refreshed each time it’s hit — so caching pays off when requests come in close together.</p><p><strong>How many hits before it pays off?</strong> Because that first write costs <em>more</em> than a plain request, a single call with no reuse is a straight loss — you paid the surcharge and never collected a discounted read. You only come out ahead once the reads have earned back the surcharge. Comparing the cost of the <em>prefix</em> across R matching requests (the volatile part costs the same either way, so it cancels out):</p><ul><li>No caching: R × 1.0 (full price every time).</li><li>Caching: 1.25 for the one write, then (R − 1) × 0.10 for the reads.</li></ul><p>Caching wins when 1.25 + 0.10·(R − 1) &lt; R, which solves to R &gt; 1.28. In plain terms: <strong>you break even on the second matching request</strong> — a single reuse (one write + one read = 1.25 + 0.10 = 1.35×) already beats two full-price calls (2.0×). The optional 1-hour cache writes at ~2× instead, so its threshold is R &gt; (2.0 − 0.10) / (1 − 0.10) = 2.11 — you need <strong>the third request</strong> (two reuses) before it pays off. Generally: cache wins once R &gt; (write_multiplier − read_multiplier) / (1 − read_multiplier). If you can&#39;t clear that within the cache window — a one-shot call, or traffic too sparse to land the next hit in time — don&#39;t cache; you&#39;ll only pay the surcharge with nothing to collect. (On OpenAI there&#39;s no write surcharge, so there&#39;s no breakeven to clear — any hit is pure upside.)</p><p>That’s the whole API surface. The hard part isn’t the call. It’s what you put before the breakpoint.</p><h3>OpenAI: the provider draws it for you</h3><p>With OpenAI, there’s no marker and no flag. For any prompt over ~1,024 tokens on a supported model, the platform automatically looks for the <strong>longest matching prefix</strong> it has already processed (in ~128-token increments beyond the first 1,024) and serves it from cache. You don’t opt in, and there’s no write surcharge — a cache miss simply costs the normal price.</p><p>Because it’s automatic, the only lever you have is the <em>shape</em> of your prompt and, optionally, a routing hint so that identical prefixes are more likely to land on the same cache:</p><pre>response = client.responses.create(<br>    model=&quot;gpt-4o&quot;,<br>    instructions=LONG_STABLE_SYSTEM_PROMPT,   # persona, rules, format spec — stable, goes first<br>    input=user_input,                         # volatile, goes last<br>    prompt_cache_key=&quot;chat-agent-v3&quot;,         # optional: nudges identical prefixes onto the same cache<br>)<br><br># The cache hit shows up here — no separate &quot;creation&quot; counter, because writes are free:<br>cached = response.usage.input_tokens_details.cached_tokens<br>print(&quot;cached tokens:&quot;, cached)</pre><p>The key mental adjustment: with OpenAI you can’t <em>make</em> something cache, and you can’t <em>stop</em> it either. All you can do is make sure the stable material really is a stable prefix — which is exactly the discipline the next sections are about.</p><h3>The mistake almost everyone makes</h3><p>Here’s the natural, intuitive way to build a system prompt for a chat agent — and it’s wrong, on <strong>both</strong> providers:</p><pre>system_prompt = f&quot;&quot;&quot;<br>You are {persona}.<br>Current step: {current_step}          # &lt;-- changes every turn<br>Known user details: {user_profile}    # &lt;-- changes every turn<br>Previous state: {previous_state}      # &lt;-- changes every turn<br>{the_long_static_rulebook}<br>{tool_definitions}<br>&quot;&quot;&quot;</pre><p>It reads fine. It also defeats the cache completely.</p><p>current_step, user_profile, and previous_state change on <strong>every turn</strong>. Because they sit near the <strong>top</strong> of the prompt — inside the cacheable prefix — the prefix is different every single request.</p><ul><li>On <strong>Anthropic</strong>, the cache is technically enabled but the hit rate is zero: you pay the cache-write surcharge on every call and never collect the read discount. You’ve made it slightly <em>more</em> expensive than doing nothing.</li><li>On <strong>OpenAI</strong>, there’s no surcharge to lose, but the automatic matcher finds no reusable prefix, so you simply never get the discount. The feature is “on,” and it does nothing.</li></ul><p>Either way, the savings never materialize — because they depend entirely on prompt <strong>layout</strong>, not on the flag.</p><h3>The fix: order your prompt by volatility</h3><p>The mental shift is to stop organizing your prompt by <em>topic</em> and start organizing it by <em>how often each part changes</em>. Put the stable material first, draw the cache boundary after it (explicitly on Anthropic, implicitly on OpenAI), and let the volatile material come last.</p><p>Think in three tiers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wp8ehf9ZLhKK87sGK_4BqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99Hjz5ula9JTRHyg6foiWQ.png" /></figure><p>The same prompt, laid out correctly for Anthropic:</p><pre>system=[<br>    {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;text&quot;: PERSONA_AND_RULEBOOK,            # stable: never changes per turn<br>    },<br>    {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;text&quot;: active_role_instructions,        # semi-stable: changes only on role switch<br>        &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;},  # &lt;-- cache boundary AFTER the stable part<br>    },<br>]<br># Everything volatile goes in the user message, NOT the system prompt:<br>messages=[<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: (<br>            f&quot;Current step: {current_step}\n&quot;<br>            f&quot;Known user details: {user_profile}\n\n&quot;<br>            f&quot;{user_input}&quot;<br>        ),<br>    },<br>]</pre><p>On OpenAI it’s the same layout with the marker removed — the stable text goes in instructions (or the leading system message), the volatile text goes in input, and the automatic matcher does the rest.</p><p>Two rules do all the work, on either provider:</p><ol><li><strong>Order from least-volatile to most-volatile.</strong> The cacheable prefix stays byte-identical across requests, so it hits every time after the first.</li><li><strong>Exile per-request data into the user message.</strong> The user message is naturally different every turn and naturally uncached — it’s the <em>correct</em> home for anything dynamic. Keeping it out of the system prompt is what protects the prefix.</li></ol><p>Follow those two and your hit rate jumps from ~0% to near-100% after the first request (until the semi-stable tier changes, which only re-caches that smaller chunk).</p><h3>When you should NOT cache</h3><p>This is the part the “turn on caching!” posts leave out. On an explicit-control provider like Anthropic, caching has a real cost — the write surcharge — and it isn’t always recovered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZLV2G8YogOgrL_VfNoq6Q.png" /></figure><p>Skip caching (or at least don’t count on it) when:</p><ul><li><strong>The prompt is short.</strong> Providers enforce a minimum cacheable size (on the order of 1,024–2,048 tokens, depending on the model). Below that, the marker does nothing. Even just above it, the savings are tiny. Don’t bother caching a 200-token prompt.</li><li><strong>It’s a one-shot call.</strong> Caching only pays back on <em>reuse</em>. If a prompt is sent once and never repeated within the cache window, on Anthropic you pay the ~25% write surcharge and never collect a single discounted read — a straight loss. As the breakeven math above shows, you need at least the second matching request (the third for the 1-hour cache) before caching is net-positive. One-off batch jobs, single-shot classifications, and ad-hoc calls shouldn’t be cached.</li><li><strong>Traffic is too sparse for the TTL.</strong> The ephemeral cache lives ~5 minutes. If your requests for a given prefix arrive further apart than that, every call re-writes the cache and never reads it — again, pure surcharge, no payoff. Caching rewards bursty, high-frequency traffic, not a trickle.</li><li><strong>The prefix genuinely churns.</strong> If there’s no meaningfully stable chunk above the minimum size — every request really is different from the first token — there’s nothing to cache. Forcing a breakpoint just adds write overhead.</li></ul><p><strong>A note on the automatic case.</strong> Because OpenAI’s caching has no write surcharge, the downside of getting this wrong is milder: you don’t <em>lose</em> money, you just don’t <em>save</em> any. There’s nothing to switch off and no penalty to avoid — so on OpenAI the list above isn’t about restraint, it’s simply a description of the situations where caching can’t help you. The remedy is the same either way: get more stable material into a longer, stabler prefix, or accept that this particular workload isn’t a caching candidate.</p><p>The rule of thumb for explicit caching: <strong>cache a prefix only if it’s (a) large enough to clear the minimum, (b) stable across requests, and © reused frequently enough to land within the cache lifetime.</strong> Miss any of the three and you’re paying for a feature that costs you money.</p><h3>Don’t trust it — measure it</h3><p>Because caching depends on layout, it’s easy to <em>believe</em> it’s working when it isn’t. Verify with the token counts the provider returns.</p><p>Claude reports two distinct numbers:</p><ul><li>cache_creation_input_tokens — tokens written to the cache (the surcharged path).</li><li>cache_read_input_tokens — tokens served from cache (the discounted path).</li></ul><p>A healthy, well-laid-out prompt shows a burst of <strong>creation</strong> on the first call, then mostly <strong>reads</strong> afterward. If you see creation on every call and reads near zero, your prefix is unstable — something volatile crept above the cache boundary.</p><pre>usage = response.usage<br>print(&quot;cache_creation:&quot;, usage.cache_creation_input_tokens)  # surcharged write path (Anthropic)<br>print(&quot;cache_read:    &quot;, usage.cache_read_input_tokens)      # discounted read path (Anthropic)</pre><p>OpenAI reports a single cached-token count, because writes are free and there’s no creation event to bill:</p><pre># OpenAI: only a &quot;cached&quot; count — a read-hit measure.<br>print(&quot;cached:&quot;, response.usage.input_tokens_details.cached_tokens)</pre><p>That difference matters if you support multiple providers. Model “not reported” <em>distinctly</em> from “zero” in your own metrics (e.g. int | None, not int). Anthropic emits creation and reads as separate counters; OpenAI&#39;s automatic caching has no creation event at all. If you collapse &quot;unreported&quot; into 0, your cache-hit dashboard will quietly lie the moment you switch providers.</p><pre># Model absence as None, not 0 — otherwise an automatic-caching provider<br># (no creation event) makes your hit-rate dashboard silently misreport.<br>cache_read: int | None = getattr(usage, &quot;cache_read_input_tokens&quot;, None)</pre><p>Track the creation-vs-read ratio (or the cached-token share) in your metrics. Don’t assume.</p><h3>The takeaway</h3><p>Prompt caching isn’t a flag you flip — it’s a way of <strong>laying out your prompt</strong>, and that’s true whether your provider makes you draw the boundary (Anthropic) or draws it for you (OpenAI):</p><ol><li>Order content from least-volatile to most-volatile.</li><li>Put the cache boundary after the stable part — explicitly, or by letting the automatic matcher find it.</li><li>Push every per-request value into the user message.</li><li>Don’t count on caching for short, one-shot, or sparsely-repeated prompts — and on explicit-control providers, that misuse actively costs you the write surcharge.</li><li>Verify with the provider’s cache token counts, and model “unreported” as None, not 0. Never assume.</li></ol><p>Get the layout right and a large, repetitive system prompt goes from a per-request tax to a near-free, fast-to-process asset. Get it wrong and you’ve added complexity — and, on some providers, cost — for a cache that never hits. The difference is entirely in the structure. So structure it on purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=374a711ac01b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded Databases: What They Are, Why They Exist, and When to Use Them]]></title>
            <link>https://medium.com/@srivatsa4123/embedded-databases-what-they-are-why-they-exist-and-when-to-use-them-ee8dfd44d23c?source=rss-150d91553aea------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8dfd44d23c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[embedded-databases]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Srivatsa.k]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 17:29:04 GMT</pubDate>
            <atom:updated>2026-02-28T17:29:04.483Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple guide to understanding embedded databases, their use cases, and how to choose between options like SQLite, BadgerDB, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyPejdtOdCtE_ZbX0LxsCA.png" /></figure><p>When we hear the word <em>database</em>, most of us immediately think of things like PostgreSQL, MySQL, or MongoDB — a database running somewhere on a server, accessed over the network.</p><p>But not all databases work that way.</p><p>There is another category called <strong>embedded databases</strong>, and they quietly power many applications we use every day.</p><p>In this blog, we’ll explore:</p><ul><li>What embedded databases really are</li><li>How they are different from “normal” databases</li><li>Why they exist</li><li>When they are useful</li><li>Common use cases</li><li>Examples like <strong>SQLite</strong> and <strong>BadgerDB</strong></li><li>How to decide which embedded database to choose</li></ul><h3>What Is an Embedded Database?</h3><p>An <strong>embedded database</strong> is a database that runs <strong>inside your application process</strong>, not as a separate server.</p><p>Instead of connecting over the network, your application:</p><ul><li>Links the database as a <strong>library</strong></li><li>Reads and writes data <strong>locally</strong></li><li>Stores data in a <strong>file or directory on disk</strong></li></ul><p>A simple way to think about it:</p><blockquote><em>An embedded database is part of your application, not a separate system.</em></blockquote><h3>How Is This Different from a “Normal” Database?</h3><p>Traditional databases (like Postgres or MySQL):</p><ul><li>Run as independent server processes</li><li>Are accessed over the network</li><li>Are designed for multiple clients and services</li><li>Focus on sharing data and scaling across systems</li></ul><p>Embedded databases:</p><ul><li>Run inside the application</li><li>Are accessed via function calls</li><li>Are usually owned by a single application</li><li>Focus on simplicity, locality, and low overhead</li></ul><p>A useful mental model:</p><blockquote><em>Server databases optimize for </em><strong><em>sharing and scale</em></strong><em>.<br>Embedded databases optimize for </em><strong><em>ownership and simplicity</em></strong><em>.</em></blockquote><h3>Why Do Embedded Databases Exist?</h3><p>You might ask:</p><blockquote><em>“If server databases are so powerful, why do embedded databases exist at all?”</em></blockquote><p>Embedded databases exist because not every problem needs a database server.</p><p>They solve problems where:</p><ul><li>Running a separate database is unnecessary overhead</li><li>Network access is unreliable or unavailable</li><li>Low-latency local access is important</li><li>Simpler deployment matters more than distributed scaling</li></ul><p>Embedded databases reduce complexity by <strong>keeping data close to the application</strong>.</p><h3>When Are Embedded Databases Useful?</h3><p>Embedded databases shine when <strong>data ownership is clear</strong> and <strong>local access is enough</strong>.</p><p>Common scenarios include:</p><h3>Local state inside applications</h3><p>Applications often need to store:</p><ul><li>Metadata</li><li>Configuration</li><li>Caches</li><li>Checkpoints</li><li>Offsets</li></ul><p>If only one service owns this data, an embedded database is often the simplest choice.</p><h3>Desktop and mobile applications</h3><p>Many desktop and mobile apps need:</p><ul><li>Local persistence</li><li>Offline support</li><li>Fast startup</li></ul><p>Embedded databases are ideal here because there is no server dependency.</p><h3>Agents, CLIs, and background services</h3><p>Command-line tools and agents often need:</p><ul><li>Lightweight storage</li><li>Simple setup</li><li>Predictable behavior</li></ul><p>Embedding the database avoids forcing users to install or manage anything else.</p><h3>Edge and IoT environments</h3><p>In constrained environments:</p><ul><li>Network may be unreliable</li><li>Resources are limited</li><li>Simplicity is critical</li></ul><p>Embedded databases fit naturally in these scenarios.</p><h3>When Embedded Databases Are NOT a Good Fit</h3><p>Embedded databases are not a universal solution.</p><p>They are usually a poor choice when:</p><ul><li>Multiple services need shared write access</li><li>Data must be accessed across machines</li><li>Horizontal scaling is required</li><li>Complex multi-writer concurrency is needed</li></ul><p>A good rule of thumb:</p><blockquote><em>If many systems need to share the same data, a server database is usually a better fit.</em></blockquote><h3>Types of Embedded Databases</h3><p>Before looking at specific tools, it helps to understand <strong>categories</strong>.</p><h3>Embedded relational databases</h3><ul><li>Use tables and schemas</li><li>Support SQL</li><li>Provide strong consistency and transactions</li><li>Best for structured data</li></ul><h3>Embedded key-value databases</h3><ul><li>Store data as key → value</li><li>No SQL or joins</li><li>Application controls data structure</li><li>Optimized for throughput and simplicity</li></ul><h3>Embedded analytical databases</h3><ul><li>Focus on analytics and reporting</li><li>Column-oriented</li><li>Used for local data analysis</li></ul><p>This categorization helps decide <em>what kind of problem</em> you are solving.</p><blockquote><em>We’ll look at one example from each category: SQLite (relational), BadgerDB (key-value), and DuckDB (analytical).</em></blockquote><h3>SQLite: Embedded Relational Database</h3><p>SQLite is one of the most widely used embedded databases in the world.</p><p>It is:</p><ul><li>Embedded</li><li>Relational</li><li>ACID-compliant</li><li>File-based</li><li>SQL-powered</li></ul><p>SQLite is a good fit when:</p><ul><li>Data is structured</li><li>SQL queries are useful</li><li>Correctness and reliability matter</li><li>Reads are frequent</li><li>Deployment simplicity is important</li></ul><p>A common misconception is that SQLite is “only for small apps”.<br> In reality, SQLite is used in browsers, operating systems, and production systems worldwide.</p><h3>BadgerDB: Embedded Key-Value Database</h3><p>BadgerDB represents a different design approach.</p><p>It is:</p><ul><li>Embedded</li><li>Key-value based</li><li>Optimized for write-heavy workloads</li><li>Designed to be simple and fast</li><li>Commonly used in Go applications</li></ul><p>BadgerDB is a good fit when:</p><ul><li>Data access patterns are simple</li><li>High write throughput is important</li><li>SQL is unnecessary</li><li>The application controls data modeling</li></ul><p>It is important to frame this correctly:</p><blockquote><em>BadgerDB does not replace SQLite — it serves a different purpose.</em></blockquote><h3>DuckDB: Embedded Analytical Database</h3><p>DuckDB represents a third category of embedded databases: <strong>analytical databases</strong>.</p><p>Unlike SQLite and BadgerDB, which are commonly used for application state and operational data, DuckDB is designed for <strong>analytics and reporting</strong>.</p><p>DuckDB is:</p><ul><li>Embedded and runs inside the application</li><li>Column-oriented</li><li>Optimized for analytical (read-heavy) queries</li><li>Designed for local data analysis</li><li>Often described as “SQLite for analytics”</li></ul><p>DuckDB is a good fit when:</p><ul><li>You need to analyze large datasets locally</li><li>Queries involve aggregations, filtering, and reporting</li><li>The workload is mostly read-heavy</li><li>You want analytical capabilities without setting up a data warehouse</li><li>Data analysis needs to be embedded directly into an application</li></ul><p>Common use cases include:</p><ul><li>Local data exploration</li><li>Embedded analytics inside applications</li><li>Processing CSV or Parquet files</li><li>Lightweight reporting and dashboards</li><li>Data science and experimentation workflows</li></ul><p>An important distinction to understand:</p><blockquote><em>DuckDB is not meant for transactional workloads.<br> It is optimized for analytics, not for frequent small writes.</em></blockquote><h3>Other Embedded Databases (Briefly)</h3><p>There are many other embedded databases, each with a specific focus:</p><ul><li>BoltDB / bbolt for simple key-value storage</li><li>PebbleDB for high-performance embedded storage</li><li>LMDB for read-heavy workloads</li></ul><h3>How to Choose the Right Embedded Database</h3><p>Instead of asking <em>“Which database is better?”</em>, ask:</p><ul><li>Do I need SQL queries?</li><li>Is my data structured or opaque?</li><li>Is write throughput important?</li><li>Will there be one writer or many?</li><li>Is this local state or shared state?</li></ul><p>From there:</p><ul><li>Structured data + queries → embedded relational databases</li><li>Simple access + high throughput → embedded key-value databases</li></ul><p>SQLite and BadgerDB naturally fall into these categories.</p><h3>Final Thoughts</h3><p>Embedded databases are not “lightweight alternatives” to server databases — they are <strong>architectural tools</strong> designed for specific scenarios.</p><p>When data ownership is clear and locality matters, embedded databases can dramatically simplify systems.<br> When data needs to be shared and scaled across services, server databases remain the better choice.</p><p>Understanding <strong>when and why</strong> to use embedded databases helps you design systems that are simpler, more reliable, and easier to operate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8dfd44d23c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Your Service as HTTPS: What It Really Means, Why It Matters, and How to Do It (Go & Node.js)]]></title>
            <link>https://medium.com/@srivatsa4123/running-your-service-as-https-what-it-really-means-why-it-matters-and-how-to-do-it-go-node-js-0ebb0565b61a?source=rss-150d91553aea------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ebb0565b61a</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[tls-handshake]]></category>
            <category><![CDATA[private-key]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[http-vs-https]]></category>
            <dc:creator><![CDATA[Srivatsa.k]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 13:32:03 GMT</pubDate>
            <atom:updated>2026-01-24T13:32:03.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9fF3vKYlEG71AnbSoS-tnw.png" /></figure><p>When developers think about HTTPS, they usually associate it with <strong>Nginx, API gateways, or load balancers</strong>.<br> While that is very common, it often hides an important fact:</p><blockquote><strong><em>HTTPS is not just an infrastructure feature — it can be handled directly by your service.</em></strong></blockquote><p>Running a service as HTTPS is <strong>possible in almost every modern programming language</strong>.</p><p>In this blog, we will focus on:</p><ul><li>What HTTPS really means</li><li>How HTTPS works internally</li><li>Why HTTPS inside the service can be useful</li><li>How to run a service as HTTPS, with examples in Go and Node.js</li></ul><h3>1. HTTP vs HTTPS (Short and Clear)</h3><p><strong>HTTP</strong> sends data as plain text.<br>Anyone who can observe the network traffic can read the request and response.</p><p><strong>HTTPS</strong> is HTTP running inside a <strong>secure encrypted channel</strong> created using TLS.</p><ul><li>Data cannot be read by attackers</li><li>The client can verify the server’s identity</li><li>Data cannot be modified during transit</li></ul><p>In simple terms:</p><blockquote><strong><em>HTTP is readable. HTTPS is protected.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*ANO3GuKDnlmvxowM.png" /></figure><h3>2. How HTTPS Works (Certificate and Private Key Explained)</h3><p>HTTPS relies on <strong>two important files</strong>:</p><ul><li><strong>Certificate (</strong><strong>.crt)</strong></li><li><strong>Private key (</strong><strong>.key)</strong></li></ul><p>Understanding what these two do makes HTTPS much easier to reason about.</p><h3>2.1 What the Certificate Is Used For</h3><p>The certificate contains:</p><ul><li>The server’s identity</li><li>A public key</li><li>Information about who the certificate belongs to</li></ul><p>When a client connects to an HTTPS server:</p><ul><li>The server sends its certificate</li><li>The client verifies the certificate</li><li>The client extracts the public key from it</li></ul><p>The certificate is <strong>safe to share</strong> and is meant to be public.</p><h3>2.2 What the Private Key Is Used For</h3><p>The private key:</p><ul><li>Exists only on the server</li><li>Is never shared with clients</li><li>Is used to prove the server’s identity</li><li>Is used during the TLS handshake to establish a secure session</li></ul><p>If the private key is compromised, HTTPS security is broken, which is why it must be protected carefully</p><h3>2.3 A Simple HTTPS Flow Example</h3><ol><li>A client connects to <a href="https://localhost/">https://localhost</a></li><li>The server sends its certificate</li><li>The client verifies the certificate</li><li>The client generates a secret session key</li><li>The client encrypts this secret using the server’s public key</li><li>The server decrypts it using its private key</li><li>Both sides now communicate using fast symmetric encryption</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*DFZ_sVR3e90yFg0C.png" /><figcaption><strong>Image source:</strong> 7SSL.com — SSL/TLS Handshake Diagram</figcaption></figure><p>After this step:</p><ul><li>All HTTP requests and responses are encrypted</li><li>The private key is no longer used for each request</li><li>HTTPS works efficiently and transparently</li></ul><p>This entire process happens automatically.</p><h3>3. Why Run HTTPS Inside the Service?</h3><p>Running HTTPS inside the service is useful in several situations.<br> It gives the service more control over how secure communication is handled.</p><p>It is commonly used when:</p><h4>HTTPS is required for local development</h4><p>Some features like OAuth callbacks, secure cookies, and SameSite=None cookies require HTTPS even in local setups. Running HTTPS inside the service avoids workarounds and keeps behavior closer to production.</p><h4>The service is standalone</h4><p>Standalone services such as agents, CLI tools, desktop apps, or IoT services often do not sit behind gateways or proxies. In these cases, the service itself must handle HTTPS to communicate securely.</p><h4>Internal service-to-service calls need to be encrypted</h4><p>In many environments (like Kubernetes or private networks), when one service calls another service internally, the traffic is often <strong>plain HTTP</strong> because it never goes through a gateway or load balancer.</p><p>This usually looks like:</p><pre>Service A → HTTP → Service B</pre><p>This is common and often acceptable because:</p><ul><li>Traffic stays inside a trusted network</li><li>It reduces overhead</li><li>It simplifies debugging</li></ul><p>However, in some setups, <strong>encrypting internal traffic is still important</strong>, for example:</p><ul><li>Zero-trust architectures</li><li>Multi-tenant clusters</li><li>Regulatory or compliance requirements</li><li>Environments where the network itself is not fully trusted</li></ul><p>In such cases, running the service itself as HTTPS allows:</p><pre>Service A → HTTPS → Service B</pre><p>This ensures that <strong>even internal traffic is encrypted</strong>, without depending on a gateway.</p><p>So, internal HTTPS is <strong>not always required</strong>, but when security requirements demand it, <strong>running HTTPS inside the service makes it possible</strong>.</p><h4>You want simpler deployments without extra infrastructure</h4><p>For smaller setups or internal tools, adding and managing Nginx or a gateway can be unnecessary overhead. Enabling HTTPS directly in the service keeps the architecture simple.</p><h4>The service itself acts as the edge</h4><p>When the service is directly exposed to clients (without any proxy in front), it must handle HTTPS on its own. In this case, HTTPS inside the service is not optional — it is required.</p><p>This approach does not replace gateways in large production systems, but it provides <strong>flexibility and control</strong> when your architecture or security model needs it.</p><h3>4. Generate Certificates (Simple Way for Local Development)</h3><p>For local testing,</p><p>Use the following simple commands:</p><pre># Generate a private key<br>openssl genrsa -out server.key 2048</pre><pre># Generate a self-signed certificate for localhost<br>openssl req -new -x509 \<br>  -key server.key \<br>  -out server.crt \<br>  -days 365 \<br>  -subj &quot;/CN=localhost&quot;</pre><p>This creates:</p><ul><li>server.key → private key (keep it secret)</li><li>server.crt → certificate (safe to share)</li></ul><p>Browsers will show a warning because the certificate is self-signed.<br>This is expected for local development.</p><blockquote><em>️ Self-signed certificates should never be used in production.</em></blockquote><h3>5. Running a Service as HTTPS</h3><h4>5a. Go Example (Basic HTTPS Service)</h4><p>Go provides native support for HTTPS.</p><pre>package main<br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br>)<br>func main() {<br> http.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  fmt.Fprintln(w, &quot;Hello from HTTPS Go service!&quot;)<br> })<br> err := http.ListenAndServeTLS(<br>  &quot;:8443&quot;,<br>  &quot;server.crt&quot;,<br>  &quot;server.key&quot;,<br>  nil,<br> )<br> if err != nil {<br>  panic(err)<br> }<br>}</pre><p>In this example:</p><ul><li>Go loads the certificate and private key</li><li>The TLS handshake is handled automatically</li><li>Your handlers receive normal HTTP requests that are already secured</li></ul><h4>5b. Node.js Example (Basic HTTPS Service)</h4><p>Node.js also supports HTTPS directly.</p><pre>const https = require(&quot;https&quot;);<br>const fs = require(&quot;fs&quot;);<br>const options = {<br>  key: fs.readFileSync(&quot;server.key&quot;),<br>  cert: fs.readFileSync(&quot;server.crt&quot;),<br>};<br>https.createServer(options, (req, res) =&gt; {<br>  res.writeHead(200);<br>  res.end(&quot;Hello from HTTPS Node.js service!&quot;);<br>}).listen(8443, () =&gt; {<br>  console.log(&quot;HTTPS server running at https://localhost:8443&quot;);<br>});</pre><p>Here:</p><ul><li>Node.js reads the certificate and private key</li><li>TLS is managed internally by Node</li><li>Your application logic remains unchanged</li></ul><h3>6. When NOT to Run HTTPS Inside the Service</h3><p>In large production environments, HTTPS is often terminated at:</p><ul><li>Nginx</li><li>Envoy</li><li>API gateways</li><li>Cloud load balancers</li></ul><p>These systems handle:</p><ul><li>Certificate rotation</li><li>Rate limiting</li><li>DDoS protection</li><li>Centralized security policies</li></ul><p>Running HTTPS inside the service is a <strong>design decision</strong>, not a strict requirement.</p><h3>7. Final Thoughts</h3><p>HTTPS is not limited to gateways or proxies — it is a core mechanism for secure communication between clients and services.</p><p>In this blog, we covered:</p><ul><li>What HTTPS is and how it differs from HTTP</li><li>How certificates and private keys are used during secure communication</li><li>When running HTTPS inside the service is useful</li><li>How to run a service as HTTPS using Go and Node.js</li></ul><p>Running HTTPS inside the service is not mandatory in every architecture, but understanding how it works helps you make better design decisions based on security, deployment, and operational needs.</p><p>The same concepts apply regardless of the programming language — once you understand the basics, you can implement HTTPS wherever it is required.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ebb0565b61a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Go Feels Different: Goroutines, Channels & the Tiny Mini-OS Inside Go]]></title>
            <link>https://medium.com/@srivatsa4123/why-go-feels-different-goroutines-channels-the-tiny-mini-os-inside-go-22e8e97ee65a?source=rss-150d91553aea------2</link>
            <guid isPermaLink="false">https://medium.com/p/22e8e97ee65a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[goroutines]]></category>
            <dc:creator><![CDATA[Srivatsa.k]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 12:06:32 GMT</pubDate>
            <atom:updated>2025-12-30T15:46:37.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vw7ScFlyarGXYe5NCF6CnQ.png" /></figure><p>When I first learned Go, I expected just another programming language with the usual features: variables, loops, if-else, the occasional headache…</p><p>But instead, Go slapped me in the face with concepts that felt <strong>too simple</strong>, <strong>too fast</strong>, and almost <strong>cheating</strong> compared to other languages.</p><p>And the more I used it, the more I realized:</p><blockquote><strong><em>Go isn’t just a language.<br> It’s a language + a tiny operating system hidden inside the runtime.</em></strong></blockquote><p>And the biggest secret behind Go’s magic is:<br> <strong>It’s not just a language. Go ships with its own mini operating system (runtime) inside it.</strong></p><p>In this blog, let’s explore the <strong>most interesting and unique Go concepts</strong>, compare them with other languages</p><h3>1. Goroutines — Threads That Hit the Gym &amp; Got Super Lightweight</h3><p>If other languages spawn threads like this:</p><ul><li><strong>Python</strong>: <em>“Let me start a new thread… wait, why is my program slow?”</em></li><li><strong>Java</strong>: <em>“Here, take this 1 MB thread. Use it wisely.”</em></li><li><strong>JavaScript</strong>: <em>“We don’t do threads here. We multitask… one thing at a time.”</em></li></ul><p>Go simply says:</p><pre>go func() {<br>    fmt.Println(&quot;Hello from a goroutine!&quot;)<br>}()</pre><p>That’s it.<br> One word — go — and you have a new background worker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dKctHqwFN4JEnErpCogNTg.png" /><figcaption>“How Go juggles thousands of goroutines across cores without breaking a sweat.”</figcaption></figure><h3>But what exactly Is a goroutine?</h3><p>A goroutine is:</p><ul><li>A function running independently</li><li>Managed by the Go runtime</li><li>Not tied to any one OS thread</li><li>Free to move between CPU cores</li></ul><p>You can think of a goroutine like a message you send to Go saying:</p><blockquote>“Hey, please run this in the background whenever you have time.”</blockquote><p>No complicated syntax.<br>No thread creation boilerplate.<br>No locking required just to get started.</p><h3>Quick example: launching multiple tasks</h3><pre>for i := 1; i &lt;= 5; i++ {<br>    go func(i int) {<br>        fmt.Println(&quot;Task:&quot;, i)<br>    }(i)<br>}</pre><p>Go will happily run all these tasks concurrently.<br> Try this in Java or Python threads and watch your system cry.</p><h3>Why goroutines are special</h3><ul><li>They start with just <strong>2 KB</strong> memory (yes, KB).</li><li>You can spin up <strong>millions</strong>.</li><li>They run <strong>in parallel</strong> across CPU cores.</li><li>Switching between them is extremely cheap.</li></ul><h3>Why this is better than async/await</h3><ul><li>In JavaScript, async/await still runs on <em>one</em> thread.</li><li>In Python, asyncio is <em>not parallel</em> (unless you add processes).</li><li>In Java, threads are expensive.</li></ul><p>Go made concurrency so easy that it almost feels like cheating.</p><h3>2. The Go Scheduler — The Hidden Brain Running the Show</h3><p>Goroutines alone are cool…<br> But the real superhero is the <strong>Go Scheduler</strong>.</p><p>It’s the secret “mini OS” inside Go that:</p><ul><li>assigns goroutines to OS threads</li><li>balances them across CPU cores</li><li>pauses/resumes goroutines automatically</li><li>handles blocking without blocking others</li></ul><h3>Think of the Go Scheduler like a smart traffic controller</h3><p>You write Go code using <strong>goroutines</strong> (very lightweight threads).<br> But <strong>goroutines don’t run by themselves</strong> — the <strong>Go Scheduler</strong> decides:</p><ul><li><strong>which goroutine runs</strong></li><li><strong>on which OS thread</strong></li><li><strong>on which CPU core</strong></li><li><strong>and for how long</strong></li></ul><p>Its main goal is simple:</p><blockquote><strong><em>Run millions of goroutines efficiently using a small number of OS threads.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGiin1whGBhmUY_s7ihKhA.png" /><figcaption>“Go’s scheduler directing goroutines to the right threads and CPU cores.”</figcaption></figure><h3>M:N Scheduling (Go’s secret sauce)</h3><p>Many goroutines → Few OS threads → Multiple CPU cores</p><p>This is why Go servers can handle <strong>huge traffic</strong> with low memory.</p><h3>Compared to JavaScript</h3><p>JavaScript has the event loop:</p><pre>One guy doing all the work.<br>If he sleeps, the whole office stops.</pre><h3>Go Scheduler</h3><pre>Thousands of workers.<br>Smart manager that assigns tasks.<br>Nobody blocks anyone else.</pre><p>Try blocking JavaScript:</p><pre>while(true) {} // goodbye server</pre><p>Try blocking Go:</p><pre>time.Sleep(5 * time.Second)</pre><p>Other goroutines continue working happily.<br>Because Go’s scheduler is carrying 90% of the stress.</p><h3>3. Channels — Communication Without Headaches</h3><p>Most languages use:</p><ul><li>locks</li><li>mutexes</li><li>semaphores</li><li>callbacks</li><li>coping mechanisms</li></ul><p>Go says:</p><blockquote><strong><em>“Hey, just send messages between goroutines.”</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*sW3Az9fQ5OVcxtdc9mm1sA.png" /><figcaption><strong>“Channels let goroutines pass data safely and in sync.”</strong></figcaption></figure><p>Here’s a channel in action:</p><pre>ch := make(chan string)<br>go func() {<br>    ch &lt;- &quot;hello&quot; // send<br>}()<br>msg := &lt;-ch  // receive<br>fmt.Println(msg)</pre><h3>Why channels are magical</h3><ul><li>No locks needed</li><li>No race conditions when used right</li><li>Goroutines naturally synchronize</li><li>Code stays readable</li><li>Built-in backpressure</li></ul><h3>Compared to Python / Java</h3><p>Python’s Queue + locks = clutter<br>Java’s synchronized = stress<br>Go’s channels = clean and friendly</p><p>This is based on CSP (Communicating Sequential Processes), which basically says:</p><blockquote><strong><em>“Don’t share memory.<br> Share messages.”</em></strong></blockquote><p>This keeps your code simple and scalable.</p><h3>4. Blocking That Doesn’t Block (Yes, Really)</h3><p>In most languages, if something blocks, your entire program suffers.</p><p><strong>Python:</strong></p><pre>time.sleep(5)  # everything naps</pre><p><strong>JavaScript:</strong></p><pre>while(true) {} // browser or server freezes</pre><p><strong>Go:</strong></p><pre>time.Sleep(5 * time.Second)</pre><p>Only that goroutine sleeps.<br>Everything else stays lightning-fast.</p><p>Because Go’s scheduler simply parks the sleeping goroutine and picks another one.</p><h3>5. Auto-Growing Stack — Go Manages Memory Smartly</h3><p>Each goroutine starts with a tiny <strong>2 KB stack</strong>.<br>But if your function uses more memory, Go automatically grows the stack.<br>When it’s done, Go shrinks it again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gl0F2XD_eQGlCtX60r3WA.png" /></figure><p>Other languages give every thread <strong>1 MB</strong> even if they only use <strong>20 KB</strong>.</p><p><strong>Go</strong>:</p><blockquote><em>“Use what you need. I’ll handle the rest.”</em></blockquote><p>This makes goroutines super memory-efficient.</p><h3>Final Thoughts — Go Makes Concurrency Feel Easy</h3><p>Go’s power isn’t just its syntax — it’s what the <strong>runtime</strong> does behind the scenes:</p><ul><li>Goroutines → tiny &amp; fast</li><li>Scheduler → smart &amp; fair</li><li>Channels → clean communication</li><li>Auto-stack → memory efficient</li><li>Blocking without fear → developer-friendly</li></ul><p>Most languages let you <em>do</em> concurrency.<br> Go makes concurrency <strong>simple, elegant, and fun</strong>.</p><p>And here’s the best part:</p><blockquote><strong><em>This is just Part 1.<br> Stay tuned — in Part 2, I’ll dive into more hidden Go superpowers like escape analysis, garbage collector magic, interfaces, maps, and more!</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22e8e97ee65a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ The Long Road to Lua + ModSecurity on Nginx: Our Docker Battle Story]]></title>
            <link>https://medium.com/@srivatsa4123/%EF%B8%8F-the-long-road-to-lua-modsecurity-on-nginx-our-docker-battle-story-8afe0f5ca0a1?source=rss-150d91553aea------2</link>
            <guid isPermaLink="false">https://medium.com/p/8afe0f5ca0a1</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[modsecurity]]></category>
            <category><![CDATA[web-application-firewall]]></category>
            <category><![CDATA[lua]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Srivatsa.k]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 14:26:49 GMT</pubDate>
            <atom:updated>2025-08-19T16:49:00.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUzSf4Q7i0trPqIjI6HRCA.png" /></figure><p>When building a secure, programmable edge layer using Nginx, we wanted the best of both worlds: <strong>ModSecurity for Web Application Firewall (WAF)</strong> functionality, and <strong>Lua scripting</strong> for dynamic request inspection and custom behavior. But as we quickly found out, finding or building a Docker image that supports <strong>both ModSecurity and Lua</strong> was <strong>far from easy</strong>.</p><p>In this blog, I’ll walk through the pain points we encountered, the multiple approaches we attempted, and finally, the working approach and setup that brought it all together.</p><h3>🚧 The Core Problem</h3><p>There was no <strong>official or community-maintained image</strong> that came out of the box with:</p><ul><li><strong>ModSecurity v3</strong>, <strong>with CRS (Core Rule Set)</strong></li><li><strong>LuaJIT + lua-nginx-module</strong></li><li><strong>Recent stable Nginx</strong></li></ul><p>You either got one or the other:</p><ul><li>openresty/* had Lua but not ModSecurity.</li><li>owasp/modsecurity-crs:* had ModSecurity and CRS but no Lua or Lua modules.</li><li>Adding both required careful Nginx compilation with custom modules.</li></ul><h3>🔍 What We Tried (and What Failed)</h3><h3>1. Tried OpenResty</h3><p>It comes precompiled with LuaJIT and lua-nginx-module. We attempted to add ModSecurity to OpenResty.<br> <strong>Problem:</strong> ModSecurity was not compiled in and adding it manually required modifying OpenResty internals — messy and unstable.</p><h3>2. Tried ModSecurity Base Images</h3><p>We picked owasp/modsecurity-crs:nginx, thinking we could install Lua modules directly.<br> <strong>Problem:</strong> No lua-nginx-module and compiling it with ModSecurity required rebuilding Nginx entirely.</p><h3>3. Tried Adding Lua via Luarocks</h3><p>We installed Lua via luarocks, thinking Lua scripting could just be injected into Nginx config.<br> <strong>Problem:</strong> Luarocks can install Lua libraries, but for Lua scripting to work <strong>in Nginx config</strong>, you need ngx_http_lua_module compiled into Nginx. It wasn’t.</p><h3>4. Recompiling Nginx With Modules</h3><p>We attempted to manually build Nginx from source with both lua-nginx-module and ModSecurity-nginx.<br> 🚧 <strong>Painful Proces</strong></p><ul><li>Nginx source compilation is brittle.</li><li>LuaJIT paths must be configured correctly.</li><li>Linking ModSecurity required compiling libmodsecurity manually.</li><li>You must make sure the .so files are available in library paths at runtime.</li></ul><h3>🔨 The Final Solution (What Worked)</h3><p>After weeks of trial and error, <strong>this approach </strong>finally worked.</p><h3>Base Image:</h3><p>We chose a solid starting point:</p><pre>FROM owasp/modsecurity-crs:4.11.0-nginx-202502070602</pre><p>This gave us:</p><ul><li>A working CRS setup</li><li>ModSecurity-nginx connector pre-installed</li><li>A familiar Nginx base for expansion</li></ul><h3>What We Added:</h3><ul><li><strong>LuaJIT from OpenResty repo</strong></li><li><strong>lua-nginx-module</strong>, <strong>lua-resty-core</strong>, <strong>lua-resty-lrucache</strong></li><li><strong>Manual Nginx compilation</strong> with --add-module for Lua and ModSecurity</li><li><strong>Custom </strong><strong>nginx.conf</strong> to initialize Lua runtime properly</li><li><strong>Runtime configs</strong> to ensure .so libraries are found</li></ul><h3>🧩 Key Takeaways</h3><ul><li><strong>ModSecurity and Lua</strong> are both powerful, but not designed to coexist out of the box.</li><li><strong>Custom compilation</strong> is essential. Prebuilt images don’t offer both.</li><li><strong>Test iteratively.</strong> Compilation errors (especially linking errors) are cryptic and hard to debug.</li><li><strong>Base image matters.</strong> Starting from the ModSecurity CRS image saved a lot of setup time.</li></ul><h3>🎯 What We Can Do Now</h3><p>With this setup, we’re able to:</p><ul><li>Parse request payloads in Lua and route traffic conditionally</li><li>Generate structured telemetry in real-time</li><li>Still enforce all <strong>ModSecurity WAF</strong> protections</li><li>Maintain clean and modular Docker setup</li></ul><h3>🔚 Final Thoughts</h3><p>We wish there were a simpler way to do this — and maybe one day, the community will maintain a fully-featured ModSecurity + Lua Nginx image.</p><p>Until then: <strong>this approach and setup is your best friend</strong>. You can check out the <strong>Dockerfile on GitHub </strong><a href="https://github.com/Srivatsak2002/nginx-modsecurity-lua/blob/main/Dockerfile"><strong>here</strong></a>.</p><p>If you’re trying to build something similar and want help , just reach out in the comments 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8afe0f5ca0a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>