<?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"><channel><title><![CDATA[Mudassir Khan]]></title><description><![CDATA[Mudassir Khan]]></description><link>https://mudassirworks.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 12 Nov 2026 19:46:00 GMT</lastBuildDate><atom:link href="https://mudassirworks.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Python Routing Middleware on Vercel: FastAPI, Flask, Django Integration Guide]]></title><description><![CDATA[Vercel's latest Python release added routing middleware through the vercel-proxy package: code that runs before your app and can route, redirect and change…]]></description><link>https://mudassirworks.hashnode.dev/python-routing-middleware-on-vercel-fastapi-flask-django-integration-guide</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/python-routing-middleware-on-vercel-fastapi-flask-django-integration-guide</guid><category><![CDATA[FastAPI]]></category><category><![CDATA[Vercel]]></category><category><![CDATA[Python]]></category><category><![CDATA[Middleware]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Thu, 12 Nov 2026 18:41:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/ba30a1f0-7443-4c0c-ad63-48e3f7ad34b3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Vercel's latest Python release added routing middleware through the <code>vercel-proxy</code> package: code that runs before your app and can route, redirect and change request headers. If you run FastAPI, Flask or Django on Vercel, the useful question is not how to turn it on. It is which of your existing checks move out of the app, and which must stay inside it. Vercel Python middleware and FastAPI middleware share a name, not a layer, and treating them as one stack is how a redirect rule turns into an auth hole.</p>
<p><strong>TL;DR</strong></p>
<ul>
<li>Routing middleware runs before the app. Framework middleware runs inside it. Vercel's example redirects with HTTP 308, which is the right status only for URLs that moved for good.</li>
<li>Keep every redirect decision in one pure Python function, then let each framework enforce sessions its own way: a dependency in FastAPI, <code>before_request</code> in Flask, a middleware class in Django.</li>
<li>Never let the app trust a header because the routing layer set it. OWASP LLM06 asks for independent downstream authorization, and the tests below prove you have it.</li>
</ul>
<p>By the end you will have a shared rules module, a working session check for all three frameworks, a slash handling plan, and a test file you can run in CI. If this Python service is the backend for an AI agent, the choice of agent stack is a separate decision, and the <a href="https://mudassirkhan.me/tools/ai-agent-framework-chooser">AI agent framework chooser</a> helps with that one. Everything here applies either way.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/3f2422a9-9287-4ce0-a8f8-b7c18651f9f1.gif" alt="Vercel Python middleware and FastAPI middleware as two separate layers: the routing layer runs before the app and handles redirects, routing and header changes; the application layer runs inside the app and handles sessions, authorization and business rules" style="display:block;margin:0 auto" />

<h2>Separate routing and application layers: a Vercel Python middleware FastAPI guide</h2>
<p>The split that holds up in production is simple. The routing layer answers questions it can settle from the URL and the presence of a cookie. The application layer answers questions that need a verified identity or your database.</p>
<table>
<thead>
<tr>
<th>Job</th>
<th>Routing layer</th>
<th>Application layer</th>
</tr>
</thead>
<tbody><tr>
<td>Moved URL map</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Send signed out users to login</td>
<td>Yes, by cookie presence only</td>
<td>Also enforces it</td>
</tr>
<tr>
<td>Verify a session signature</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Decide what a user can do</td>
<td>No</td>
<td>Yes, on every request</td>
</tr>
<tr>
<td>Add a request ID to the response</td>
<td>No</td>
<td>Yes</td>
</tr>
</tbody></table>
<p>FastAPI's documentation shows the in app shape: <code>@app.middleware("http")</code> wraps each request and response, in a sample that targets Python 3.10+. That wrapper lives in your process. Don't assume it shares an ordering, a runtime or a config file with the routing layer.</p>
<p>Here is the module both layers can rely on. It has no framework imports and no Vercel imports, so it survives any change to either.</p>
<pre><code class="language-python"># routing_rules.py
from urllib.parse import quote, urlsplit

PERMANENT_MOVES = {
    "/docs/v1": "/docs",
    "/api/v1/reports": "/api/reports",
}
LOGIN_GATED_PREFIXES = ("/dashboard", "/settings")


def is_safe_next(target: str) -&gt; bool:
    parts = urlsplit(target)
    return (
        target.startswith("/")
        and not target.startswith("//")
        and "\\" not in target
        and not parts.scheme
        and not parts.netloc
    )


def decide(path: str, has_session_cookie: bool) -&gt; tuple[int, str] | None:
    """Return (status, location) for a redirect, or None to pass through."""
    if path in PERMANENT_MOVES:
        return 308, PERMANENT_MOVES[path]
    if path.startswith(LOGIN_GATED_PREFIXES) and not has_session_cookie:
        next_path = path if is_safe_next(path) else "/"
        return 307, f"/login?next={quote(next_path)}"
    return None
</code></pre>
<p>Call <code>decide</code> from a thin handler wired the way Vercel's changelog and docs show. I am leaving that handler out on purpose: the feature is new, and a signature pasted from memory is worse than none. All your logic is in the function above, which you can test without a deployment.</p>
<h2>Configure ASGI/WSGI entrypoints for each framework</h2>
<p>The three frameworks differ in where the app object lives and where a per request check belongs. FastAPI is ASGI. Flask is WSGI. Django ships both an <code>asgi.py</code> and a <code>wsgi.py</code>, so pick one and stay with it. Check Vercel's Python docs for the entrypoint file names your project should use.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/e4b85c84-9c1a-4915-b3c7-4ca61ea2e94a.gif" alt="Three Python framework entrypoints behind Vercel routing middleware: FastAPI is ASGI and checks sessions in a dependency, Flask is WSGI and checks sessions in before_request, Django offers ASGI or WSGI and checks sessions in a middleware class" style="display:block;margin:0 auto" />

<p>All three use one verifier. It takes a signed token and returns a user ID or <code>None</code>, and it ignores every header.</p>
<pre><code class="language-python"># sessions.py
import hashlib
import hmac
import os

SECRET = os.environ.get("SESSION_SECRET", "local-test-secret").encode()


def sign(user_id: str) -&gt; str:
    sig = hmac.new(SECRET, user_id.encode(), hashlib.sha256).hexdigest()
    return f"{user_id}.{sig}"


def verify_session(token: str | None) -&gt; str | None:
    if not token or "." not in token:
        return None
    user_id, _, sig = token.rpartition(".")
    expected = hmac.new(SECRET, user_id.encode(), hashlib.sha256).hexdigest()
    return user_id if hmac.compare_digest(sig, expected) else None
</code></pre>
<p>This is a teaching verifier with no expiry. In production, use your auth library's session check and keep the same function shape.</p>
<h3>FastAPI: a dependency, not middleware</h3>
<p>Use <code>@app.middleware("http")</code> for cross cutting work like request IDs. Put identity in a dependency, so a route that needs a user declares it and can't forget it.</p>
<pre><code class="language-python"># fastapi_app.py
import uuid

from fastapi import Depends, FastAPI, HTTPException, Request

from sessions import verify_session

app = FastAPI()


@app.middleware("http")
async def add_request_id(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Request-ID"] = uuid.uuid4().hex
    return response


def current_user(request: Request) -&gt; str:
    user = verify_session(request.cookies.get("session"))
    if user is None:
        raise HTTPException(status_code=401, detail="Not signed in")
    return user


@app.get("/dashboard/billing")
def billing(user: str = Depends(current_user)) -&gt; dict[str, str]:
    return {"user": user}
</code></pre>
<h3>Flask: before_request</h3>
<pre><code class="language-python"># flask_app.py
from flask import Flask, abort, g, jsonify, request

from routing_rules import LOGIN_GATED_PREFIXES
from sessions import verify_session

app = Flask(__name__)


@app.before_request
def require_session():
    if request.path.startswith(LOGIN_GATED_PREFIXES):
        g.user = verify_session(request.cookies.get("session"))
        if g.user is None:
            abort(401)


@app.get("/dashboard/billing")
def billing():
    return jsonify(user=g.user)
</code></pre>
<h3>Django: a middleware class</h3>
<p>Add it to <code>MIDDLEWARE</code> in your settings, after <code>CommonMiddleware</code>.</p>
<pre><code class="language-python"># django_auth.py
from django.http import JsonResponse

from routing_rules import LOGIN_GATED_PREFIXES
from sessions import verify_session


class VerifiedSessionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.path.startswith(LOGIN_GATED_PREFIXES):
            request.verified_user = verify_session(request.COOKIES.get("session"))
            if request.verified_user is None:
                return JsonResponse({"detail": "Not signed in"}, status=401)
        return self.get_response(request)
</code></pre>
<p>Notice what none of these read: <code>X-User-Id</code>. Header changes are one of the three things routing middleware can do, so it is tempting to look up the user there and pass the result along. Don't. A client can send any header it likes, and your authorization would rest on one. OWASP's excessive agency entry makes the same point for agent tools: limit what is exposed and enforce authorization downstream, not through model prompts. If a verified user later decides what a tool can do, our <a href="https://mudassirkhan.me/blog/ai-agent-security-prompt-injection">guide to prompt injection and agent security</a> covers why that boundary has to stand alone.</p>
<h2>Middleware deployment dependencies</h2>
<p>A repo that now holds routing rules and an app has two deployable concerns, and they can drift. Four habits keep them honest:</p>
<ol>
<li><strong>Import, don't copy.</strong> Both layers import <code>routing_rules.py</code>. If the prefix list lives in two files, one will go stale.</li>
<li><strong>Keep the routing path light.</strong> Routing middleware runs before the app on matching requests, so don't import your ORM, your framework or an LLM client into it. Standard library plus <code>vercel-proxy</code> is the target.</li>
<li><strong>Pin</strong> <code>vercel-proxy</code><strong>.</strong> It is a young package. Pin it in your lockfile and read the changelog before you bump it.</li>
<li><strong>Fail open on routing, closed on auth.</strong> If the routing layer throws, the request should still reach an app that enforces identity. The reverse is never acceptable.</li>
</ol>
<p>Habit four is why the framework checks above return 401 by themselves. My opinion: if deleting your routing middleware would expose a single private route, the design is wrong, because that layer is an optimization and not a control.</p>
<h2>Correct path and redirect handling</h2>
<p>Vercel's published example uses HTTP 308. Under RFC 9110, 308 is permanent, keeps the method and body, and can be cached. So a browser can keep following an old rule after you deploy a new one, and your deploy can't reach its cache. That is ideal for <code>/api/v1/reports</code>, because a <code>POST</code> stays a <code>POST</code>. It is a poor fit for a login gate, which is why <code>decide</code> returns 307 there.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/1ef81016-9b2d-4539-8e3f-5f8546cc006a.gif" alt="Choosing a redirect status in Vercel Python middleware: 308 means moved for good, can be cached, use for URL moves; 307 means temporary, keeps method and body, use for login gates" style="display:block;margin:0 auto" />

<p>The quiet bug here is the trailing slash, because all three frameworks have their own opinion and they don't agree. Ask for <code>/items</code> when only <code>/items/</code> is routed and FastAPI answers 307, Flask answers 308 and Django's <code>CommonMiddleware</code> answers 301 (confirmed by running them on Django 6.1, Flask 3.1 and FastAPI 0.162, and worth pinning in a test because defaults can change). A 301 can also turn a <code>POST</code> into a <code>GET</code> in some clients. Stack a routing rule that strips slashes on top of a framework that adds them, and you have a redirect loop that only appears after deployment.</p>
<p>Pick one canonical form and let one layer own it:</p>
<ul>
<li>Decide on no trailing slash, or a trailing slash, for the whole site.</li>
<li>Normalize in the routing layer only if you also turn the framework's behaviour off: <code>redirect_slashes=False</code> in FastAPI, <code>strict_slashes=False</code> in Flask, <code>APPEND_SLASH = False</code> in Django.</li>
<li>Validate every post login destination with <code>is_safe_next</code>, so <code>//evil.example</code> can't become an open redirect.</li>
<li>Log the original path before any rewrite, otherwise your app logs describe a URL the user never asked for.</li>
</ul>
<h2>Operational tests for your Python middleware</h2>
<p>These run with no deployment. <code>pip install fastapi httpx flask django pytest</code> first, and keep the Django check in your own project's test settings.</p>
<pre><code class="language-python"># test_layers.py
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from fastapi_app import app as fastapi_app
from flask_app import app as flask_app
from routing_rules import decide, is_safe_next
from sessions import sign

FORGED = {"X-User-Id": "admin"}


@pytest.mark.parametrize(
    "path,cookie,expected",
    [
        ("/docs/v1", False, (308, "/docs")),
        ("/dashboard/billing", False, (307, "/login?next=/dashboard/billing")),
        ("/dashboard/billing", True, None),
        ("/pricing", False, None),
    ],
)
def test_decide(path, cookie, expected):
    assert decide(path, cookie) == expected


def test_open_redirect_is_blocked():
    assert not is_safe_next("//evil.example")
    assert not is_safe_next("https://evil.example")


def test_fastapi_ignores_forged_header():
    client = TestClient(fastapi_app)
    assert client.get("/dashboard/billing", headers=FORGED).status_code == 401


def test_flask_ignores_forged_header():
    client = flask_app.test_client()
    assert client.get("/dashboard/billing", headers=FORGED).status_code == 401


def test_fastapi_accepts_real_session():
    client = TestClient(fastapi_app, cookies={"session": sign("u_42")})
    assert client.get("/dashboard/billing").json() == {"user": "u_42"}


def test_fastapi_slash_redirect_is_pinned():
    probe = FastAPI()

    @probe.get("/items/")
    def items():
        return []

    response = TestClient(probe, follow_redirects=False).get("/items")
    assert response.status_code == 307
</code></pre>
<p>Then run a short check against a preview deployment, because local tests can't see the routing layer. Use this checklist before you promote:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/8b390b53-b595-4d6e-88f2-1422aa94c9b3.png" alt="Five point release checklist for Vercel Python middleware with FastAPI, Flask or Django: moved URLs answer 308, login gate answers 307, forged header gets 401, no redirect loops, app stays safe without the routing layer" style="display:block;margin:0 auto" />

<pre><code class="language-bash">PREVIEW="https://your-preview.vercel.app"
curl -s -o /dev/null -w "%{http_code}\n" "$PREVIEW/docs/v1"
curl -s -o /dev/null -w "%{http_code}\n" "$PREVIEW/dashboard/billing"
curl -s -o /dev/null -w "%{http_code}\n" -H "X-User-Id: admin" -H "Cookie: session=fake" "$PREVIEW/dashboard/billing"
curl -s -L --max-redirs 5 -o /dev/null -w "%{num_redirects}\n" "$PREVIEW/items"
</code></pre>
<p>With the rules above, you should see 308, 307 and 401, and the last line should print a small number rather than a redirect error.</p>
<h2>FAQ</h2>
<h3>How do I implement Vercel Python middleware with FastAPI safely?</h3>
<p>Put redirects and coarse routing in a pure function that routing middleware calls, and verify identity inside FastAPI with a dependency. Then write a test proving a forged header gets a 401.</p>
<h3>What changed with Vercel Python middleware in this release?</h3>
<p>Routing middleware now supports Python through <code>vercel-proxy</code>. It runs before the app and can route, redirect and change request headers. It does not replace your framework's middleware, which still runs inside the app.</p>
<h3>Should FastAPI, Flask and Django apps drop their own middleware?</h3>
<p>No. Move URL level decisions out if that saves function calls, and keep sessions, authorization and request level logging in the app.</p>
<p><strong>Related reading:</strong> <a href="https://dev.to/mudassirworks/vercel-python-routing-middleware-the-308-and-auth-trap-58pf">Vercel Python Routing Middleware: The 308 and Auth Trap</a> and <a href="https://mudassirworks.hashnode.dev/next-js-security-hardening-middleware-server-actions-and-csp-patterns-that-hold-up">Next.js Security Hardening: Middleware, Server Actions, and CSP Patterns That Hold Up</a>.</p>
<p>If you are putting a Python agent or API into production and want a second pair of eyes on where these boundaries sit, see my <a href="https://mudassirkhan.me/services/agentic-ai-consulting">agentic AI consulting service</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Vercel Connect Stripe Managed Keys: A Least Privilege Next.js Architecture]]></title><description><![CDATA[Vercel Connect Stripe managed keys landed with a small changelog entry and a big consequence. Vercel's managed Stripe connector can now create one…]]></description><link>https://mudassirworks.hashnode.dev/vercel-connect-stripe-managed-keys-a-least-privilege-next-js-architecture</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/vercel-connect-stripe-managed-keys-a-least-privilege-next-js-architecture</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Vercel]]></category><category><![CDATA[stripe]]></category><category><![CDATA[Security]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Sun, 08 Nov 2026 18:45:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/780a9cc6-ed67-47d6-8957-6bb4120e28b5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Vercel Connect Stripe managed keys landed with a small changelog entry and a big consequence. Vercel's managed Stripe connector can now create one restricted API key for each agent or task, with only the permissions you select, and an old key can stay valid for up to 24 hours while it rotates. That reads like a settings toggle. It is an architecture decision: once every agent can carry its own key, you have to decide what each agent is allowed to touch, how your Next.js code picks the right key, and what you do during that 24 hour overlap.</p>
<p><strong>TL;DR</strong></p>
<ul>
<li>Vercel Connect Stripe managed keys give you one restricted key per agent or per task, with selected permissions. Treat each key as a service identity, not as a shared secret.</li>
<li>Stripe separates publishable (<code>pk_live_</code>), restricted (<code>rk_live_</code>) and secret (<code>sk_live_</code>) live keys and recommends granting only the permissions an integration needs. No agent should ever hold an <code>sk_live_</code> key.</li>
<li>Rotation is not instant. An old key can remain valid for up to 24 hours, so your audit tests and alerts have to cover that window.</li>
</ul>
<p>By the end of this guide you will have a per task permission matrix, a Next.js service identity layer that resolves the right restricted key on the server, and a set of rotation and audit tests that keep the whole thing honest. One warning first: a scoped key limits what a hijacked agent can do, but it does not stop the hijack. Read <a href="https://mudassirkhan.me/blog/ai-agent-security-prompt-injection">our production guide to prompt injection and AI agent security</a> before you give any agent access to payments.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/dfbf4834-c9de-44bf-9984-66c80709cc57.gif" alt="One key per agent: three agent cards, Support lookup with a read only key, Refund assistant with a refund key plus approval, and Revenue report with a read only key, each connected to Stripe; footer reads restricted keys only, no secret key in any agent" style="display:block;margin:0 auto" />

<h2>Key management announcement: what actually changed</h2>
<p>The usual pattern for an agent that talks to Stripe has been one key in one environment variable, shared by every tool the agent can call. If the support bot and the refund flow live in the same app, they share the same power. The managed Stripe connector in Vercel Connect changes the unit of credential from the app to the agent or the task.</p>
<p>Three facts shape the rest of this guide:</p>
<ol>
<li><strong>One restricted key per agent or task.</strong> Vercel's changelog says the connector creates a restricted key for each agent or task with the permissions you select.</li>
<li><strong>Rotation overlaps.</strong> The same changelog says old keys can remain valid for up to 24 hours during rotation.</li>
<li><strong>Stripe has three live key types.</strong> Stripe's key documentation lists publishable (<code>pk_live_</code>), restricted (<code>rk_live_</code>) and secret (<code>sk_live_</code>) keys, and recommends giving a key only the permissions its integration needs.</li>
</ol>
<p>As a Vercel Connect Stripe managed keys guide, the short version is this: the platform now makes least privilege cheap, and the work that remains is deciding the privileges. What the announcement does not give you is independent evidence that it improves security outcomes, or any promise that a payment action is safe. It is a vendor capability. The safety comes from how you scope it and how you test it.</p>
<h2>Choose a per task permission matrix</h2>
<p>Start from zero. Every agent begins with no access, and you add only what its job needs. OWASP's Excessive Agency entry (LLM06) gives the same advice for agents in general: read only credentials where possible, authorization in the context of the real user, and approval gates for high impact operations.</p>
<p>Here is the matrix I would start a typical SaaS billing setup with. The agents and resources are illustrative; replace them with your own.</p>
<table>
<thead>
<tr>
<th>Agent or task</th>
<th>Customers</th>
<th>Charges</th>
<th>Refunds</th>
<th>Subscriptions</th>
<th>Approval gate</th>
</tr>
</thead>
<tbody><tr>
<td>Support lookup</td>
<td>Read</td>
<td>Read</td>
<td>None</td>
<td>Read</td>
<td>No</td>
</tr>
<tr>
<td>Refund assistant</td>
<td>Read</td>
<td>Read</td>
<td>Write</td>
<td>None</td>
<td>Yes, every refund</td>
</tr>
<tr>
<td>Revenue report</td>
<td>None</td>
<td>Read</td>
<td>None</td>
<td>Read</td>
<td>No</td>
</tr>
<tr>
<td>Plan change</td>
<td>Read</td>
<td>None</td>
<td>None</td>
<td>Write</td>
<td>Yes, above your limit</td>
</tr>
</tbody></table>
<p>Four rules make the matrix useful instead of decorative:</p>
<ul>
<li><strong>One agent, one key.</strong> Two agents never share a key, even when their permissions match today.</li>
<li><strong>Read before write.</strong> If a task can be done with read access, it gets read access.</li>
<li><strong>Write means a gate.</strong> Any key that can move money or change a plan sits behind a human approval.</li>
<li><strong>No secret keys.</strong> An <code>sk_live_</code> key never reaches an agent, a tool or a prompt.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/0fe00995-3db9-4100-88f5-99c0be8daefc.png" alt="Illustrative per task permission matrix: Support lookup reads customers, charges and subscriptions; Refund assistant reads customers and charges and writes refunds behind an approval gate; Revenue report reads charges and subscriptions; Plan change reads customers and writes subscriptions behind an approval gate" style="display:block;margin:0 auto" />

<p>Put the matrix in code so the rest of the system can read it. This file becomes the source of truth you copy from when you configure each key in Vercel Connect, and the tests later in this guide compare against it.</p>
<pre><code class="language-ts">// lib/agent-permissions.ts
export type Access = "none" | "read" | "write";
export type Resource = "customers" | "charges" | "refunds" | "subscriptions";

type AgentPolicy = Record&lt;Resource, Access&gt; &amp; { approval: boolean };

export const AGENT_PERMISSIONS = {
  "support-lookup": { customers: "read", charges: "read", refunds: "none", subscriptions: "read", approval: false },
  "refund-assistant": { customers: "read", charges: "read", refunds: "write", subscriptions: "none", approval: true },
  "revenue-report": { customers: "none", charges: "read", refunds: "none", subscriptions: "read", approval: false },
  "plan-change": { customers: "read", charges: "none", refunds: "none", subscriptions: "write", approval: true },
} as const satisfies Record&lt;string, AgentPolicy&gt;;

export type AgentId = keyof typeof AGENT_PERMISSIONS;
</code></pre>
<p>If you are still deciding how to split work between agents in the first place, the role boundaries in my <a href="https://mudassirkhan.me/blog/multi-agent-system-architecture">multi agent system architecture guide</a> map neatly onto key boundaries: one role, one key, one row in this table.</p>
<h2>Next.js service identity design</h2>
<p>The best practices for Vercel Connect Stripe managed keys inside a Next.js app come down to one idea: the server decides which identity a request runs as, and the model never does. Three layers make that real.</p>
<ol>
<li><strong>Session check.</strong> The human user behind the request must be allowed to do the thing. This is the user context authorization OWASP asks for.</li>
<li><strong>Approval gate.</strong> For any agent whose row says approval, the action waits for a person.</li>
<li><strong>Key resolver.</strong> A server only function maps an agent id to its restricted key. The agent id comes from the route, never from model output.</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/a9097a36-e1cf-426f-b89b-4291f9048922.gif" alt="Next.js service identity flow in five steps: 1 User request, 2 Session check, 3 Approval gate, 4 Key resolver, 5 Stripe API; footer reads the server picks the key, never the model" style="display:block;margin:0 auto" />

<p>How the managed key reaches your runtime depends on how you wire Vercel Connect into your project, so check the connector docs for your setup. The resolver below assumes each agent's key is available to the server under its own variable name, which is the convention I use.</p>
<pre><code class="language-ts">// lib/stripe-for-agent.ts
import "server-only";
import Stripe from "stripe";
import type { AgentId } from "./agent-permissions";

// One variable per agent. The names are this project's convention.
export const KEY_ENV: Record&lt;AgentId, string&gt; = {
  "support-lookup": "STRIPE_KEY_SUPPORT_LOOKUP",
  "refund-assistant": "STRIPE_KEY_REFUND_ASSISTANT",
  "revenue-report": "STRIPE_KEY_REVENUE_REPORT",
  "plan-change": "STRIPE_KEY_PLAN_CHANGE",
};

export function stripeForAgent(agent: AgentId): Stripe {
  const key = process.env[KEY_ENV[agent]];
  if (!key) throw new Error(`No Stripe key configured for ${agent}`);
  if (process.env.NODE_ENV === "production" &amp;&amp; !key.startsWith("rk_live_")) {
    throw new Error(`${agent} must run on a restricted key`);
  }
  return new Stripe(key);
}
</code></pre>
<p>The route handler is where the three layers meet. Notice that the agent id is a constant in the file, not a parameter.</p>
<pre><code class="language-ts">// app/api/agents/refund/route.ts
import { NextResponse } from "next/server";
import { stripeForAgent } from "@/lib/stripe-for-agent";
import { getSession } from "@/lib/auth";
import { requestApproval } from "@/lib/approvals";

export async function POST(req: Request) {
  const session = await getSession();
  if (!session?.user.canIssueRefunds) {
    return NextResponse.json({ error: "forbidden" }, { status: 403 });
  }

  const { chargeId, amount, reason } = await req.json();
  const approval = await requestApproval({
    requestedBy: session.user.id,
    action: "refund",
    chargeId,
    amount,
    reason,
  });
  if (approval.status !== "approved") {
    return NextResponse.json({ status: "pending_approval", approvalId: approval.id }, { status: 202 });
  }

  const stripe = stripeForAgent("refund-assistant");
  const refund = await stripe.refunds.create(
    { charge: chargeId, amount },
    { idempotencyKey: `refund_${approval.id}` },
  );
  return NextResponse.json({ refundId: refund.id });
}
</code></pre>
<p>The <code>server-only</code> import makes a client bundle that touches the resolver fail at build time, and the idempotency key tied to the approval id means a retried request cannot refund twice.</p>
<h2>Rotation and audit tests</h2>
<p>The implementation of Vercel Connect Stripe managed keys is only as good as the checks that run after the first week, when someone adds a fifth agent in a hurry. Three tests catch most of the drift.</p>
<pre><code class="language-ts">// tests/agent-keys.test.ts
import { describe, it, expect } from "vitest";
import { AGENT_PERMISSIONS, type AgentId } from "@/lib/agent-permissions";
import { KEY_ENV } from "@/lib/stripe-for-agent";

const agents = Object.keys(AGENT_PERMISSIONS) as AgentId[];

describe("agent Stripe keys", () =&gt; {
  it("never hands an agent a secret or publishable key", () =&gt; {
    for (const agent of agents) {
      const key = process.env[KEY_ENV[agent]] ?? "";
      expect(key.startsWith("sk_live_")).toBe(false);
      expect(key.startsWith("pk_live_")).toBe(false);
    }
  });

  it("gives every agent its own key", () =&gt; {
    const keys = agents.map((agent) =&gt; process.env[KEY_ENV[agent]]);
    expect(new Set(keys).size).toBe(keys.length);
  });

  it("keeps the permission matrix under review", () =&gt; {
    expect(AGENT_PERMISSIONS).toMatchSnapshot();
  });
});
</code></pre>
<p>The snapshot test is the quiet hero. Any change to who can write what fails CI until a reviewer updates the snapshot on purpose, which turns a permission change into a visible diff.</p>
<p>Rotation needs one more piece. Because an old key can stay valid for up to 24 hours, you want to know which key each call actually used. Log a fingerprint, never the key itself.</p>
<pre><code class="language-ts">// lib/key-fingerprint.ts
import { createHash } from "node:crypto";

export function keyFingerprint(key: string): string {
  return createHash("sha256").update(key).digest("hex").slice(0, 12);
}

// In the resolver, after picking the key:
// logger.info({ agent, key: keyFingerprint(key), op: "refunds.create" });
</code></pre>
<p>After a rotation, the old fingerprint should disappear from your logs as soon as the new deploy is live. If it keeps showing up, some process is still holding the old key. And if you rotated because a key leaked, assume the leaked key keeps working for the full window: pause that agent's route until the 24 hours have passed.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/ebd16f2c-37b3-47f5-bf39-fd25e69a698a.gif" alt="Rotation overlap window: Rotate, new key deployed; Overlap, old key still valid for up to 24 hours; Revoked, old fingerprint gone from logs" style="display:block;margin:0 auto" />

<h2>Operational limitations</h2>
<p>Be honest with your team about what this design does not do.</p>
<ul>
<li><strong>It is a vendor capability.</strong> The changelog describes a feature. There is no independent measurement yet showing that managed keys reduce incidents, and nothing in it guarantees that any payment action is safe.</li>
<li><strong>Scope limits reach, not intent.</strong> A refund key can still refund the wrong charge. That is why the approval gate and the session check exist.</li>
<li><strong>Permissions are not business rules.</strong> A key describes which resources it can touch. Limits like a maximum refund amount belong in your route handlers.</li>
<li><strong>The overlap is real exposure.</strong> Up to 24 hours of a valid old key is a window you plan for, not one you ignore.</li>
<li><strong>Key count grows.</strong> More agents means more keys to audit. The matrix file and the tests above keep that manageable.</li>
</ul>
<p><strong>Use per task keys when</strong> an agent can write to Stripe, when several agents share one app, or when you need to explain to an auditor exactly what each automated actor can do. <strong>A single restricted key is often enough when</strong> you run one read only reporting job and nothing else.</p>
<h2>My take</h2>
<p>This is the cheapest security control most agent backends will add this year. It costs a table, a resolver and three tests. The part teams skip is the approval gate, because it slows the demo down. I would rather ship a slower refund agent than explain an automated refund run to a finance lead.</p>
<h2>FAQ</h2>
<h3>How do I implement vercel connect stripe managed keys safely?</h3>
<p>Write a per task permission matrix first, give each agent its own restricted key from it, resolve keys on the server only, put write capable agents behind an approval gate and a session check, and add tests that reject <code>sk_live_</code> and <code>pk_live_</code> keys, catch shared keys and snapshot the matrix.</p>
<h3>What changed with Vercel Connect Stripe managed keys in this release?</h3>
<p>The managed Stripe connector can now create one restricted API key for each agent or task with the permissions you select, and old keys can remain valid for up to 24 hours during rotation.</p>
<h3>Does an agent ever need a Stripe secret key?</h3>
<p>No. Stripe recommends granting only the permissions an integration needs, and a restricted key with the right resources covers agent work. Keep <code>sk_live_</code> keys out of every agent path.</p>
<h3>What happens to the old key when I rotate?</h3>
<p>It can keep working for up to 24 hours. Log key fingerprints so you can see when it stops being used, and pause the agent during that window if the rotation was caused by a leak.</p>
<p><strong>Related reading:</strong> <a href="https://dev.to/mudassirworks/persistent-agents-need-a-workspace-not-a-bigger-prompt-1dc5">Persistent Agents Need a Workspace, Not a Bigger Prompt</a> and <a href="https://medium.com/@mudassir00seven/ai-agent-evals-need-live-internet-containment-before-production-realism-1434676aead4">AI Agent Evals Need Live Internet Containment Before Production Realism</a>.</p>
<p>If you are choosing the agent framework that will sit on top of these keys, <a href="https://mudassirkhan.me/tools/ai-agent-framework-chooser">the AI agent framework chooser</a> helps you compare the options for your use case.</p>
<p><em>Sources:</em> <a href="https://vercel.com/changelog/vercel-connect-adds-managed-stripe-api-keys"><em>Vercel changelog on managed Stripe API keys</em></a><em>,</em> <a href="https://docs.stripe.com/keys"><em>Stripe API keys documentation</em></a><em>,</em> <a href="https://genai.owasp.org/llmrisk/llm062025-excessive-agency/"><em>OWASP LLM06 Excessive Agency</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[GitHub Apps Enterprise Installation: Migrating Automation from PATs to Scoped Permissions]]></title><description><![CDATA[GitHub just made enterprise installations for GitHub Apps generally available, with permission surfaces that now reach governance, security and enterprise…]]></description><link>https://mudassirworks.hashnode.dev/github-apps-enterprise-installation-migrating-automation-from-pats-to-scoped-permissions</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/github-apps-enterprise-installation-migrating-automation-from-pats-to-scoped-permissions</guid><category><![CDATA[GitHub]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Security]]></category><category><![CDATA[automation]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Wed, 04 Nov 2026 18:44:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/392b169f-16ff-4173-90dc-f22bb57ae029.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>GitHub just made enterprise installations for GitHub Apps generally available, with permission surfaces that now reach governance, security and enterprise administration, and support noted for GHES 3.24. If your release scripts, audit exports and triage bots still run on a personal access token that belongs to whoever set them up, this is the moment to move them. A GitHub Apps enterprise installation gives each automation its own identity and only the permissions you grant it, instead of everything one person can reach.</p>
<p><strong>TL;DR</strong></p>
<ul>
<li>GitHub Apps can now be installed at the enterprise level with expanded permissions for governance, security and enterprise administration. GHES support is noted for version 3.24.</li>
<li>A PAT is a person's power lent to a script. An installation is an app identity with a permission list you wrote. Migrate one workflow at a time and map each to the smallest permission set.</li>
<li>RFC 9700 and OWASP LLM06 point the same way: narrow scopes, short lived credentials, and a human approval for high impact actions, especially when an AI agent holds the token.</li>
</ul>
<p>By the end of this guide you will have a workflow to permission map, a working installation token example in TypeScript, and a rollout and rollback checklist you can run this sprint. If your automations are part of a bigger pipeline, my guide to <a href="https://mudassirkhan.me/blog/ai-agent-workflow-automation">building production AI agent workflow automation</a> covers the orchestration side; this article stays on credentials.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/82127040-a3fd-4792-8edc-adccebe63701.gif" alt="GitHub Apps enterprise installation compared with a personal access token: the PAT card is tied to a person, reaches everything the user can reach, is long lived and leaves with the employee; the app installation card is tied to the app, holds only granted permissions, uses short lived tokens and survives staff changes" style="display:block;margin:0 auto" />

<h2>Enterprise API expansion: a GitHub Apps enterprise installation guide</h2>
<p>Until now, a lot of enterprise automation had a quiet dependency on a human account. An enterprise admin created a classic PAT with broad scopes, pasted it into a secret store, and every script that needed enterprise data used it. When that admin changed teams, someone discovered the dependency the hard way.</p>
<p>The GitHub changelog entry changes the default option. Three facts matter for your migration:</p>
<ol>
<li><strong>Enterprise installations are GA.</strong> You install the app once at the enterprise level instead of chasing every organization.</li>
<li><strong>The permission surface grew.</strong> GitHub describes expanded permissions across governance, security and enterprise administration, the areas where PATs used to be the only practical choice.</li>
<li><strong>GHES is covered.</strong> Support is noted for GitHub Enterprise Server 3.24, so self hosted teams can plan the same move once they upgrade.</li>
</ol>
<p>What the announcement does not do is pick permissions for you. An app with every permission ticked is a PAT with a nicer name. The real work is the mapping in the next section.</p>
<h2>Map workflows to app permissions</h2>
<p>Start with an inventory. List every automation that authenticates to GitHub, the token it uses, and the actions it actually performs. Not the scopes the token has, the calls the code makes. In my experience the gap between those two lists is where the risk lives: a token with admin scope that only ever reads issues.</p>
<p>Then give each workflow its own row and its own smallest permission set:</p>
<table>
<thead>
<tr>
<th>Workflow</th>
<th>What it really does</th>
<th>App permission</th>
<th>Access</th>
</tr>
</thead>
<tbody><tr>
<td>Release tagger</td>
<td>Creates tags and releases in 1 repo</td>
<td>Contents</td>
<td>Write, one repo</td>
</tr>
<tr>
<td>Triage bot</td>
<td>Labels and comments on issues</td>
<td>Issues</td>
<td>Write</td>
</tr>
<tr>
<td>Security report</td>
<td>Reads code scanning alerts</td>
<td>Code scanning alerts</td>
<td>Read</td>
</tr>
<tr>
<td>Org audit export</td>
<td>Reads org settings for compliance</td>
<td>Administration</td>
<td>Read</td>
</tr>
</tbody></table>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/89bc9670-9503-4fd7-870b-1219e55f85a2.jpg" alt="Illustrative workflow to permission map for a GitHub Apps enterprise installation: Release tagger gets Contents write on one repo, Triage bot gets Issues write, Security report gets Code scanning read, Org audit export gets Administration read" style="display:block;margin:0 auto" />

<p>Two rules keep this map honest. First, split apps by blast radius, not by team: a read only reporting app and a write capable release app should be separate apps, even if one team owns both. Second, restrict repository access on the installation itself. A release tagger that can write to one repo cannot damage any other repo in the enterprise.</p>
<p>Here is a small script that turns your inventory file into a review list, so nobody approves an app without seeing what it can do:</p>
<pre><code class="language-ts">// scripts/permission-review.ts
type Access = "read" | "write";
interface WorkflowRow {
  workflow: string;
  permissions: Record&lt;string, Access&gt;;
  repos: string[] | "all";
}

const inventory: WorkflowRow[] = [
  { workflow: "release-tagger", permissions: { contents: "write" }, repos: ["platform/api"] },
  { workflow: "triage-bot", permissions: { issues: "write" }, repos: "all" },
  { workflow: "security-report", permissions: { security_events: "read" }, repos: "all" },
];

for (const row of inventory) {
  const writes = Object.entries(row.permissions).filter(([, a]) =&gt; a === "write");
  const wide = row.repos === "all" &amp;&amp; writes.length &gt; 0;
  console.log(`${row.workflow}: ${writes.length} write permission(s)${wide ? " on ALL repos, review" : ""}`);
}
</code></pre>
<h2>Compare PATs and installation identity: best practices</h2>
<p>The difference is not cosmetic. It changes who the credential belongs to and how long it lives.</p>
<table>
<thead>
<tr>
<th>Question</th>
<th>Personal access token</th>
<th>App installation</th>
</tr>
</thead>
<tbody><tr>
<td>Who is the actor?</td>
<td>A person</td>
<td>The app</td>
</tr>
<tr>
<td>What can it reach?</td>
<td>Whatever that user can reach</td>
<td>Only the granted permissions and repos</td>
</tr>
<tr>
<td>How long does a token live?</td>
<td>Until it expires or is revoked</td>
<td>Short lived, minted on demand</td>
</tr>
<tr>
<td>What happens when the owner leaves?</td>
<td>Automation breaks or keeps hidden power</td>
<td>Nothing, the app stays</td>
</tr>
<tr>
<td>What does the audit log show?</td>
<td>The user's name</td>
<td>The app's name</td>
</tr>
</tbody></table>
<p>The best practices that fall out of this table are simple. Keep the app's private key in your secret manager, never in a repo. Mint an installation token at the start of each job instead of caching one. And name each app after its job, so an audit log line reads like a sentence.</p>
<p>Minting a token in a Node job looks like this with Octokit:</p>
<pre><code class="language-ts">// lib/github-app.ts
import { App } from "octokit";

const app = new App({
  appId: process.env.GH_APP_ID!,
  privateKey: process.env.GH_APP_PRIVATE_KEY!,
});

export async function releaseClient(installationId: number) {
  // Each call mints a fresh, short lived installation token
  return app.getInstallationOctokit(installationId);
}

const gh = await releaseClient(Number(process.env.GH_INSTALLATION_ID));
await gh.rest.git.createRef({
  owner: "platform",
  repo: "api",
  ref: "refs/tags/v4.12.0",
  sha: process.env.RELEASE_SHA!,
});
</code></pre>
<p>Notice what is missing: no user, no long lived secret in the job, no scope wider than the release repo.</p>
<h2>OAuth and least privilege principles in your implementation</h2>
<p>GitHub Apps sit on OAuth ideas, and the current security guidance is worth reading before you design scopes. IETF RFC 9700 is a Best Current Practice that updates OAuth 2.0 security guidance and the older RFCs 6749, 6750 and 6819. Its direction is consistent: restrict privileges to the minimum, keep tokens short lived, and limit where a token can be used.</p>
<p>The same logic applies with more force when an AI agent holds the credential. OWASP's LLM06 Excessive Agency entry recommends granting agents the narrowest tool and downstream permissions and requiring approval for high impact actions. An agent that can open pull requests should not also be able to change branch protection. If you are wiring a coding agent into GitHub, my <a href="https://mudassirkhan.me/blog/ai-agent-security-prompt-injection">AI agent security and prompt injection defense guide</a> shows why a scoped token limits the damage of a hijacked prompt but never prevents it.</p>
<p>In practice, an implementation that follows both looks like this:</p>
<pre><code class="language-ts">// lib/approval-gate.ts
const HIGH_IMPACT = new Set(["administration:write", "members:write", "actions:write"]);

export function requiresApproval(permission: string, actor: "human" | "agent") {
  return actor === "agent" &amp;&amp; HIGH_IMPACT.has(permission);
}

// in the agent tool handler
if (requiresApproval("administration:write", "agent")) {
  throw new Error("Needs a human approval ticket before this call");
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/3c5dd1e6-6cda-4187-8596-8abcc7a80a8a.gif" alt="Five step GitHub Apps enterprise installation rollout: 1 Inventory PATs, 2 Map permissions, 3 Install the app, 4 Run in parallel, 5 Revoke the PAT, with a rollback path back to the PAT during the parallel run" style="display:block;margin:0 auto" />

<h2>Rollout/rollback checklist</h2>
<p>Migrate one workflow per change, never the whole estate at once. For each one:</p>
<ol>
<li><strong>Inventory.</strong> Record the PAT, its owner, its scopes and the API calls the workflow makes.</li>
<li><strong>Map.</strong> Write the smallest permission set and the exact repos for this workflow.</li>
<li><strong>Install.</strong> Create the app, install it at the enterprise or org level, restrict repository access.</li>
<li><strong>Run in parallel.</strong> Switch the job to the app token, keep the PAT valid but unused, and watch the audit log for the app's name.</li>
<li><strong>Revoke.</strong> After a clean week of runs, revoke the PAT and delete its secret.</li>
</ol>
<p>Rollback stays cheap as long as step 4 exists: point the job back at the PAT secret and redeploy. Once you revoke, rollback means minting a new PAT, which is exactly the habit you are trying to break, so do not skip the parallel run.</p>
<p><strong>Use an app installation when</strong> a workflow runs unattended, touches more than one repo, or outlives the person who wrote it. <strong>A fine grained PAT is still fine when</strong> you run a personal script against your own repos and nothing else depends on it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/a8cc34a7-eba2-4c14-a663-bd0ffa417d6e.gif" alt="Three least privilege rules for GitHub App automation: 01 None by default, 02 Read where needed, 03 Write behind approval" style="display:block;margin:0 auto" />

<h2>My take</h2>
<p>This is one of the few security upgrades that also removes operational pain. The broken automation after an offboarding, the mystery admin token in a secret store, the audit line that blames a person for a bot's action: all of that goes away. The part teams skip is the parallel run, because the new token works on the first try and revoking feels done. Keep the old path alive for a week anyway.</p>
<h2>FAQ</h2>
<h3>How do I implement github apps enterprise installation safely?</h3>
<p>Inventory every PAT and the calls each workflow makes, map each workflow to its own app with the smallest permission set and the exact repos, mint installation tokens per job, put high impact permissions behind a human approval, run the app in parallel with the PAT, then revoke the PAT.</p>
<h3>What changed with github apps enterprise installation in this release?</h3>
<p>GitHub made enterprise installations for GitHub Apps generally available, with expanded permissions across governance, security and enterprise administration, and noted support for GHES 3.24.</p>
<h3>Should AI agents use a GitHub App instead of a PAT?</h3>
<p>Yes. OWASP recommends the narrowest permissions for agents and approval for high impact actions, and an app installation lets you give an agent exactly that without lending it a person's access.</p>
<p><strong>Related reading:</strong> <a href="https://dev.to/mudassirworks/github-copilot-mcp-usage-metrics-without-false-signals-303e">GitHub Copilot MCP Usage Metrics Without False Signals</a> and <a href="https://medium.com/@mudassir00seven/openais-sandbox-findings-change-how-leaders-should-design-agent-controls-2cb3fe1b004f">OpenAI Sandbox Findings Change How Leaders Should Design Agent Controls</a>.</p>
<p>If you want a second pair of eyes on how agents and automations get credentials in your stack, I help teams with exactly that through <a href="https://mudassirkhan.me/services/agentic-ai-consulting">agentic AI consulting</a>.</p>
<p><em>Sources:</em> <a href="https://github.blog/changelog/"><em>GitHub changelog on enterprise installations for GitHub Apps</em></a><em>,</em> <a href="https://datatracker.ietf.org/doc/html/rfc9700"><em>IETF RFC 9700</em></a><em>,</em> <a href="https://genai.owasp.org/llmrisk/llm062025-excessive-agency/"><em>OWASP LLM06 Excessive Agency</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[UGC Fresh Data Program Integration: How Google's Pipeline Differs from the Indexing API]]></title><description><![CDATA[Google just published the technical eligibility and freshness requirements for its UGC Fresh Data Program, a dedicated ingestion pipeline for large user…]]></description><link>https://mudassirworks.hashnode.dev/ugc-fresh-data-program-integration-how-google-s-pipeline-differs-from-the-indexing-api</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/ugc-fresh-data-program-integration-how-google-s-pipeline-differs-from-the-indexing-api</guid><category><![CDATA[SEO]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[Google]]></category><category><![CDATA[architecture]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Sat, 31 Oct 2026 18:42:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/1301e163-cdb8-41c7-8430-d5445f23f00e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Google just published the technical eligibility and freshness requirements for its UGC Fresh Data Program, a dedicated ingestion pipeline for large user generated content platforms. The surprising part is not that it exists. It is that Google built it as a third path, separate from ordinary crawling and separate from the Indexing API, and still promises nothing about visibility.</p>
<p><strong>TL;DR</strong></p>
<ul>
<li>Google now runs three distinct paths into Search for content: ordinary crawling, the Indexing API, and the UGC Fresh Data Program. They are separate pipelines with separate rules.</li>
<li>The program is selective. Google asks applicants to expect roughly 6 to 8 weeks for a response, and it targets eligible high volume UGC platforms, not every site with comments.</li>
<li>The freshness bar is concrete: new UGC within minutes, engagement counters updated within 72 hours. Even after you are in, inclusion in Search is not guaranteed.</li>
</ul>
<p>This guide treats UGC Fresh Data Program integration as an engineering problem: which path your content actually travels, what the eligibility review checks, how to build the event pipeline that hits those freshness windows, and how your structured data should behave either way. The examples use TypeScript and Next.js, because that is the stack I build forum and community products in. If your posts enter the system through a form, our walkthrough on <a href="https://mudassirkhan.me/blog/next-js-form-server-actions">building a Next.js form with Server Actions and Zod</a> shows the validated submission step that everything below hangs off.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/966dc974-7be8-4e89-b511-461e78bf1488.gif" alt="Three paths into Google Search: Crawl, where Googlebot finds pages on a recrawl schedule; Indexing API, where you send URL notifications; and UGC Fresh Data, a dedicated ingestion pipeline where new posts arrive within minutes; footer reads separate pipelines, no path guarantees visibility" style="display:block;margin:0 auto" />

<h2>The three ingestion paths</h2>
<p>Most teams think of Google indexing as one funnel with a few accelerators bolted on. That model is now wrong. There are three paths, and Google describes the UGC Fresh Data Program as distinct from both of the others.</p>
<ol>
<li><strong>Ordinary crawling.</strong> Googlebot discovers and recrawls your pages on its own schedule. You influence it with sitemaps, internal links and server health, but you do not control timing.</li>
<li><strong>The Indexing API.</strong> You notify Google about specific URLs. It is a notification channel, not a content channel, and it is not the UGC program.</li>
<li><strong>The UGC Fresh Data Program.</strong> A dedicated ingestion pipeline for eligible high volume UGC platforms, designed around freshness rather than normal recrawl latency.</li>
</ol>
<p>The practical consequence: a platform that wants the third path still needs the first one to work perfectly. Your pages remain the canonical, crawlable source of truth. The fresh data pipeline is an extra lane for speed, not a replacement for being a well built website.</p>
<p>Here is how I would encode that routing decision in code, so nobody on the team quietly assumes the fast lane exists:</p>
<pre><code class="language-ts">type IngestionPath = "crawl" | "indexing-api" | "ugc-fresh-data";

interface PlatformProfile {
  acceptedIntoUgcProgram: boolean; // only true after Google approves the application
  usesIndexingApiForThisContent: boolean;
}

export function ingestionPathsFor(profile: PlatformProfile): IngestionPath[] {
  // Crawling is never optional: it is the baseline every other path assumes.
  const paths: IngestionPath[] = ["crawl"];
  if (profile.usesIndexingApiForThisContent) paths.push("indexing-api");
  if (profile.acceptedIntoUgcProgram) paths.push("ugc-fresh-data");
  return paths;
}

// A community product before acceptance:
console.log(ingestionPathsFor({ acceptedIntoUgcProgram: false, usesIndexingApiForThisContent: false }));
// -&gt; [ 'crawl' ]
</code></pre>
<p>Boring on purpose. The function makes one point explicit in your codebase: crawl is always in the list.</p>
<h2>Technical eligibility requirements</h2>
<p>Google's documentation and the independent coverage agree on the shape of the eligibility process: it is selective, it starts with an application, and it is not a general purpose submission API. Google tells applicants to expect roughly 6 to 8 weeks for an application response.</p>
<p>That timeline matters for planning. If your growth plan assumes fresh data ingestion next sprint, it is already late. Treat the application as a parallel track and keep shipping improvements to the crawl path while you wait.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/f1c960cc-4c1a-45bc-8e03-32089066f9bd.gif" alt="From application to ingestion in five steps: Apply, Selective review, Response in 6 to 8 weeks, Connect the pipeline, Keep it fresh" style="display:block;margin:0 auto" />

<p>What can you do before applying? Make sure the platform already behaves the way a fresh data partner would have to behave. A small readiness check against your own event log answers that. The thresholds below are illustrative engineering targets, not Google's criteria:</p>
<pre><code class="language-ts">interface PostEvent {
  postId: string;
  createdAt: number;   // ms since epoch, when the user hit submit
  publishedAt: number; // ms since epoch, when the canonical URL returned 200
}

const MINUTE = 60_000;

export function publishLagReport(events: PostEvent[]) {
  const lags = events.map((e) =&gt; e.publishedAt - e.createdAt).sort((a, b) =&gt; a - b);
  const p95 = lags[Math.floor(lags.length * 0.95)] ?? 0;
  return {
    posts: events.length,
    p95LagMinutes: +(p95 / MINUTE).toFixed(1),
    // Internal target: a post is live on its own URL in under 2 minutes at p95.
    readyForMinuteLevelFreshness: p95 &lt; 2 * MINUTE,
  };
}
</code></pre>
<p>If your own pages take twenty minutes to become reachable after a user submits, no external pipeline will make you look fresh. Fix the internal lag first.</p>
<h2>Freshness and interaction updates</h2>
<p>This is the part of the published requirements I find most useful, because it gives two concrete windows. Google recommends sending new UGC within minutes, and updating engagement counters within 72 hours. Those numbers tell you the program is built around freshness, not around the latency of a normal recrawl.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/fe712244-331f-4a67-81b3-809dc3e00dc7.gif" alt="Two freshness windows recommended by Google: New posts are sent within minutes; likes, replies and views counters are updated within 72 hours" style="display:block;margin:0 auto" />

<p>Two windows means two lanes in your pipeline. New content is latency sensitive, so it goes out on an event the moment a post is published. Counters change constantly, so they get batched and flushed well inside the 72 hour window instead of firing on every like.</p>
<pre><code class="language-ts">type Outbound =
  | { kind: "new-post"; postId: string; url: string }
  | { kind: "counters"; postId: string; replies: number; likes: number };

const HOUR = 3_600_000;
const COUNTER_FLUSH_EVERY = 6 * HOUR; // well inside the 72 hour window

const pendingCounters = new Map&lt;string, Extract&lt;Outbound, { kind: "counters" }&gt;&gt;();

export async function onPostPublished(postId: string, url: string, send: (m: Outbound) =&gt; Promise&lt;void&gt;) {
  // Lane 1: new content leaves immediately.
  await send({ kind: "new-post", postId, url });
}

export function onEngagementChanged(postId: string, replies: number, likes: number) {
  // Lane 2: keep only the latest counters per post; the flusher sends them in batches.
  pendingCounters.set(postId, { kind: "counters", postId, replies, likes });
}

export async function flushCounters(send: (m: Outbound) =&gt; Promise&lt;void&gt;) {
  for (const update of pendingCounters.values()) await send(update);
  pendingCounters.clear();
}

setInterval(() =&gt; flushCounters(async (m) =&gt; console.log("send", m)), COUNTER_FLUSH_EVERY);
</code></pre>
<p>The <code>send</code> function is deliberately abstract. The transport for accepted partners is defined by Google's program documentation; I am not going to guess at an API shape I have not integrated. What you control today is the architecture: an outbox with two lanes, keyed by post id, that you can point at whatever transport you are given.</p>
<h2>Structured data integration for ordinary sites</h2>
<p>Even if you never apply, the program is a strong hint about what Google values for UGC: stable URLs, accurate counters and content that is visible fast. The markup on your pages should carry the same truth your pipeline would send. A <code>schema.org</code> <code>DiscussionForumPosting</code> block in <code>JSON-LD</code>, generated from the same record that renders the page, keeps the two from drifting apart:</p>
<pre><code class="language-tsx">// app/threads/[id]/page.tsx
import { getThread } from "@/lib/threads";

export default async function ThreadPage({ params }: { params: Promise&lt;{ id: string }&gt; }) {
  const { id } = await params;
  const thread = await getThread(id);

  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "DiscussionForumPosting",
    headline: thread.title,
    text: thread.body,
    url: `https://forum.example.com/threads/${thread.id}`,
    datePublished: thread.createdAtIso,
    author: { "@type": "Person", name: thread.authorName },
    interactionStatistic: [
      { "@type": "InteractionCounter", interactionType: "https://schema.org/CommentAction", userInteractionCount: thread.replyCount },
      { "@type": "InteractionCounter", interactionType: "https://schema.org/LikeAction", userInteractionCount: thread.likeCount },
    ],
  };

  return (
    &lt;article&gt;
      &lt;script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} /&gt;
      &lt;h1&gt;{thread.title}&lt;/h1&gt;
      &lt;p&gt;{thread.body}&lt;/p&gt;
      &lt;footer&gt;{thread.replyCount} replies · {thread.likeCount} likes&lt;/footer&gt;
    &lt;/article&gt;
  );
}
</code></pre>
<p>The rule I follow: the counter in the markup and the counter in the footer come from one field. When they disagree, you are telling a crawler one thing and a reader another. If you are building this kind of community product on Next.js and want a second pair of eyes on the architecture, that is the work behind our <a href="https://mudassirkhan.me/services/nextjs-for-ai-products">Next.js for AI products service</a>.</p>
<h2>Why inclusion is still not guaranteed</h2>
<p>The line in Google's documentation that every product manager should read twice: participation does not guarantee Search visibility. The program changes how fast your content can reach Google. It does not change whether Google decides that content deserves to be shown.</p>
<p>So the pipeline is necessary, not sufficient. Quality, duplication, spam handling and page experience still decide ranking. A platform that pushes thin or duplicated threads faster has simply found a quicker way to show Google its weak pages.</p>
<p>My take, as an opinion rather than a finding: the teams that will benefit most are the ones whose crawl path is already excellent. For them, the fresh data lane removes the last bit of latency. For everyone else, the 6 to 8 weeks of review is better spent on the readiness work in the checklist below.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/05a1d471-07d1-46ff-a3cd-65301b92abaf.png" alt="UGC freshness readiness checklist: publish events, not cron sweeps; a stable URL for every post; counters updated in one place; markup matches visible content; measure post to index lag; plan for no guarantee" style="display:block;margin:0 auto" />

<table>
<thead>
<tr>
<th>Situation</th>
<th>What to do</th>
</tr>
</thead>
<tbody><tr>
<td>Small community, steady posting</td>
<td>Perfect the crawl path: sitemaps, internal links, fast canonical URLs</td>
</tr>
<tr>
<td>Time sensitive URLs you already notify Google about</td>
<td>Keep the Indexing API where it fits; it is a separate path</td>
</tr>
<tr>
<td>High volume UGC platform with minute level freshness</td>
<td>Apply to the program and build the two lane outbox now</td>
</tr>
<tr>
<td>Accepted partner</td>
<td>Send new posts within minutes, counters within 72 hours, and keep pages canonical</td>
</tr>
</tbody></table>
<h2>FAQ</h2>
<h3>What changed in ugc fresh data program integration structured data?</h3>
<p>Google documented a dedicated ingestion path for eligible high volume UGC platforms, with published freshness targets: new content within minutes and engagement counters within 72 hours. It is separate from both crawling and the Indexing API. Your structured data still matters, because your pages remain the canonical source that crawling reads.</p>
<h3>How should teams adopt ugc fresh data program integration structured data?</h3>
<p>Start with readiness, not the application. Measure how long a post takes to become reachable on its own URL, generate markup and visible counters from one record, and build an outbox with a fast lane for new posts and a batched lane for counters. Then apply, and expect roughly 6 to 8 weeks for a response.</p>
<h3>Does the UGC Fresh Data Program replace the Indexing API?</h3>
<p>No. Google describes them as separate. The Indexing API notifies Google about URLs; the UGC program is its own ingestion pipeline with its own eligibility review.</p>
<h3>Will joining the program improve my rankings?</h3>
<p>Not by itself. Google states that participation does not guarantee Search visibility. It shortens the path, not the judgment.</p>
<p><strong>Related reading:</strong> <a href="https://dev.to/mudassirworks/nextjs-server-actions-vs-trpc-how-to-actually-choose-17e7">Next.js Server Actions vs tRPC: which one to pick for your AI app</a> and <a href="https://mudassirworks.hashnode.dev/next-js-security-hardening-middleware-server-actions-and-csp-patterns-that-hold-up">Next.js Security Hardening: Middleware, Server Actions, and CSP Patterns That Hold Up</a>.</p>
<p>If you are planning a UGC platform that has to be fast for users and for search engines, I help teams design exactly this pipeline; see <a href="https://mudassirkhan.me/services/nextjs-for-ai-products">how I build production Next.js products</a> for how that engagement works.</p>
]]></content:encoded></item><item><title><![CDATA[Next.js 16.4 Self Hosting and Cache Components: An Upgrade Checklist You Can Run Before Production]]></title><description><![CDATA[Next.js 16.4 made Cache Components the recommended path and switched them on by default for every new create-next-app project. Your existing app did not…]]></description><link>https://mudassirworks.hashnode.dev/next-js-16-4-self-hosting-and-cache-components-an-upgrade-checklist-you-can-run-before-production</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/next-js-16-4-self-hosting-and-cache-components-an-upgrade-checklist-you-can-run-before-production</guid><category><![CDATA[Next.js]]></category><category><![CDATA[webdev]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Devops]]></category><category><![CDATA[AI]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Tue, 27 Oct 2026 18:42:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/a23a5ba9-33a5-4e5f-a248-d64018534b5a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Next.js 16.4 made Cache Components the recommended path and switched them on by default for every new <code>create-next-app</code> project. Your existing app did not get that switch. That gap between what a fresh project does and what your upgraded project does is exactly where self hosted upgrades go wrong, and it is why the release thread filled up with migration and self hosting questions within hours.</p>
<p><strong>TL;DR</strong></p>
<ul>
<li>New projects on 16.4 start with Cache Components on. Existing apps keep their current caching model until you change it, so upgrading the version and adopting the model are two separate jobs.</li>
<li>Test four things before production: your caching assumptions, navigation and prefetch behavior, the self hosted build output, and a rollback you have actually rehearsed.</li>
<li>One independent production upgrade reported about 5% less shipped JavaScript and a 1,555 page build dropping from 83.9s to 49.1s. Treat that as a reason to measure your own app, not as a promise.</li>
</ul>
<p>This guide walks you through a nextjs 16.4 self hosting cache components checklist you can run in a staging environment in an afternoon. A quick way to get a clean reference point is to scaffold a fresh 16.4 project next to your real one and build something small in it, the way our <a href="https://mudassirkhan.me/blog/build-calculator-nextjs">step by step Next.js calculator build</a> does. That throwaway app shows you the new defaults, so every difference you later see in your real app is one you can explain.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/dd42908c-bb8c-4e55-8aad-4c8f0b5a4fed.gif" alt="Four upgrade gates for Next.js 16.4 (01 Inventory caching, 02 Test navigation, 03 Validate build output, 04 Rehearse rollback) rise in reading order, then the band Upgrade the version and adopt Cache Components in separate deploys wipes in and is highlighted" style="display:block;margin:0 auto" />

<h2>What changed in Next.js 16.4 self hosting and cache components</h2>
<p>Three facts from the release and the first migration write ups shape everything below:</p>
<ol>
<li><strong>Cache Components are the recommended path.</strong> The Next.js team now points new work at them, and new <code>create-next-app</code> projects enable them by default.</li>
<li><strong>Existing applications do not adopt the new model automatically.</strong> Independent migration guidance is explicit here: review caching, navigation and configuration behavior yourself instead of assuming the upgrade did it.</li>
<li><strong>There is a new upgrade command.</strong> The release adds <code>next upgrade --agent</code>. Whatever it changes in your repo, review its diff the way you would review any pull request.</li>
</ol>
<p>So the honest answer to "what changed for my app?" is: the version changed, the defaults for new projects changed, and your app's behavior changed only where you change it. That is good news for a self hosted team, because it means you control the rollout. It is also a trap, because a teammate who reads the release post and starts a new route with the new defaults is now mixing two caching models in one codebase.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/17d1a8f3-58f4-472a-84d3-5a6a56adb9f9.gif" alt="Comparison of an existing app upgraded to Next.js 16.4, which keeps its current caching model, against a new project on 16.4 with Cache Components on by default; a spotlight moves from one card to the other as each card object grows, then the line Existing apps do not adopt the new model automatically fades in and is underlined" style="display:block;margin:0 auto" />

<h2>Inventory current caching assumptions</h2>
<p>Before you change a single route, write down how your app caches today. Most teams cannot answer that from memory, because caching decisions live in dozens of files: a <code>revalidate</code> export here, a <code>fetch</code> option there, an <code>unstable_cache</code> wrapper someone added during an incident.</p>
<p>Run a small scanner over the repo and commit its output as a baseline. This one is plain Node with no dependencies:</p>
<pre><code class="language-js">// scripts/cache-inventory.mjs
import { readFileSync, readdirSync, statSync } from "node:fs";
import { join } from "node:path";

const patterns = {
  revalidateExport: /export\s+const\s+revalidate\s*=/,
  dynamicExport: /export\s+const\s+dynamic\s*=/,
  fetchCacheOption: /fetch\([^)]*cache\s*:/s,
  fetchNextRevalidate: /next\s*:\s*\{\s*revalidate/,
  unstableCache: /unstable_cache\(/,
  useCacheDirective: /["']use cache["']/,
};

function walk(dir, out = []) {
  for (const name of readdirSync(dir)) {
    if (name === "node_modules" || name.startsWith(".")) continue;
    const full = join(dir, name);
    if (statSync(full).isDirectory()) walk(full, out);
    else if (/\.(tsx?|jsx?|mjs)$/.test(name)) out.push(full);
  }
  return out;
}

const rows = [];
for (const file of walk("app")) {
  const src = readFileSync(file, "utf8");
  const hits = Object.entries(patterns)
    .filter(([, re]) =&gt; re.test(src))
    .map(([key]) =&gt; key);
  if (hits.length) rows.push({ file, hits: hits.join(",") });
}

console.table(rows);
console.log(`${rows.length} files carry an explicit caching decision`);
</code></pre>
<p>Run it with <code>node scripts/cache-inventory.mjs &gt; cache-baseline.txt</code> and keep the file in the upgrade branch. Now every route falls into one of three buckets:</p>
<ul>
<li><strong>Explicitly cached</strong> (a revalidate export, a fetch option, a cache wrapper). These are the routes most likely to behave differently once someone moves them to Cache Components.</li>
<li><strong>Explicitly dynamic</strong> (a <code>dynamic</code> export or per request data). Confirm they stay dynamic.</li>
<li><strong>Implicit</strong> (no caching code at all). These are the dangerous ones, because their behavior depends entirely on framework defaults.</li>
</ul>
<p>Write the bucket next to each route in the baseline file. You will use it in every later step.</p>
<h2>Test navigation and prefetch behavior</h2>
<p>Caching bugs rarely show up as errors. They show up as a user who saves a form, navigates back, and sees the old value. So test the journeys, not the pages.</p>
<p>Pick the five or six flows where stale data would hurt: checkout, account settings, a dashboard that shows money or quotas, anything with a mutation followed by a navigation. Then record what the browser actually requests on your current version and on the 16.4 candidate, and compare. A Playwright test makes that repeatable:</p>
<pre><code class="language-ts">// tests/navigation-freshness.spec.ts
import { test, expect } from "@playwright/test";

test("saved profile name is fresh after navigating back", async ({ page }) =&gt; {
  const requests: string[] = [];
  page.on("request", (req) =&gt; requests.push(`${req.method()} ${req.url()}`));

  await page.goto("/settings/profile");
  await page.getByLabel("Display name").fill("Ayesha Upgrade Test");
  await page.getByRole("button", { name: "Save" }).click();
  await expect(page.getByText("Saved")).toBeVisible();

  await page.getByRole("link", { name: "Dashboard" }).click();
  await page.getByRole("link", { name: "Settings" }).click();

  await expect(page.getByLabel("Display name")).toHaveValue("Ayesha Upgrade Test");

  // Keep the request log so you can diff it between versions.
  await test.info().attach("requests", { body: requests.join("\n") });
});
</code></pre>
<p>Run the suite against both builds and diff the attached request logs. You are looking for three things: a request that disappeared (something is now served from a cache you did not expect), a request that appeared (prefetching more than before, which matters if those routes are expensive), and any assertion that flips from pass to fail. Each of those goes into the matrix with the route's bucket from the inventory.</p>
<h2>Validate self hosting and build output</h2>
<p>On a managed platform, someone else checks that the build output runs. When you self host, that someone is you. This is the part of the nextjs 16.4 self hosting cache components production story that the release notes cannot test for you, because it depends on your container, your proxy and your disk.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/59b9f9ab-fd0d-48e7-aa22-43b829f67fbb.gif" alt="Self hosting validation path for a Next.js 16.4 upgrade: next build, standalone output, container image, staging smoke test, then promote or roll back; a spotlight moves along the path and the outcomes, then the benchmark note counts up to 83.9s on 16.3 and 49.1s on 16.4" style="display:block;margin:0 auto" />

<p>Build the candidate exactly the way production builds it. If you ship the standalone output in a container, that means the same Dockerfile, not a local <code>next start</code>:</p>
<pre><code class="language-dockerfile"># Dockerfile (candidate build, same as production)
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:22-alpine AS run
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]
</code></pre>
<p>Then run a smoke script against the staging container. It checks status codes and prints every cache related response header, so you can compare them with the current production build line by line:</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# scripts/smoke.sh  usage: ./scripts/smoke.sh https://staging.example.com
set -euo pipefail
BASE="$1"
for path in / /pricing /dashboard /api/health; do
  code=$(curl -s -o /dev/null -w "%{http_code}" "$BASE$path")
  echo "== $path  status $code"
  curl -s -D - -o /dev/null "$BASE$path" | grep -i -E "cache|age|vary" || true
done
</code></pre>
<p>While you are there, time the build. The independent write up that tested a 1,555 page site measured total build time falling from 83.9s on 16.3 to 49.1s on 16.4, and the same team saw roughly 5% less shipped JavaScript. Your numbers will differ. Record build time, image size and first load JavaScript for both versions in the matrix, because a regression in any of them is a reason to stop.</p>
<h2>Run a rollback ready upgrade</h2>
<p>An upgrade is only safe if going back is boring. Before the candidate touches production, prove you can return to the previous build in one command:</p>
<pre><code class="language-bash">#!/usr/bin/env bash
# scripts/rollback.sh  keeps the last known good image one command away
set -euo pipefail
PREVIOUS_TAG="$(cat .deploy/last-good-tag)"
docker pull "registry.example.com/web:${PREVIOUS_TAG}"
docker service update --image "registry.example.com/web:${PREVIOUS_TAG}" web
echo "Rolled back to ${PREVIOUS_TAG}"
</code></pre>
<p>Rehearse it in staging: deploy the 16.4 image, run the smoke script, roll back, run the smoke script again. If the rehearsal takes longer than a coffee, fix that first.</p>
<p>Two more rules keep the rollout calm:</p>
<ul>
<li><strong>Upgrade the version and adopt Cache Components in separate deploys.</strong> The first deploy should change nothing a user can see. Only then move routes to the new model, one bucket at a time, starting with explicitly cached routes that have good test coverage.</li>
<li><strong>Keep the request logs and the smoke output from every deploy.</strong> When someone reports stale data a week later, you want evidence, not memory.</li>
</ul>
<h2>The checklist (save this)</h2>
<table>
<thead>
<tr>
<th>Gate</th>
<th>What you check</th>
<th>Stop the rollout if</th>
</tr>
</thead>
<tbody><tr>
<td>Inventory caching</td>
<td>Every route sorted into cached, dynamic or implicit</td>
<td>Implicit routes have no owner</td>
</tr>
<tr>
<td>Test navigation</td>
<td>Request logs and freshness tests on both versions</td>
<td>A freshness assertion fails or requests change unexplained</td>
</tr>
<tr>
<td>Validate build output</td>
<td>Same Dockerfile, smoke script, cache headers, build time</td>
<td>Status codes or headers differ without a reason</td>
</tr>
<tr>
<td>Rehearse rollback</td>
<td>Deploy, smoke, roll back, smoke again in staging</td>
<td>Rollback needs more than one command</td>
</tr>
</tbody></table>
<h2>My take</h2>
<p>I think the safest reading of 16.4 is the boring one: upgrade the version this sprint, adopt the new caching model next sprint. The release is clearly pushing everyone toward Cache Components, and for new projects I would just take the default. For an app that already carries years of caching decisions, the risk is not the framework. The risk is a codebase where half the routes follow the old rules and half follow the new ones, and nobody wrote down which is which. The inventory step fixes that, and it costs one script.</p>
<h2>FAQ</h2>
<p><strong>What changed in nextjs 16.4 self hosting cache components?</strong> Next.js 16.4 makes Cache Components the recommended path and enables them by default for new <code>create-next-app</code> projects. It also adds <code>next upgrade --agent</code>. Existing applications keep their current caching model until you change it, so self hosted teams should test caching, navigation and build output explicitly.</p>
<p><strong>How should teams adopt nextjs 16.4 self hosting cache components?</strong> In two steps. First upgrade the version with no behavior changes and verify it with freshness tests, a smoke script against the real container and a rehearsed rollback. Then move routes to Cache Components one group at a time, starting with explicitly cached routes that have test coverage.</p>
<p><strong>Do existing apps get Cache Components automatically after upgrading?</strong> No. Migration guidance for 16.4 says existing applications do not adopt the new caching model automatically, which is why the inventory step comes first.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/de745a5e-98cc-4f65-83bd-23e88621e676.png" alt="Next.js 16.4 upgrade checklist: four gates with what to check and when to stop the rollout" style="display:block;margin:0 auto" />

<p><strong>Related reading:</strong> <a href="https://dev.to/mudassirworks/nextjs-app-router-caching-what-actually-gets-cached-and-what-doesnt-6ej">Next.js App Router caching: what actually gets cached</a> and <a href="https://dev.to/mudassirworks/react-server-components-and-ai-streaming-in-nextjs-patterns-that-actually-work-35pc">React Server Components and AI streaming patterns that work</a>.</p>
<p>If you are planning a Next.js upgrade for a product with AI features and want a second pair of eyes on the caching and self hosting plan, see how I work on <a href="https://mudassirkhan.me/services/nextjs-for-ai-products">Next.js for AI products</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Agent Persistent State, Files and Memory: How to Separate the Three Layers]]></title><description><![CDATA[Vercel Drives just reached general availability: persistent storage that survives individual Sandbox runtimes, 1 TiB by default and configurable up to 16…]]></description><link>https://mudassirworks.hashnode.dev/agent-persistent-state-files-and-memory-how-to-separate-the-three-layers</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/agent-persistent-state-files-and-memory-how-to-separate-the-three-layers</guid><category><![CDATA[AI]]></category><category><![CDATA[webdev]]></category><category><![CDATA[agents]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[architecture]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Sun, 25 Oct 2026 18:42:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/3d676462-97d6-4ee3-98fe-fb456aedbffc.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Vercel Drives just reached general availability: persistent storage that survives individual Sandbox runtimes, 1 TiB by default and configurable up to 16 TiB. That turns a fuzzy question into a concrete design decision for anyone shipping agents. Where does your agent keep what it remembers, where does it keep where it was, and where does it keep what it made? If the answer to all three is "the same place", your next crash will show you why that hurts.</p>
<p><strong>TL;DR</strong></p>
<ul>
<li>Agent persistence is three layers with three lifecycles: conversational memory, workflow state, and durable files. Store them separately and give each its own key.</li>
<li>Checkpoint workflow state at side effect boundaries (after a tool call commits, before the next one starts), keyed by a thread id, so a resume never repeats a payment or an email.</li>
<li>Mount files as a separate volume that state only points to by path and hash. Then test resume and fork on purpose, before production does it for you.</li>
</ul>
<p>This guide treats agent persistent state files memory as one architecture problem with three answers. If you want the wider map of memory types first (working, episodic, semantic, procedural), our <a href="https://mudassirkhan.me/blog/ai-agent-memory-management">guide to the four types of AI agent memory</a> covers that ground. Here we stay practical: what goes in which layer, where the checkpoints go, how the files attach, and how to prove the whole thing survives a crash.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/d9ce5b3d-6d1d-48ed-bfcd-d7efbb51e0ab.gif" alt="Three persistence layers for an AI agent: Memory holds the conversation and lives for the session, State holds the step and the plan and lives until the run ends, Files hold the workspace and outlive every runtime, with Drives at 1 TiB default and up to 16 TiB" style="display:block;margin:0 auto" />

<h2>What changed in agent persistent state files memory</h2>
<p>Three things moved recently, and together they make the separation hard to ignore:</p>
<ol>
<li><strong>Files became their own product.</strong> Vercel Drives is storage built to outlive the Sandbox runtime that wrote to it. A runtime can die and the next one picks up the same workspace.</li>
<li><strong>Memory has a lifecycle you choose.</strong> The OpenAI Agents SDK persists conversation history in sessions that live outside a single model call. Its <code>MemorySession</code> keeps that history in process, so it resets when the process exits. Same API, very different durability.</li>
<li><strong>State resumes by thread.</strong> LangGraph durable execution uses a checkpointer plus a thread identifier, so a workflow can resume after an interruption, even long after the original process ended.</li>
</ol>
<p>Read those three side by side and the pattern is obvious. Memory, state and files already ship as different products with different lifetimes. Your agent should model them the same way.</p>
<h2>Define the three persistence layers</h2>
<p>Here is the split I use. Each layer answers one question and has one owner.</p>
<table>
<thead>
<tr>
<th>Layer</th>
<th>Answers</th>
<th>Typical store</th>
<th>Lives until</th>
</tr>
</thead>
<tbody><tr>
<td>Memory</td>
<td>What was said and learned?</td>
<td>Session store (database or in process)</td>
<td>The session ends or is summarized</td>
</tr>
<tr>
<td>State</td>
<td>Where is the run right now?</td>
<td>Checkpointer keyed by thread id</td>
<td>The run completes</td>
</tr>
<tr>
<td>Files</td>
<td>What did the agent produce?</td>
<td>Mounted volume (a drive, a bucket)</td>
<td>You delete it</td>
</tr>
</tbody></table>
<p>Write the layers down as types before you write any storage code. It forces every field to pick a home:</p>
<pre><code class="language-ts">// persistence.ts
export type ThreadId = string;

export interface MemoryRecord {
  threadId: ThreadId;
  role: "user" | "assistant" | "tool";
  content: string;
  createdAt: number;
}

export interface RunState {
  threadId: ThreadId;
  step: number;                  // last completed step
  plan: string[];                // remaining steps
  pendingToolCall?: { id: string; name: string; args: unknown };
  artifacts: ArtifactRef[];      // pointers into the files layer, never contents
}

export interface ArtifactRef {
  path: string;                  // path inside the mounted workspace
  sha256: string;                // proves the file matches what the state expects
}

export interface PersistenceLayers {
  memory: { append(r: MemoryRecord): Promise&lt;void&gt;; load(t: ThreadId): Promise&lt;MemoryRecord[]&gt; };
  state: { save(s: RunState): Promise&lt;void&gt;; load(t: ThreadId): Promise&lt;RunState | null&gt; };
  files: { root(t: ThreadId): string };
}
</code></pre>
<p>The rule that matters: <code>RunState</code> holds references to files, never their bytes. The moment a checkpoint embeds a 40 MB CSV, every save gets slow and every fork copies data it does not need.</p>
<h2>Agent persistent state files memory architecture: choose checkpoint boundaries</h2>
<p>A checkpoint is only useful if resuming from it is safe. The safe places are side effect boundaries: right after a tool call has committed its effect and right before the next one starts. Checkpoint in the middle of a tool call and a resume will run that call twice.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/3994f03e-7be7-4898-bbaf-85d7f8fc2c7a.gif" alt="Checkpoint boundaries in an agent run: Plan, Call tool, Commit effect, Save checkpoint, Next step, built left to right, with the rule save after the effect commits and before the next call starts" style="display:block;margin:0 auto" />

<p>A small wrapper makes the boundary explicit and idempotent:</p>
<pre><code class="language-ts">// run-step.ts
import { randomUUID } from "node:crypto";
import type { PersistenceLayers, RunState } from "./persistence";

export async function runStep(
  layers: PersistenceLayers,
  state: RunState,
  call: (idempotencyKey: string) =&gt; Promise&lt;void&gt;,
  toolName: string,
) {
  // 1. Record intent before the side effect, with a stable key.
  const pending = state.pendingToolCall ?? { id: randomUUID(), name: toolName, args: null };
  await layers.state.save({ ...state, pendingToolCall: pending });

  // 2. The tool uses the key, so a retried call is a no op on the provider side.
  await call(pending.id);

  // 3. Effect committed: advance and clear the pending call in one save.
  const next: RunState = { ...state, step: state.step + 1, pendingToolCall: undefined };
  await layers.state.save(next);
  return next;
}
</code></pre>
<p>If the process dies between steps 1 and 3, the resumed run finds <code>pendingToolCall</code> with the same id and replays it with the same idempotency key. Payments, emails and tickets stay single.</p>
<p>Three boundaries I always add:</p>
<ul>
<li>After every external write (API call, email, database write).</li>
<li>Before any long wait, such as a human approval, so the waiting run holds no process.</li>
<li>After every file the agent finalizes, with its new hash recorded in <code>artifacts</code>.</li>
</ul>
<h2>Mount durable files separately</h2>
<p>Files are the layer people most often stuff into the wrong place. Logs, generated code, downloaded datasets and screenshots belong on a volume that outlives the runtime, which is exactly what a product like Vercel Drives is for. State keeps a pointer and a hash, memory keeps a sentence about it ("I wrote the report to reports/q3.md"), and the bytes stay on the drive.</p>
<pre><code class="language-ts">// files.ts
import { createHash } from "node:crypto";
import { readFile, writeFile, mkdir } from "node:fs/promises";
import { dirname, join } from "node:path";
import type { ArtifactRef, ThreadId } from "./persistence";

const WORKSPACE = process.env.AGENT_WORKSPACE ?? "/mnt/agent-drive";

export const filesRoot = (t: ThreadId) =&gt; join(WORKSPACE, "threads", t);

export async function writeArtifact(t: ThreadId, rel: string, body: string): Promise&lt;ArtifactRef&gt; {
  const full = join(filesRoot(t), rel);
  await mkdir(dirname(full), { recursive: true });
  await writeFile(full, body);
  return { path: rel, sha256: createHash("sha256").update(body).digest("hex") };
}

export async function verifyArtifact(t: ThreadId, ref: ArtifactRef): Promise&lt;boolean&gt; {
  const body = await readFile(join(filesRoot(t), ref.path));
  return createHash("sha256").update(body).digest("hex") === ref.sha256;
}
</code></pre>
<p>Two habits keep this layer honest. Scope every thread to its own directory, so two runs never write the same path. And verify hashes on resume: if a file on the drive no longer matches what the state recorded, stop and say so instead of building on top of it.</p>
<p>When several agents share one workspace, the same rules hold per agent, with one owner per directory. That is the core of the handoff patterns in this <a href="https://mudassirkhan.me/blog/multi-agent-system-architecture">production guide to multi agent system architecture</a>.</p>
<h2>Test resume and fork behavior</h2>
<p>You do not know your persistence works until you kill a run on purpose. A resume test and a fork test cover most of what breaks in production.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/90e11772-5860-43fc-ac96-16714265157e.gif" alt="Failure recovery sequence for an agent: Runtime crashes, Load checkpoint by thread id, Reattach drive and verify hashes, Replay pending call with the same key, Resume at the next step" style="display:block;margin:0 auto" />

<pre><code class="language-ts">// resume.test.ts
import { describe, it, expect } from "vitest";
import { makeTestLayers, runAgent, CrashAfter } from "./harness";

describe("agent persistence", () =&gt; {
  it("resumes after a crash without repeating the side effect", async () =&gt; {
    const layers = makeTestLayers();
    const sent: string[] = [];
    const sendEmail = async (key: string) =&gt; { if (!sent.includes(key)) sent.push(key); };

    await expect(runAgent(layers, "thread-a", { sendEmail, crash: CrashAfter.toolCall })).rejects.toThrow();
    await runAgent(layers, "thread-a", { sendEmail });           // fresh process, same thread id

    expect(sent).toHaveLength(1);
    expect((await layers.state.load("thread-a"))?.plan).toEqual([]);
  });

  it("forks state and files without touching the parent", async () =&gt; {
    const layers = makeTestLayers();
    await runAgent(layers, "thread-a", { stopAtStep: 2 });
    await layers.fork("thread-a", "thread-b");                  // copies state, copies files dir

    await runAgent(layers, "thread-b", { overridePlan: ["draft-alt"] });
    const parent = await layers.state.load("thread-a");
    expect(parent?.step).toBe(2);
  });
});
</code></pre>
<p>The fork test catches the most common bug I see: a forked thread that still points at the parent's files directory. Both branches then write the same report and whichever finishes last wins.</p>
<h2>Agent persistent state files memory checklist for production</h2>
<p>Before you call this production ready, every line below should be true:</p>
<table>
<thead>
<tr>
<th>Check</th>
<th>Layer</th>
<th>Fails when</th>
</tr>
</thead>
<tbody><tr>
<td>Every record carries a thread id</td>
<td>All three</td>
<td>Two runs read each other's data</td>
</tr>
<tr>
<td>Checkpoints sit after committed effects</td>
<td>State</td>
<td>A resume repeats a payment or an email</td>
</tr>
<tr>
<td>Pending calls carry an idempotency key</td>
<td>State</td>
<td>A replay creates a duplicate on the provider side</td>
</tr>
<tr>
<td>State stores file paths and hashes, not bytes</td>
<td>State and Files</td>
<td>Checkpoints grow and forks copy data</td>
</tr>
<tr>
<td>Files live on a volume that outlives the runtime</td>
<td>Files</td>
<td>A crash deletes the agent's work</td>
</tr>
<tr>
<td>In process memory is used only for tests</td>
<td>Memory</td>
<td>A deploy wipes every conversation</td>
</tr>
<tr>
<td>A crash test and a fork test run in CI</td>
<td>All three</td>
<td>The first real crash is your test</td>
</tr>
</tbody></table>
<h2>My take</h2>
<p>My opinion, after seeing a few agent codebases: most persistence bugs are not storage bugs. They are ownership bugs. Someone put the plan in the chat history because it was convenient, or wrote a file and kept its contents in the checkpoint "just for now". Drives going GA does not fix that. It just makes the files layer cheap enough that there is no excuse left. Draw the three boxes first, then pick the products.</p>
<h2>FAQ</h2>
<p><strong>What changed in agent persistent state files memory?</strong> Persistent file workspaces became a product (Vercel Drives is GA, 1 TiB default and up to 16 TiB, surviving individual Sandbox runtimes), memory got explicit lifecycles in SDKs like OpenAI Agents sessions, and durable execution in LangGraph resumes state by thread id through a checkpointer. Memory, state and files now ship as separate pieces.</p>
<p><strong>How should teams adopt agent persistent state files memory?</strong> Start by typing the three layers and giving every record a thread id. Then add checkpoints at side effect boundaries with idempotency keys, move every artifact onto a mounted volume that state references by path and hash, and add a crash test and a fork test to CI before the first production run.</p>
<p><strong>Should conversation memory and workflow state share one store?</strong> They can share a database, but not a record. Memory is what was said; state is where the run is. Keep them as separate tables or collections with separate retention, because you will want to summarize memory long before you are allowed to drop state.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/bb88adab-fef3-40d0-8913-2e4fefb1864c.jpg" alt="Agent persistence checklist: thread id on every record, checkpoint after committed effects, idempotency key on pending calls, paths and hashes instead of bytes, files on a durable volume, crash and fork tests in CI" style="display:block;margin:0 auto" />

<p><strong>Related reading:</strong> <a href="https://dev.to/mudassirworks/ai-agent-memory-management-beyond-the-context-window-5c65">Why your AI agent forgets: context engineering patterns that hold up</a> and <a href="https://medium.com/@mudassir00seven/why-40-of-ai-agent-projects-get-killed-and-the-ones-that-survive-e88ea081da1e">Why 40% of AI agent projects get killed, and the ones that survive</a>.</p>
<p>Still deciding which agent framework should own your checkpoints and sessions? Run your requirements through the <a href="https://mudassirkhan.me/tools/ai-agent-framework-chooser">AI agent framework chooser</a> before you commit to one.</p>
]]></content:encoded></item><item><title><![CDATA[LLM Context Window Management in Production: A Governance Checklist]]></title><description><![CDATA[Your model advertises a 200K token window. Your agent starts producing worse answers somewhere around 90K, and nobody notices for three weeks, because…]]></description><link>https://mudassirworks.hashnode.dev/llm-context-window-management-in-production-a-governance-checklist</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/llm-context-window-management-in-production-a-governance-checklist</guid><category><![CDATA[AI]]></category><category><![CDATA[webdev]]></category><category><![CDATA[llm]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[MachineLearning]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Wed, 09 Sep 2026 22:47:41 GMT</pubDate><content:encoded><![CDATA[<p>Your model advertises a 200K token window. Your agent starts producing worse answers somewhere around 90K, and nobody notices for three weeks, because nothing throws. That gap between advertised capacity and usable capacity is the entire problem, and LLM context window management in production is the discipline that closes it.</p>
<p>This article covers what context rot is, where degradation actually begins, what an ungoverned window costs you in tokens and latency, and a governance model you can implement today. By the end you will have a budget calculation, a compaction trigger, and a telemetry schema you can drop into an existing agent loop.</p>
<h2>Context rot: the failure mode nobody monitors</h2>
<p>Context rot is the progressive loss of answer quality as a session grows, while the context stays comfortably inside the model's advertised limit. Nothing truncates. Nothing errors. Every token you sent is still sitting in the payload. The model simply attends to it worse.</p>
<p>A study of 18 frontier models found that all of them degraded at every increment of context growth, with accuracy drops above 30 percent for information buried in the middle of long sessions. Not most of them. All 18, without exception. If you are running an agent on a frontier model, you are running it on a model that has this property.</p>
<p>For a coding agent the symptom is specific and expensive. The agent forgets a constraint you gave it 40 turns ago, rewrites a function it already fixed, or reintroduces a bug it removed two files back. You read the diff, decide the model is having an off day, and run the prompt again. The actual cause is that your constraint now sits in the low attention middle of a 90K token conversation.</p>
<p>Two vocabulary items separate teams that fix this from teams that keep rerolling prompts:</p>
<ul>
<li><p>Nominal window: the number printed on the model card.</p>
</li>
<li><p>Effective window: the region where retrieval accuracy actually holds. Always smaller.</p>
</li>
</ul>
<p>Your job is to keep every session inside the effective window. That is context governance, and it is a system property, not a prompting trick.</p>
<h2>It starts at 50 percent capacity, not 100 percent</h2>
<p>Significant context degradation begins at roughly 50 percent of a model's advertised context window capacity, not at the ceiling. That single number should change how you build.</p>
<p>If you treat the nominal window as your budget, you are already deep into degraded territory long before any alarm fires. Treat half of it as your working ceiling instead, and give yourself a second threshold that forces action:</p>
<pre><code class="language-ts">// context-budget.ts
export interface ContextBudget {
  nominal: number; // advertised window from the model card
  soft: number;    // 50% of nominal: degradation onset
  hard: number;    // 70% of nominal: force a compaction now
}

export function budgetFor(nominal: number): ContextBudget {
  return {
    nominal,
    soft: Math.floor(nominal * 0.5),
    hard: Math.floor(nominal * 0.7),
  };
}

export type BudgetState = "healthy" | "degrading" | "critical";

export function classify(used: number, b: ContextBudget): BudgetState {
  if (used &gt;= b.hard) return "critical";
  if (used &gt;= b.soft) return "degrading";
  return "healthy";
}
</code></pre>
<p>Crossing the soft threshold is not an error condition. It is a signal that answer quality has quietly become a function of how well you curated the middle of that window.</p>
<h2>Lost in the middle: position bias inside a long session</h2>
<p>The 30 percent accuracy drop is not spread evenly across the payload. It concentrates on information buried in the middle. Content near the start and near the end survives. Content in the belly of a long transcript is the content the model treats as optional.</p>
<p>This is the lost in the middle problem, and in production it has one practical consequence: transcript position is not a stable place to store anything that must hold for the whole session. A constraint you stated at turn 12 is in a different relative position at turn 80, and its relative position is exactly what determines whether the model still honours it.</p>
<p>So stop storing durable facts in the transcript. Pin them, and rewrite the pinned block on every turn:</p>
<pre><code class="language-ts">// build-messages.ts
import type { Message } from "./types";

export function buildMessages(opts: {
  contract: string;       // rewritten every turn, never buried
  retrieved: string[];    // top k documents for THIS turn only
  recentTurns: Message[]; // sliding window of dialogue
  task: string;
}): Message[] {
  return [
    { role: "system", content: opts.contract },
    ...opts.recentTurns,
    {
      role: "user",
      content: `${opts.retrieved.join("\n\n")}\n\n${opts.task}`,
    },
  ];
}
</code></pre>
<p>Two things are doing the work here. The contract lives at a fixed high attention position and is regenerated each turn from structured state, so it never drifts into the middle. The retrieved documents are scoped to the current turn and do not accumulate. That second decision alone removes most of the growth that produces llm context degradation in a long session.</p>
<h2>The hidden cost: 100K tokens at 50x the price of 2K</h2>
<p>Context window cost optimization usually gets filed under nice to have. The arithmetic disagrees. A 100K token conversation costs 50 times more than a 2K token conversation on the same model, because you resend the entire accumulated context on every single turn. One study recorded a 7x increase in latency at 15,000 words of context.</p>
<p>Stack those two facts. The ungoverned session is the slow one and the expensive one, and it is also the one giving worse answers. There is no tradeoff to balance here, which is unusual and worth exploiting. Governance wins on cost, on latency, and on accuracy simultaneously.</p>
<p>Now multiply by traffic. An agent serving 10,000 sessions a day at 60K tokens per turn instead of 12K is not marginally more expensive. It is 5 times more expensive on your single largest line item, every day, while being slower and less accurate than the cheaper version.</p>
<h2>Silent failure versus loud failure: why context rot is dangerous</h2>
<p>Overflow is a loud failure. You get an exception, a truncated payload, a 400 from the provider, an alert in your channel. Loud failures get fixed, because they show up on a dashboard within minutes of shipping.</p>
<p>The dominant production failure mode for agents is not overflow. It is silent quality degradation well before the limit is reached. For coding agents specifically, context rot is the primary failure mode. Nothing pages anyone. Your p50 latency chart looks normal. Your error rate is flat at zero. The only real signal is that users quietly stop trusting the agent for anything long, and you learn about it in a retro instead of an alert.</p>
<p>That is why context governance has to be instrumented rather than assumed. Log this on every turn:</p>
<pre><code class="language-ts">// telemetry.ts
export interface TurnContextEvent {
  sessionId: string;
  turnIndex: number;
  tokensContract: number;   // pinned block
  tokensRetrieved: number;  // this turn's documents
  tokensDialogue: number;   // sliding window
  tokensTotal: number;
  budgetState: BudgetState;
  compacted: boolean;
  tokensReclaimed: number;
}

export function emitTurnContext(e: TurnContextEvent): void {
  logger.info("agent.context", { ...e, ratio: e.tokensTotal / e.nominal });
}
</code></pre>
<p>Then chart your quality metrics against <code>budgetState</code> rather than against wall clock time. If the thumbs down rate is 3 percent in the healthy band and 11 percent in the degrading band, you have just measured your own context rot curve, and you know precisely where to set your trigger instead of guessing.</p>
<h2>Context engineering: the discipline that replaced prompt wrangling</h2>
<p>Context engineering, meaning the practice of governing what enters the context window rather than only how large that window is, has become the core discipline of production AI engineering. The research converges on one finding worth internalising: fewer, higher signal objects outperform larger ungoverned windows.</p>
<p>Signal density is the metric, not token count. Ten precisely retrieved paragraphs beat 200 loosely related ones, and they beat them on accuracy, not merely on cost. Every token you add that is not load bearing dilutes the attention available to the tokens that are.</p>
<p>Which reframes what a bigger model card number means. A larger nominal window is not permission to send more. It is headroom that lets your governed window sit further from the edge.</p>
<h2>A governance model: when to summarize, when to retrieve, when to reset</h2>
<p>Three actions, three triggers. Wire them explicitly rather than hoping the window absorbs everything.</p>
<p><strong>Retrieve</strong> when the information is external to the dialogue. Scope retrieval to the current turn, never let it accumulate, and prefer a small top k with a reranker over a large top k without one. Retrieval is the cheap path because retrieved context leaves the window as soon as the turn ends.</p>
<p><strong>Summarize</strong> when <code>budgetState</code> reaches degrading. Compact the oldest dialogue into a structured summary, keep the most recent turns verbatim in a sliding window, and preserve decisions and constraints losslessly by promoting them into the pinned contract instead of the summary prose.</p>
<pre><code class="language-ts">// compact.ts
const KEEP_VERBATIM = 8; // most recent turns stay untouched

export async function compactIfNeeded(
  session: Session,
  budget: ContextBudget,
): Promise&lt;Session&gt; {
  if (classify(session.tokensUsed, budget) === "healthy") return session;

  const older = session.turns.slice(0, -KEEP_VERBATIM);
  const recent = session.turns.slice(-KEEP_VERBATIM);
  if (older.length === 0) return session;

  const summary = await summarizeTurns(older); // returns { prose, decisions[] }

  return {
    ...session,
    contract: mergeContract(session.contract, summary.decisions),
    turns: [asSystemNote(summary.prose), ...recent],
    compactions: session.compactions + 1,
  };
}
</code></pre>
<p><strong>Reset</strong> when the task changes. A session that has moved from debugging an auth bug to writing release notes is carrying 40K tokens of pure noise. Start a fresh window seeded only with the pinned contract. Resets are the most underused of the three and often the highest leverage.</p>
<h2>The checklist</h2>
<p>Run this against any agent you have in production:</p>
<ol>
<li><p>Do you know your nominal window and have you set a soft ceiling at 50 percent of it?</p>
</li>
<li><p>Is <code>budgetState</code> computed and logged on every turn?</p>
</li>
<li><p>Are durable constraints stored in a rewritten pinned block rather than in the transcript?</p>
</li>
<li><p>Is retrieved context scoped to a single turn instead of accumulating?</p>
</li>
<li><p>Does compaction fire automatically at the degrading threshold?</p>
</li>
<li><p>Are decisions promoted into the contract losslessly when you compact?</p>
</li>
<li><p>Do you reset on task change instead of continuing forever?</p>
</li>
<li><p>Are quality metrics charted against budget state so you can see your own rot curve?</p>
</li>
</ol>
<p>Anything you answer no to is an ungoverned surface, and ungoverned surfaces fail silently.</p>
<h2>FAQ</h2>
<h3>What is context rot in LLMs?</h3>
<p>Context rot is the measurable decline in an LLM's answer quality as the amount of context in a session grows, even while the total stays inside the advertised window. A study of 18 frontier models found every model degraded at every increment of context growth, with accuracy drops above 30 percent for information positioned in the middle of long sessions. It differs from context overflow because nothing errors and nothing truncates.</p>
<h3>How do you manage context in a long running AI session?</h3>
<p>Set a soft budget at 50 percent of the nominal window and classify every turn against it. Keep durable constraints in a pinned block that you rewrite each turn instead of leaving them in the transcript. Scope retrieval to the current turn so it never accumulates. Compact older dialogue into a structured summary once you cross the soft threshold, keeping recent turns verbatim in a sliding window. Reset the session outright when the task changes.</p>
<h3>When does LLM context degradation start?</h3>
<p>Significant degradation begins at roughly 50 percent of a model's advertised context window capacity, not at the limit. Treat that halfway point as the boundary of your effective window and instrument around it, because the failure produces no exception to catch.</p>
<h2>Where to start</h2>
<p>Pick your busiest agent and add one thing this week: the <code>budgetState</code> field on your existing turn log. Do not change behaviour yet. After a few thousand sessions, chart your quality metric against that field and you will see the exact token count where your own product starts rotting. Everything else in this article is easier to justify once that chart exists.</p>
]]></content:encoded></item><item><title><![CDATA[GraphRAG vs RAG: The Break Even Analysis Before You Switch]]></title><description><![CDATA[The GraphRAG vs RAG question usually gets asked backwards. Teams ask whether a knowledge graph produces better answers, and the honest answer is that it…]]></description><link>https://mudassirworks.hashnode.dev/graphrag-vs-rag-the-break-even-analysis-before-you-switch</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/graphrag-vs-rag-the-break-even-analysis-before-you-switch</guid><category><![CDATA[AI]]></category><category><![CDATA[MachineLearning]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Python]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Mon, 07 Sep 2026 12:49:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/69d75e21-78b5-425f-b6bc-5de014fe29fc.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The GraphRAG vs RAG question usually gets asked backwards. Teams ask whether a knowledge graph produces better answers, and the honest answer is that it depends entirely on the shape of the query you are serving. This article gives you the benchmark split by query type, the real GraphRAG indexing cost picture, and a decision rule you can apply to your own traffic. By the end you will be able to tell whether your workload justifies building a graph, or whether you are about to pay for structure your users never actually query.</p>
<p>Quick definitions, because the two systems differ before retrieval even starts. Plain vector RAG embeds your documents, retrieves the chunks nearest to the question, and hands them to the model. GraphRAG first runs entity extraction across the whole corpus, builds a knowledge graph of entities and the relationships between them, precomputes community summarization over clusters in that graph, and then retrieves by traversing structure instead of by vector distance alone.</p>
<p>All of the extra cost lives in that indexing pipeline. So does all of the advantage, for a narrow band of queries.</p>
<h2>The benchmark: plain RAG vs GraphRAG by query type</h2>
<p>The single most useful thing you can do before switching is stop evaluating retrieval quality as one number. Split it by query type and the picture separates cleanly.</p>
<p>On simple single hop factual retrieval, the two approaches are effectively tied. GraphRAG scores 60.9 against plain vector RAG at 60.1. That gap is noise. If you paid for a graph index to serve those queries, you paid for nothing.</p>
<p>The separation shows up elsewhere. On multi hop reasoning, GraphRAG gains roughly 10 points, 53.4 against 42.9. On contextual summarization, it gains roughly 13 points, 64.4 against 51.3.</p>
<table>
<thead>
<tr>
<th>Query type</th>
<th>GraphRAG</th>
<th>Plain vector RAG</th>
<th>Gap</th>
</tr>
</thead>
<tbody><tr>
<td>Single hop factual</td>
<td>60.9</td>
<td>60.1</td>
<td>tie</td>
</tr>
<tr>
<td>Multi hop reasoning</td>
<td>53.4</td>
<td>42.9</td>
<td>about 10 points</td>
</tr>
<tr>
<td>Contextual summarization</td>
<td>64.4</td>
<td>51.3</td>
<td>about 13 points</td>
</tr>
</tbody></table>
<p>Two things are worth pulling out of that table. First, the tie on single hop retrieval is not a small win for the graph, it is a genuine tie, and single hop factual lookup is the majority of traffic in most production question answering systems. Second, even where GraphRAG wins, absolute scores on multi hop reasoning stay low for both. A graph makes hard queries less bad. It does not make them solved.</p>
<p>So before you cost anything out, go and sample a few hundred real queries from your logs and label them. If fewer than one in five needs to cross a relationship between documents, the benchmark is already telling you the answer.</p>
<h2>When GraphRAG wins: multi hop and global queries</h2>
<p>GraphRAG multi hop reasoning wins for a structural reason, not a magical one. A multi hop question requires you to find entity A, follow a relationship to entity B, and only then retrieve the fact you actually wanted. Vector similarity has no mechanism for that second step. The chunk containing B might sit nowhere near the question in embedding space, so it never enters the context window and the model confabulates the join.</p>
<p>The graph makes that traversal explicit. Entity extraction has already recorded that A relates to B, so the retriever walks the edge rather than hoping the embedding lands.</p>
<p>The second win is on global queries. There is a real difference between a local query, meaning "what did this specific contract say about termination", and a global query, meaning "what themes run across all of these contracts". Vector retrieval answers the first well and the second badly, because top k chunk retrieval can only ever show the model a sample. Community summarization gives GraphRAG a precomputed view of the whole corpus, which is exactly what a global query needs.</p>
<p>The numbers back that up. On global dataset wide queries, GraphRAG won 72 to 83 percent of comprehensiveness comparisons against plain vector RAG, and 62 to 82 percent of diversity comparisons.</p>
<p>If your product does corpus level sensemaking, competitive analysis across a document set, thematic review, or anything a human would describe as "read all of this and tell me what is going on", that is the workload the graph was built for.</p>
<h2>When plain RAG wins: single hop factual retrieval</h2>
<p>Plain RAG wins the common case, and it wins it on economics rather than on quality, because quality is a tie.</p>
<p>Single hop factual retrieval means the answer lives in one place. A policy clause, a specification value, an error code, a price. You embed, you retrieve, you answer. The graph adds an indexing pipeline, an entity resolution problem, a schema to maintain, and a second failure mode where a wrong edge routes the retriever confidently into the wrong neighbourhood.</p>
<p>There is also a cheaper upgrade path that teams skip past on the way to a graph. If your vector retrieval is missing things, hybrid retrieval combining lexical and dense search, merged with reciprocal rank fusion, usually recovers a meaningful slice of the misses for a fraction of the operational weight. It is not as interesting as a knowledge graph. It ships in an afternoon.</p>
<p>Knowledge graph RAG production systems also carry costs that no benchmark measures: the graph goes stale when documents change, entity resolution drifts as new sources arrive, and someone has to own the schema. Budget for that before you commit.</p>
<h2>The cost cliff: $33,000 to $33 in eighteen months</h2>
<p>The classic objection to GraphRAG was price, and for a while it was a fair objection. Running entity extraction and summarization through a language model across an entire large corpus meant one model call per chunk before you served a single user query.</p>
<p>That number has collapsed. Indexing a large corpus went from roughly $33,000 to approximately $33 over eighteen months, a reduction of about 99.9 percent. The driver was replacing language model based entity summarization with NLP driven concept extraction.</p>
<p>If your internal position on GraphRAG was formed while the indexing bill looked like a headcount, that position is stale. The GraphRAG indexing cost argument has essentially stopped being the deciding factor. What remains is whether your query mix benefits at all, which is a product question rather than a budget one.</p>
<h2>LazyGraphRAG: 0.1% indexing cost, comparable quality</h2>
<p>LazyGraphRAG, from Microsoft Research, is the specific piece of work that moved the cost floor. The LazyGraphRAG cost reduction comes from one design decision: defer all language model use to query time instead of spending it during indexing.</p>
<p>Full GraphRAG pays up front. It walks the corpus, extracts entities, summarizes communities, and stores the result, whether or not anyone ever asks a question that needs it. LazyGraphRAG builds a much cheaper structural index and only spends model calls once a real query arrives and it knows which part of the graph matters.</p>
<p>The reported result is that indexing costs 0.1 percent of full GraphRAG. Global search queries cost about 4 percent of full GraphRAG at comparable answer quality, which works out to more than 700 times cheaper per query.</p>
<p>For most teams this changes the sequencing. You no longer have to be certain that graph retrieval will pay off before you build the index, because being wrong now costs very little. That is a different risk profile from the one that made this a committee decision.</p>
<h2>The break even rule: which workload justifies the graph?</h2>
<p>Here is the practical rule for when to use GraphRAG, stated so you can apply it to a query log rather than to a vibe.</p>
<p>Use plain vector RAG when queries are single hop and document centric. The answer lives in one place, and you only need to find that place.</p>
<p>Switch to GraphRAG or LazyGraphRAG when queries require multi hop relationship traversal, reasoning across documents, or global sensemaking over the corpus as a whole.</p>
<p>You can encode that as routing rather than as an either or platform choice, which is what I would do in most systems:</p>
<pre><code class="language-python">GRAPH_QUERY_TYPES = {"multi_hop", "cross_document", "global_sensemaking"}

def route(query_type: str) -&gt; str:
    """Pick a retriever per query instead of committing the whole system."""
    if query_type in GRAPH_QUERY_TYPES:
        return "lazy_graph_rag"
    return "vector_rag"

# Classify once, cheaply, then route. Most production traffic
# lands on vector_rag, which is the point.
</code></pre>
<p>Routing beats migrating. You keep the cheap path for the traffic that is tied on quality anyway, and you pay for traversal only on the queries that actually need it. It also gives you a real measurement: log which branch fired, and after a week you will know what share of your traffic ever justified the graph.</p>
<h2>FAQ</h2>
<h3>When is GraphRAG better than plain RAG?</h3>
<p>On multi hop reasoning, where it gains about 10 points, and on contextual summarization, where it gains about 13 points. It also wins on global dataset wide queries, taking 72 to 83 percent of comprehensiveness comparisons and 62 to 82 percent of diversity comparisons. On single hop factual retrieval it is a tie at 60.9 against 60.1, so there is no quality reason to switch for that traffic.</p>
<h3>How much does GraphRAG indexing cost now?</h3>
<p>Far less than it used to. Indexing a large corpus fell from roughly $33,000 to approximately $33 over eighteen months, driven by NLP driven concept extraction replacing language model based entity summarization. Cost is no longer the main reason to avoid a graph.</p>
<h3>What is LazyGraphRAG?</h3>
<p>A variant from Microsoft Research that defers all language model use to query time. It indexes at 0.1 percent of full GraphRAG cost and runs global search queries at about 4 percent of full GraphRAG cost with comparable answer quality, which is more than 700 times cheaper per query.</p>
<h3>Can I use GraphRAG without an expensive graph index?</h3>
<p>Yes. That is precisely what LazyGraphRAG is for. Because indexing costs 0.1 percent of the full pipeline, you can build the index to test whether your query mix benefits, rather than having to prove the benefit before you are allowed to build it.</p>
]]></content:encoded></item><item><title><![CDATA[AI Agent Tool Selection: Why Agents Break When You Give Them Every Tool]]></title><description><![CDATA[You registered every tool the team asked for, the agent got worse, and nothing in the logs explains it. AI agent tool selection is the part of agent…]]></description><link>https://mudassirworks.hashnode.dev/ai-agent-tool-selection-why-agents-break-when-you-give-them-every-tool</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/ai-agent-tool-selection-why-agents-break-when-you-give-them-every-tool</guid><category><![CDATA[AI]]></category><category><![CDATA[agents]]></category><category><![CDATA[llm]]></category><category><![CDATA[webdev]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Wed, 02 Sep 2026 19:43:41 GMT</pubDate><content:encoded><![CDATA[<p>You registered every tool the team asked for, the agent got worse, and nothing in the logs explains it. AI agent tool selection is the part of agent engineering that fails quietly, because every tool you register looks free at design time and only charges you at inference time. The bill arrives as wrong calls, skipped calls, and invented arguments.</p>
<p>This article covers why a larger tool registry degrades an agent, the specific failure modes it produces, and two patterns you can apply to a system you already run: lazy tool loading and a tool router. By the end you will be able to audit your own registry, cut it down without losing capability, and expose only the tools a given task can actually use.</p>
<p><strong>AI agent tool selection</strong> is the process by which a language model picks which registered tool to call, and with what arguments, based only on the tool names, descriptions, and parameter schemas placed in its context. The model has no other view of your system. If the description is wrong, the model is wrong.</p>
<h2>The counterintuitive result: more tools, worse performance</h2>
<p>The first thing to internalise about llm too many tools performance is that capability and accuracy pull in opposite directions. Adding a tool always increases what the agent could theoretically do. It also increases the number of near neighbours the model has to discriminate between on every turn, and discrimination is the thing that degrades.</p>
<p>An agent with a small, sharply named registry answers a question by picking the one obvious candidate. The same agent with a sprawling registry has to rank a dozen plausible candidates whose descriptions overlap, then commit to one, then produce arguments for it. Tool selection accuracy is measured on that commit step, and it is the step that quietly gets harder every time someone merges a new integration.</p>
<p>The failure is rarely dramatic. The agent does not crash. It calls <code>search_documents</code> when it should have called <code>search_tickets</code>, gets a plausible looking empty result, and reports back that it found nothing. That is the shape of the problem in production: silent wrong answers, not exceptions.</p>
<h2>Why it happens: schema injection and attention dilution</h2>
<p>Two mechanisms drive it, and they compound.</p>
<p>The first is <strong>tool schema injection</strong>. Every registered tool has to be described to the model in the prompt before the model can call it. Name, description, parameter schema, and parameter descriptions all get serialised into context on every single request. This is the mcp tool schema overhead that surprises teams when they connect several MCP servers at once: you did not add five tools, you added five tools plus their full JSON schemas, on every turn, forever.</p>
<p>That consumes context budget you were saving for the actual task. Retrieved documents, conversation state, and the user's real question now compete with a wall of boilerplate the model mostly ignores.</p>
<p>The second is <strong>attention dilution</strong>. The relevant tool description is still in the window, but it now sits among many structurally identical blocks of text. Everything looks like a tool. The signal the model needs is present and no longer distinctive, which is a different problem from missing information and is much harder to spot by reading the prompt.</p>
<p>A useful habit: dump the exact serialised prompt your framework sends, including all injected schemas, and count what fraction of it is tool boilerplate. Most teams have never looked. The number is usually uncomfortable.</p>
<pre><code class="language-python">def audit_tool_overhead(tools, tokenizer):
    """Measure what share of context the tool registry consumes."""
    total = 0
    rows = []
    for t in tools:
        blob = t.name + t.description + json.dumps(t.parameters)
        n = len(tokenizer.encode(blob))
        rows.append((t.name, n))
        total += n
    rows.sort(key=lambda r: -r[1])
    return total, rows[:10]   # worst offenders first
</code></pre>
<p>Run that once. The tools at the top of that list are usually ones nobody has called in weeks.</p>
<h2>The semantic mismatch problem: your tool names mean something different to the LLM</h2>
<p>Here is the part that catches experienced API developers.</p>
<p>Language models are literal users of tool interfaces. The tool name, the description, the parameter schema, and the parameter descriptions form the complete surface the model can reason from. There is no source code, no internal wiki, no colleague to ask. Vague descriptions cause the model to hallucinate calls or to ignore the tool entirely.</p>
<p>This is <strong>semantic mismatch</strong>: the name means one thing inside your team and something broader to the model. A tool called <code>get_user</code> reads unambiguously to the engineer who wrote it, because they know it hits the billing service. To the model it is a general lookup that plausibly answers any question containing the word user. It will be called constantly and wrongly.</p>
<p>Namespace design is the practical fix. An ai agent tool namespace collision happens when two registered tools occupy overlapping semantic space, and it becomes near certain once you connect multiple servers that each export their own generic verbs. Two tools named <code>search</code> cannot both be correct, and the model has no principled way to choose.</p>
<p>Prefix by domain, name by outcome, and make descriptions state the boundary explicitly:</p>
<pre><code class="language-json">{
  "name": "billing_get_customer_record",
  "description": "Fetch a customer's billing record by internal billing ID. Use ONLY for invoices, payment methods, and subscription state. Does NOT return login, profile, or support-ticket data.",
  "parameters": {
    "type": "object",
    "properties": {
      "billing_id": {
        "type": "string",
        "description": "Internal billing ID, format BIL-123456. Not the user's email or account ID."
      }
    },
    "required": ["billing_id"]
  }
}
</code></pre>
<p>The negative clause matters as much as the positive one. Telling the model what a tool does not cover is often what stops the wrong call.</p>
<h2>The 5 most common tool call failure modes (all preventable)</h2>
<p>The literature converges on 5 recurring failure modes, and all of them trace back to schema and description quality rather than model capability.</p>
<p><strong>1. The hallucinated call.</strong> A vague or generic tool name invites the model to invent a call that fits the shape of the name rather than its real behaviour.</p>
<p><strong>2. The ignored tool.</strong> The opposite failure. The description is so thin that the model never recognises the tool as relevant, and quietly answers from memory instead.</p>
<p><strong>3. Invented parameter values.</strong> Ambiguous parameter descriptions push the model to fabricate a value in the right format.</p>
<p><strong>4. The stray field that stalls the chain.</strong> Tool design for language models is structurally different from traditional API design. Human facing APIs are forgiving, tolerating extra or missing fields. Agent facing APIs have to be strict: validated against a schema, flat and minimal JSON, with machine readable error codes.</p>
<p><strong>5. The unrecoverable error.</strong> The tool fails and returns a human prose error message. The model cannot parse intent from it, so it either retries identically or gives up.</p>
<h2>Lazy tool loading: only expose what the current task needs</h2>
<p>The structural fix for context bloat is dynamic tool loading llm systems can drive at runtime. Instead of registering everything at startup, you register a small always available core, then load domain tools on demand.</p>
<pre><code class="language-python">CORE_TOOLS = ["list_capabilities", "load_toolset", "respond"]

TOOLSETS = {
    "billing":  ["billing_get_customer_record", "billing_list_invoices"],
    "support":  ["support_search_tickets", "support_create_ticket"],
    "analytics": ["analytics_run_query", "analytics_list_metrics"],
}

def build_tool_context(active_toolsets, registry):
    exposed = list(CORE_TOOLS)
    for name in active_toolsets:
        exposed.extend(TOOLSETS.get(name, []))
    return [registry[t].schema() for t in exposed]
</code></pre>
<h2>Building a tool router</h2>
<pre><code class="language-typescript">type ToolsetName = "billing" | "support" | "analytics";

const ROUTES: Array&lt;{ match: RegExp; toolset: ToolsetName }&gt; = [
  { match: /invoice|payment|refund|subscription/i, toolset: "billing" },
  { match: /ticket|complaint|escalat/i,            toolset: "support" },
  { match: /metric|report|trend|query/i,           toolset: "analytics" },
];

export function routeToolsets(task: string): ToolsetName[] {
  const hits = ROUTES.filter(r =&gt; r.match.test(task)).map(r =&gt; r.toolset);
  return hits.length ? [...new Set(hits)] : ["support"];
}
</code></pre>
<h2>FAQ</h2>
<h3>How many tools can an AI agent handle?</h3>
<p>There is no fixed ceiling. The practical limit is set by context budget and how distinguishable the tool descriptions are from each other.</p>
<h3>Why does giving an agent more tools make it worse?</h3>
<p>Two reasons compound. Every registered tool injects its full schema into context on every request, consuming budget the task needed. And every additional tool adds another candidate the model must discriminate against.</p>
<h3>What is lazy tool loading for LLM agents?</h3>
<p>Lazy tool loading means exposing only a small core set of tools at startup and injecting the full schemas for a domain's tools only once the task needs them.</p>
<h2>The shorter answer</h2>
<p>Treat your tool registry the way you treat a database query. Select what this task needs, not everything the schema offers. Name tools for outcomes, describe their boundaries explicitly including what they do not cover, return machine readable errors, and route each task to the smallest toolset that can finish it.</p>
<p>The agent was never confused by hard reasoning. It was confused by your interface.</p>
]]></content:encoded></item><item><title><![CDATA[RAG Retrieval Latency in Production: Where the Time Actually Goes]]></title><description><![CDATA[If you have shipped a retrieval augmented generation system and users keep telling you it feels slow, the most useful thing you can do is stop treating RAG…]]></description><link>https://mudassirworks.hashnode.dev/rag-retrieval-latency-in-production-where-the-time-actually-goes</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/rag-retrieval-latency-in-production-where-the-time-actually-goes</guid><category><![CDATA[RAG ]]></category><category><![CDATA[AI]]></category><category><![CDATA[VectorDatabase]]></category><category><![CDATA[Python]]></category><category><![CDATA[MachineLearning]]></category><category><![CDATA[vector database]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Tue, 01 Sep 2026 14:32:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/407bd956-2379-46e1-8f5e-823d7f0b5dd6.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you have shipped a retrieval augmented generation system and users keep telling you it feels slow, the most useful thing you can do is stop treating RAG retrieval latency as a single number. It is three numbers stacked on top of each other, and the one most teams spend their optimization budget on is usually not the one costing them the time.</p>
<p>By the end of this guide you will know how a production RAG request splits into time buckets, what drives each bucket, which five levers move the needle and in what order to pull them, how to route queries adaptively so cheap questions stop paying for expensive pipelines, and how to instrument the whole query pipeline so you are tuning against P95 latency instead of a feeling.</p>
<h2>The three time buckets in a RAG request</h2>
<p>A RAG request runs three stages back to back. The user's question gets embedded into a vector, that vector gets matched against an ANN index, and the retrieved chunks get stuffed into a prompt that a language model reads before it writes anything.</p>
<p>Production RAG systems average 1.2 to 2.5 seconds end to end, and the split is lopsided. Query embedding takes 50 to 100 milliseconds. Vector search takes 100 to 300 milliseconds. LLM generation takes 1 to 2 seconds.</p>
<table>
<thead>
<tr>
<th>Stage</th>
<th>Typical time</th>
<th>What it is</th>
</tr>
</thead>
<tbody><tr>
<td>Query embedding</td>
<td>50 to 100 ms</td>
<td>Turning the question into a vector</td>
</tr>
<tr>
<td>Vector search</td>
<td>100 to 300 ms</td>
<td>ANN lookup plus any reranking</td>
</tr>
<tr>
<td>LLM generation</td>
<td>1 to 2 seconds</td>
<td>Reading context, writing the answer</td>
</tr>
</tbody></table>
<p>Do the arithmetic before you plan any work. Retrieval, the part everyone calls "the RAG part", is somewhere around 150 to 400 milliseconds of a 1200 to 2500 millisecond request. That is roughly 12 to 20 percent of the wall clock. If you halve your vector search time you have bought the user about 100 milliseconds. If you cut a second off generation you have bought them ten times that.</p>
<p>This is not an argument for ignoring retrieval. It is an argument for measuring first. I have watched teams spend two sprints migrating vector databases because retrieval "felt slow", ship it, and discover the P95 barely moved because a 4000 token prompt was doing all the damage.</p>
<p>Instrument the buckets before you touch anything:</p>
<pre><code class="language-python">import time
from contextlib import contextmanager

TIMINGS = {}

@contextmanager
def bucket(name: str):
    t0 = time.perf_counter()
    try:
        yield
    finally:
        TIMINGS[name] = (time.perf_counter() - t0) * 1000

def answer(question: str):
    with bucket("embed"):
        qvec = embedder.encode(question)
    with bucket("search"):
        hits = index.search(qvec, top_k=20)
    with bucket("rerank"):
        hits = reranker.rank(question, hits)[:5]
    with bucket("generate"):
        out = llm.complete(build_prompt(question, hits))
    logger.info("rag_latency", extra={"ms": TIMINGS})
    return out
</code></pre>
<p>Log every bucket on every request, ship it to whatever you use for metrics, and read the histogram rather than the average. Averages hide the requests that make people close the tab.</p>
<h2>Query embedding, 50 to 100 milliseconds</h2>
<p>Embedding latency is the smallest bucket and the easiest to misdiagnose, because most of it is usually not compute. It is a network round trip to a hosted embedding endpoint.</p>
<p>Three things decide this number. Whether the model runs in your process or behind an API. Whether the embedding service sits in the same region as your application. Whether you are embedding one query or waiting on a batch.</p>
<p>A small embedding model running locally on CPU will produce a query vector in a few milliseconds. The same model behind a hosted API in another region will take 60 milliseconds, almost all of it transit and queueing. If your embedding call is consistently near the top of that 50 to 100 millisecond band, check the region before you check the model.</p>
<p>The other easy win is caching. Real user traffic is repetitive. Support questions, documentation lookups, and internal search all have a heavy head of near identical phrasings. Hash the normalized query text and keep the resulting vector in a fast store:</p>
<pre><code class="language-python">import hashlib

def embed_cached(text: str) -&gt; list[float]:
    key = "emb:" + hashlib.sha256(text.strip().lower().encode()).hexdigest()
    cached = redis.get(key)
    if cached:
        return msgpack.loads(cached)
    vec = embedder.encode(text)
    redis.setex(key, 86_400, msgpack.dumps(vec))
    return vec
</code></pre>
<p>That turns a repeat query's embedding cost into a sub millisecond lookup. It is a small bucket, but it is nearly free to fix.</p>
<h2>Vector search, 100 to 300 milliseconds, and what drives it</h2>
<p>This is where vector search latency optimization actually happens, and it is the bucket with the widest spread. The same corpus, the same hardware, and the same query can return in 15 milliseconds or 300 depending on how the index is built and where the vectors live.</p>
<p>Four variables dominate.</p>
<p><strong>Index type.</strong> Exact search compares the query against every vector. It is perfectly accurate and it scales linearly, which means it stops being viable somewhere in the low hundreds of thousands of vectors. Approximate nearest neighbour indexes trade a sliver of recall for an enormous speedup. HNSW and IVF are the two you will actually meet, and they achieve query latencies as low as 15 milliseconds at 1 million vectors while keeping accuracy high enough that nobody notices the difference in answer quality.</p>
<p><strong>Where the vectors live.</strong> Disk backed indexes pay a page fault tax on every hop through the graph. In memory vector architectures achieve single digit millisecond P95 latencies even at billion vector scale. If your index fits in RAM, put it in RAM. This is usually a larger effect than any parameter you can tune.</p>
<p><strong>How many results you ask for.</strong> Fetching the top 50 candidates costs meaningfully more than fetching the top 10, and if you are then reranking those 50 with a cross encoder you have quietly added a second model to the critical path. Reranking cost is real and it belongs in your latency budget, not in a footnote.</p>
<p><strong>Metadata filtering.</strong> Filtered ANN search is harder than it looks. Depending on the engine, a restrictive filter either prunes the graph efficiently or degrades into something close to a scan. Benchmark your filtered queries separately from your unfiltered ones. They are different workloads wearing the same API.</p>
<h3>HNSW ANN search speed and the knobs that matter</h3>
<p>HNSW builds a layered proximity graph and walks it from a sparse top layer down to a dense bottom one. Three parameters control the tradeoff.</p>
<p><code>M</code> sets how many neighbours each node keeps. Higher <code>M</code> gives better recall and a bigger index. <code>ef_construction</code> sets how hard the builder searches while inserting. It costs build time, not query time. <code>ef_search</code> sets how wide the graph walk is at query time, and it is the only one of the three you can change without a rebuild.</p>
<pre><code class="language-python"># ef_search is the query time recall/latency dial.
# Sweep it against YOUR corpus, not a benchmark dataset.
for ef in (16, 32, 64, 128, 256):
    index.set_ef(ef)
    lat, recall = evaluate(index, gold_queries)
    print(f"ef_search={ef:&gt;4}  p95={lat:6.1f}ms  recall@10={recall:.3f}")
</code></pre>
<p>Run that sweep on your own data and your own gold queries. Almost every team I have seen do this finds a knee where recall has flattened but latency is still climbing, and they had been sitting well past it on a default. IVF has the same shape of dial in <code>nprobe</code>, which controls how many clusters get scanned per query.</p>
<h2>LLM generation, 1 to 2 seconds, the dominant bucket</h2>
<p>Generation is where the seconds are, so this is where rag production performance is won or lost.</p>
<p>The single biggest perceived improvement is not making generation faster. It is streaming. Time to first token is what users experience as speed, and a streamed response that starts in 400 milliseconds feels faster than a buffered one that completes in 900. If you are not streaming, do that before you tune anything else in this article.</p>
<p>After that, the levers are prompt size and model size. Every retrieved chunk you add to the context has to be read before the first token comes out, and prefill time scales with input length. Sending 12 chunks because your retriever returned 12 is a habit, not a design. Most answers are fully supported by 3 to 5 well chosen chunks, and cutting from 12 to 4 removes thousands of tokens from prefill on every single request.</p>
<p>Model choice matters just as much. A smaller model that answers a routing question in 300 milliseconds is not competing with your flagship model on quality, because it is not being asked the same kind of question.</p>
<h2>The five latency levers in order</h2>
<p>Pull them in this sequence. The ordering is by effect per unit of engineering effort, not by how interesting the work is.</p>
<ol>
<li><p><strong>Stream the response.</strong> Cheapest change with the largest perceived effect. Optimizes time to first token, which is the number users actually feel.</p>
</li>
<li><p><strong>Add semantic caching.</strong> Cache answers keyed by embedding similarity, not exact string match, so paraphrases hit too. Semantic caching cuts LLM costs by up to 68.8% and removes the entire generation bucket for anything that hits.</p>
</li>
<li><p><strong>Shrink the context.</strong> Fewer, better chunks. Rerank to 3 to 5 and stop there. This attacks prefill, which is inside the dominant bucket.</p>
</li>
<li><p><strong>Tune the ANN index.</strong> Sweep <code>ef_search</code> or <code>nprobe</code> against your own gold set and pick the knee. Usually a free 30 to 60 percent off the search bucket.</p>
</li>
<li><p><strong>Move the index into memory.</strong> Biggest infrastructure lift, and the one that takes you toward single digit millisecond P95 search. Do it last, when you have proven the other four are exhausted.</p>
</li>
</ol>
<p>Semantic caching deserves a note on correctness. A similarity threshold that is too loose will serve the answer to a neighbouring question, which is worse than being slow. Start strict, log every hit with its similarity score, and loosen only with evidence:</p>
<pre><code class="language-python">SIM_THRESHOLD = 0.95   # start strict, loosen with logged evidence

def cached_answer(question: str, qvec):
    hit = cache_index.search(qvec, top_k=1)
    if hit and hit[0].score &gt;= SIM_THRESHOLD:
        metrics.incr("semcache.hit", tags={"score": round(hit[0].score, 2)})
        return hit[0].payload["answer"]
    return None
</code></pre>
<h2>Adaptive RAG: routing by query complexity</h2>
<p>The uncomfortable truth about a fixed pipeline is that it prices every query at the cost of the hardest one. A user asking "what is your refund window" runs the same embedding, the same ANN search, the same cross encoder rerank, and the same large model as someone asking a multi hop question that spans four documents.</p>
<p>Adaptive RAG query routing fixes that. A cheap classifier sits in front and sends each question down the pipeline it actually needs. Routing each query to the appropriate retrieval pipeline based on complexity is the emerging best practice for the cost and quality tradeoff, and it is also a latency play, because most traffic is simple.</p>
<p>A practical dual pipeline looks like this:</p>
<pre><code class="language-python">def route(question: str, qvec):
    if (ans := cached_answer(question, qvec)):
        return ans                       # ~10 ms

    if classifier.is_simple(question):   # short, single fact, no comparison
        hits = index.search(qvec, top_k=5)
        return small_llm.complete(build_prompt(question, hits))   # ~400 ms

    hits = index.search(qvec, top_k=30)
    hits = reranker.rank(question, hits)[:5]
    return large_llm.complete(build_prompt(question, hits))       # ~1.8 s
</code></pre>
<p>The classifier does not need to be a model. Query length, presence of comparison words, and whether the question maps cleanly to a single document section will get you a long way. Whatever you use, log the routing decision alongside the latency buckets so you can see when it routes wrong.</p>
<p>Two things to watch. The classifier itself is now on the critical path, so keep it under 20 milliseconds. And route conservatively at first: sending a hard question down the cheap path produces a confidently wrong answer, which costs far more than the 1.4 seconds you saved.</p>
<h2>Measure P95, not the average</h2>
<p>One last discipline. Report P95 latency and P99 latency per bucket, and treat the average as decoration. The average tells you the system is fine. The tail tells you that 1 in 20 users waits four seconds because their query missed the cache, matched a filtered partition badly, and pulled 30 chunks into a prompt.</p>
<p>Latency work without per bucket instrumentation is guessing with extra steps. Get the histogram first, then pull the levers in order.</p>
<h2>FAQ</h2>
<p><strong>What is the average latency of a RAG system?</strong> Production RAG systems average 1.2 to 2.5 seconds end to end. That breaks down into roughly 50 to 100 milliseconds for query embedding, 100 to 300 milliseconds for vector search, and 1 to 2 seconds for LLM generation. Generation is the dominant bucket in almost every deployment, which is why streaming and context reduction beat vector database migrations for perceived speed.</p>
<p><strong>How do you reduce RAG retrieval latency?</strong> In order of effect per unit of effort: stream the response so time to first token drops, add semantic caching so repeated and paraphrased queries skip generation entirely, shrink the retrieved context to 3 to 5 reranked chunks, tune your ANN index parameters such as <code>ef_search</code> or <code>nprobe</code> against your own gold query set, and finally move the index into memory. Measure each bucket separately before and after every change.</p>
<p><strong>What is HNSW indexing?</strong> HNSW stands for hierarchical navigable small world. It is an approximate nearest neighbour index that stores vectors in a layered proximity graph and walks from a sparse upper layer down to a dense lower one, so a query touches a tiny fraction of the corpus instead of all of it. Alongside IVF, it delivers query latencies as low as 15 milliseconds at 1 million vectors while keeping recall high enough that answer quality is unaffected.</p>
]]></content:encoded></item><item><title><![CDATA[Session vs JWT in Next.js 16: What Changed and What Most Guides Get Wrong]]></title><description><![CDATA[Every time someone asks whether to use sessions or JWT for authentication in Next.js, the honest answer is "it depends on what you're building," and then…]]></description><link>https://mudassirworks.hashnode.dev/session-vs-jwt-in-next-js-16-what-changed-and-what-most-guides-get-wrong</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/session-vs-jwt-in-next-js-16-what-changed-and-what-most-guides-get-wrong</guid><category><![CDATA[Next.js]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Security]]></category><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Fri, 21 Aug 2026 19:45:01 GMT</pubDate><content:encoded><![CDATA[<p>Every time someone asks whether to use sessions or JWT for authentication in Next.js, the honest answer is "it depends on what you're building," and then the conversation stalls because most guides never explain what it actually depends on. This one will. By the end you'll know how server sessions work in the Next.js 16 App Router, how JWTs work and why they feel easier at first, where each one quietly breaks, and which one you should reach for on your next project.</p>
<h2>How sessions work in Next.js 16 App Router</h2>
<p>A server session is simple in concept: the server creates a record (in a database, Redis, or an encrypted cookie) when a user logs in, hands the browser an opaque session ID, and looks that ID up on every request. The user's actual data never leaves the server.</p>
<p>In the App Router, this pattern usually looks like a Server Action that runs on login, sets an HTTP only cookie, and stores the session server side:</p>
<pre><code class="language-ts">"use server";

import { cookies } from "next/headers";
import { createSession } from "@/lib/session";

export async function login(formData: FormData) {
  const user = await verifyCredentials(formData);
  const sessionId = await createSession(user.id);

  (await cookies()).set("session", sessionId, {
    httpOnly: true,
    secure: true,
    sameSite: "strict",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
  });
}
</code></pre>
<p>That <code>httpOnly</code> flag matters more than most tutorials admit. Client side JavaScript cannot read an HTTP only cookie, which closes off the most common attack path against session tokens: cross site scripting, or XSS. If an attacker manages to inject a script into your page, that script still cannot reach the cookie. HTTP only cookies remain exposed to a different attack, cross site request forgery (CSRF), where a malicious site tricks the browser into sending an authenticated request on your behalf. Setting <code>sameSite: "strict"</code> (or at minimum <code>"lax"</code>) is the mitigation, and it's the reason you see it in almost every serious session setup.</p>
<p>Route protection then happens in middleware, which runs at the edge before the request ever reaches a page or Server Action:</p>
<pre><code class="language-ts">import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const session = request.cookies.get("session");
  if (!session &amp;&amp; request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  return NextResponse.next();
}
</code></pre>
<p>For server sessions this middleware check is usually just presence, not validation. The real lookup (does this session ID still exist, is it expired, has it been revoked) happens where the session is actually created and read, because middleware runs on the edge runtime and shouldn't be doing a database round trip on every request.</p>
<h2>How JWTs work and why they feel easier</h2>
<p>A JSON Web Token bundles the user's claims (id, role, expiry) into a signed payload the server can verify without a database lookup. That's the appeal: no session store, no extra round trip, works the same whether you're serving a web page or an API.</p>
<p>JWT based auth in the Next.js 16 App Router leans on the same primitives as sessions: Server Actions issue the token on login and logout, middleware protects routes, and <code>cache()</code> lets you share the decoded session across server components in a single request without re verifying the token on every read.</p>
<pre><code class="language-ts">import { cache } from "react";
import { jwtVerify } from "jose";

export const getSession = cache(async () =&gt; {
  const token = (await cookies()).get("token")?.value;
  if (!token) return null;
  try {
    const { payload } = await jwtVerify(token, secret);
    return payload;
  } catch {
    return null;
  }
});
</code></pre>
<p>Because <code>cache()</code> dedupes the call per request, you can call <code>getSession()</code> from a layout, a page, and a nested component and only pay the verification cost once. That's a genuine ergonomic win, and it's the reason JWT patterns keep getting recommended in App Router tutorials.</p>
<p>The catch is storage. If you keep the JWT in <code>localStorage</code> so client components can read it directly, it's fully exposed to XSS: any script that runs on your page can read <code>localStorage</code> and exfiltrate the token, no cookie flags involved. Most production ready Next.js JWT setups avoid this entirely by keeping the token in an HTTP only cookie too, which closes the XSS gap but reopens the question of why you're using a JWT instead of an opaque session ID in the first place.</p>
<h2>The security tradeoffs most guides skip</h2>
<p>This is the part most JWT vs session tutorials gloss over, so it's worth stating plainly: the tradeoff isn't really about tokens versus sessions, it's about statelessness versus revocation.</p>
<p>A session is trivial to revoke. Delete the record server side, and the user is logged out everywhere, instantly, including on every device and every open tab. A JWT is valid until it expires, full stop, because the whole point is that the server doesn't need to check a store to trust it. If someone steals a JWT with a seven day expiry, that token works for seven days unless you build a separate revocation list, at which point you've reintroduced a server side lookup and lost the statelessness that made JWTs attractive.</p>
<p>That single property, token revocation, is usually the deciding factor:</p>
<ul>
<li><p>If you need to instantly kill a compromised session (a stolen device, a fired employee, a password reset), you want the immediate, guaranteed revocation that server sessions give you for free.</p>
</li>
<li><p>If your access tokens are short lived (a common pattern is 15 minutes) and paired with a refresh token you can revoke, JWTs get a workable approximation of instant revocation without giving up statelessness for the access token itself.</p>
</li>
</ul>
<p>Combine that with the XSS and CSRF picture from earlier and you get a fuller comparison: sessions in HTTP only cookies are safe from XSS and need SameSite for CSRF; JWTs in localStorage are exposed to XSS with no CSRF risk; JWTs in HTTP only cookies get the same protection profile as sessions but without the easy revocation.</p>
<h2>When to use sessions</h2>
<p>Reach for server sessions when you're building a first party web app where the browser is the only client that matters. Server sessions let you revoke access immediately, they keep zero sensitive data on the client, and they pair naturally with the App Router's server first model, since a Server Component can just read the session cookie and hit your session store directly without shipping any auth logic to the client.</p>
<p>They're also the safer default when your team is still building auth expertise: there's less surface area to get wrong, because the hard cryptographic decisions (signing algorithm, key rotation, expiry tuning) belong to whatever session library or database you're using instead of your own code.</p>
<h2>When JWTs are the right call</h2>
<p>JWTs earn their complexity in a specific shape of system: stateless APIs consumed by a mobile app or a third party integration, or a microservices setup where multiple services need to trust a user's identity without every single service making a call back to a central session store. In that world, a signed token that any service can verify independently is exactly the right tool, because the alternative (every microservice querying a shared session store on every request) is slower and adds a hard dependency between services that otherwise shouldn't need to know about each other.</p>
<p>If your Next.js app is purely first party, though, that stateless benefit mostly evaporates. You're not passing the token to another service, so you've taken on JWT's revocation weaknesses without collecting the payoff that makes them worth it elsewhere.</p>
<h2>What most teams choose today</h2>
<p>Ask around and you'll notice a pattern: most current Next.js auth stacks, including Auth.js (formerly NextAuth), Better Auth, and Supabase Auth, default to server sessions rather than JWTs for first party web apps. That's not an accident. It reflects the tradeoff above playing out at scale: for a typical Next.js app talking to itself, the revocation and simplicity of sessions win more often than the statelessness of JWTs pays off.</p>
<p>If you're starting a new App Router project and don't have a strong reason to reach for JWTs (a public API, a mobile client, a microservices boundary), start with server sessions through Auth.js or a similar library, store the session cookie as HTTP only with SameSite set to strict, and only bring in JWTs later if a genuine stateless use case shows up.</p>
<h2>FAQ</h2>
<p><strong>Should I use sessions or JWT in Next.js?</strong> For a standard first party Next.js web app, use sessions. They're easier to revoke instantly, keep no sensitive payload on the client, and fit the App Router's server first design. Reach for JWTs only when you have a real stateless requirement, like a public API or a mobile client that needs to verify identity without hitting your server on every call.</p>
<p><strong>What is the difference between session based and JWT authentication?</strong> Session based authentication stores the user's state on the server and hands the browser an opaque ID that means nothing on its own; the server looks up that ID on every request. JWT authentication bundles the user's claims into a signed token the server can verify without a lookup, trading a database round trip for a token that can't be revoked before it expires.</p>
<p><strong>Is JWT secure for Next.js applications?</strong> It can be, but only with the right storage choice. A JWT kept in <code>localStorage</code> is exposed to XSS, since any script running on the page can read it. A JWT kept in an HTTP only cookie is protected from XSS the same way a session cookie is, and needs the same SameSite protection against CSRF. The security question isn't really about JWT versus sessions as concepts; it's about where the token or session ID lives in the browser.</p>
]]></content:encoded></item><item><title><![CDATA[Context Engineering for RAG: How to Fill the Context Window With the Right Information]]></title><description><![CDATA[Most RAG systems that disappoint in production do not fail at retrieval. They fail at assembly. The retriever returns something plausible, the prompt gets…]]></description><link>https://mudassirworks.hashnode.dev/context-engineering-for-rag-how-to-fill-the-context-window-with-the-right-information</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/context-engineering-for-rag-how-to-fill-the-context-window-with-the-right-information</guid><category><![CDATA[AI]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[llm]]></category><category><![CDATA[MachineLearning]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Wed, 19 Aug 2026 19:35:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/9a65fcd3-c8c9-44d9-a574-39d4e943bc94.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most RAG systems that disappoint in production do not fail at retrieval. They fail at assembly. The retriever returns something plausible, the prompt gets stuffed with all of it, and the model answers confidently from the wrong paragraph. Context engineering for RAG is the discipline that sits between those two steps: deciding what actually enters the context window, in what order, and at what token cost.</p>
<p>This article covers the four decisions that move accuracy the most, in the order you should fix them: how you chunk, how you retrieve, how you order, and how you budget. By the end you will have a context assembly checklist you can apply to a pipeline you already run, without rewriting it.</p>
<h2>Context engineering: the discipline beyond RAG setup</h2>
<p>Context engineering is the practice of deciding what information enters a model's context window, how that information is structured, and where inside the window it sits, so the model has exactly what it needs to answer and as little as possible to distract it. Prompt engineering tunes the instructions. Context engineering for LLM systems tunes the evidence.</p>
<p>The reason this became its own concern is unpleasant and well measured. A research study testing 18 leading models found that every single one performed worse as input length grew. Some fell from 95% accuracy to 60% on the same task, purely because more text was sitting in the window. Bigger windows did not buy reliability. They bought room to make a mess.</p>
<p>So the mental model that survives contact with production is this: the context window is a budget, not a container. Every passage you add has to earn its place against the passages already there, because the cost of a weak passage is not zero. It is measured in the attention it steals from a strong one.</p>
<h2>What to put in the LLM context window</h2>
<p>Before tuning retrieval, audit what your prompt already contains. In most pipelines I have opened up, the window holds four categories of text:</p>
<ul>
<li><p>System instructions and output format rules</p>
</li>
<li><p>Retrieved evidence from the corpus</p>
</li>
<li><p>Conversation state or prior turns</p>
</li>
<li><p>Tool schemas and function definitions</p>
</li>
</ul>
<p>Only one of those is the subject of retrieval, yet the other three quietly consume a large share of the window and almost never get trimmed. A verbose system prompt and an unpruned chat history can crowd out the retrieved passages that actually answer the question.</p>
<p>The practical rule: keep instructions terse, give retrieved evidence the clear majority of the budget, summarise old conversation turns rather than replaying them, and always hold back headroom for the answer itself. Then measure. If the retrieved evidence is not the largest block in your prompt, retrieval quality is not your bottleneck yet.</p>
<h2>Why tutorial chunk sizes of 1,500 to 2,000 tokens cause retrieval failure</h2>
<p>Almost every RAG tutorial defaults to chunks of roughly 1,500 to 2,000 tokens. That default is convenient, and for domain specific content it loses retrieval signal. A chunk that large usually contains several distinct ideas, so its embedding becomes an average of all of them and matches nothing sharply. You then retrieve a passage that is topically adjacent to the question but does not contain the sentence that answers it.</p>
<p>A sound RAG chunking strategy pushes in the other direction: smaller chunks, generous overlap, tuned per corpus rather than copied from a blog post. Overlap matters because meaning does not respect your split points. A definition that starts at the end of one chunk and finishes at the start of the next is invisible to both embeddings unless the windows share tokens.</p>
<pre><code class="language-python">def chunk(text, size=350, overlap=80):
    tokens = tokenizer.encode(text)
    step = size - overlap
    out = []
    for start in range(0, len(tokens), step):
        window = tokens[start:start + size]
        if len(window) &lt; 40:
        break
        out.append(tokenizer.decode(window))
    return out
</code></pre>
<p>Two things to know before you copy that. First, <code>size</code> and <code>overlap</code> are starting points, not answers. Dense reference material and API documentation reward smaller windows; narrative documents and policy text often need larger ones to stay coherent. Second, tune it with an evaluation set of real questions, not by reading samples. Chunking is the one knob where intuition is consistently wrong and a fifty question eval set settles the argument in an afternoon.</p>
<h2>The production default: hybrid BM25 and dense retrieval with a reranker</h2>
<p>Pure vector search is the single most common architectural shortcut in RAG, and it is the one that fails most visibly on the queries that matter. Semantic search is excellent at paraphrase and terrible at exactness. Ask it for an error code, a product SKU, a config key, or a surname, and it will happily return five passages about the same general theme and none containing the literal token you asked for.</p>
<p>The default that production systems converge on is a hybrid pipeline: BM25 lexical search for exact terms, dense vector search for meaning, and a cross encoder reranker that scores the merged candidates against the actual question. Not dense retrieval alone. The three stages each cover a different failure mode, which is precisely why the combination beats any one of them.</p>
<p>Hybrid search for RAG with BM25 is easier to add than most teams expect, because you do not need a clever merge. Reciprocal rank fusion combines two ranked lists using position only, so you never have to normalise a BM25 score against a cosine similarity.</p>
<pre><code class="language-python">def rrf(rankings, k=60):
    scores = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking, start=1):
            scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)

candidates = rrf([
    bm25_search(question, top=50),
    vector_search(question, top=50),
])

passages = reranker.rank(question, candidates[:30])[:8]
</code></pre>
<p>Retrieve wide, rerank hard, pass few. The reranker is what lets you widen the first stage safely: you can pull 50 candidates from each retriever precisely because a cross encoder will throw most of them away before anything reaches the model. Skipping the reranker and sending 30 raw candidates into the prompt is how teams end up with the accuracy curve described earlier.</p>
<h2>Ordering matters: lost in the middle is a real architectural problem</h2>
<p>Once you have eight good passages, the obvious move is to paste them in relevance order and stop thinking. That is a mistake with a name. Models pay significantly less attention to information placed in the middle of a long context than to information at the start or the end, and this precision loss shows up once the window is past roughly 30% full. Your best passage, sitting fourth of eight, is in the worst seat in the room.</p>
<p>The fix costs nothing. Place your highest scoring passages at the edges and fold the weaker ones into the middle, where the attention penalty does the least damage.</p>
<pre><code class="language-python">def order_for_attention(passages):
    ranked = sorted(passages, key=lambda p: p.score, reverse=True)
    head, middle, tail = [], [], []
    for i, p in enumerate(ranked):
        bucket = (head, tail, middle)[i % 3]
        bucket.append(p)
    return head + middle + tail[::-1]
</code></pre>
<p>Two habits reinforce this. Repeat the question immediately after the evidence block as well as before it, so the instruction occupies an edge position too. And resist the urge to pad: if a passage scored poorly enough that you are burying it in the middle for safety, consider whether it belongs in the prompt at all.</p>
<h2>A context assembly checklist for production RAG</h2>
<p>Run this against an existing pipeline in order. Each step is independently useful, so you can stop when the accuracy gain flattens.</p>
<ul>
<li><p>Count the tokens in your prompt by category, and confirm retrieved evidence is the largest block</p>
</li>
<li><p>Cut chunk size well below the tutorial default and add overlap, then verify against an eval set rather than by eye</p>
</li>
<li><p>Add BM25 alongside vector search and fuse the two lists with reciprocal rank fusion</p>
</li>
<li><p>Add a cross encoder reranker, widen first stage recall, and narrow what reaches the model</p>
</li>
<li><p>Order the surviving passages strongest at the edges, weakest in the middle</p>
</li>
<li><p>Restate the question after the evidence block</p>
</li>
<li><p>Log the assembled prompt for every failed answer, because most RAG bugs are visible on inspection of the context and invisible in the metrics</p>
</li>
</ul>
<p>The order is deliberate. Chunking and hybrid retrieval change what is available to the model, and ordering and budgeting change what the model can actually use. Fixing assembly on top of bad retrieval just arranges the wrong evidence more neatly.</p>
<h2>FAQ</h2>
<h3>What is context engineering for LLMs?</h3>
<p>Context engineering is the practice of deciding what information goes into a model's context window, how it is structured, and where it is positioned, so the model receives the evidence it needs and little else. It covers chunking, retrieval, reranking, ordering, and token budgeting. Prompt engineering optimises what you ask; context engineering optimises what the model has in front of it while answering.</p>
<h3>How do you choose chunk size for RAG?</h3>
<p>Start well below the common tutorial range of 1,500 to 2,000 tokens, because chunks that large blend several ideas into one embedding and match queries weakly. Use meaningful overlap so ideas that straddle a boundary stay retrievable. Then tune per corpus against an evaluation set of real questions: dense reference material generally wants smaller chunks, while narrative or policy text needs larger ones to stay coherent.</p>
<h3>What is hybrid search in RAG?</h3>
<p>Hybrid search runs lexical retrieval such as BM25 and dense vector retrieval over the same corpus and merges the results, usually with reciprocal rank fusion, before a cross encoder reranker scores the merged candidates. BM25 catches exact tokens like error codes and identifiers that embeddings blur, while vector search catches paraphrase that keyword matching misses. The combination is the production default because each stage covers the other's failure mode.</p>
]]></content:encoded></item><item><title><![CDATA[Connecting Claude Code to your tools with MCP: a production integration guide]]></title><description><![CDATA[By the end of this guide you will have a working MCP server registered inside Claude Code, and you will understand the three transport options well enough…]]></description><link>https://mudassirworks.hashnode.dev/connecting-claude-code-to-your-tools-with-mcp-a-production-integration-guide</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/connecting-claude-code-to-your-tools-with-mcp-a-production-integration-guide</guid><category><![CDATA[AI]]></category><category><![CDATA[mcp]]></category><category><![CDATA[tooling]]></category><category><![CDATA[claude]]></category><category><![CDATA[devtools]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Sun, 16 Aug 2026 19:41:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/2985639a-5262-4880-87e2-c168caa03034.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>By the end of this guide you will have a working MCP server registered inside Claude Code, and you will understand the three transport options well enough to pick the right one for your own setup. This is a practical model context protocol tutorial: less theory, more copy and run code. If you have ever written a custom integration for every single tool an AI assistant needed to call, mcp claude code integration is the fix for that, and this walkthrough covers the production details most tutorials skip.</p>
<h2>What MCP actually does (a <code>USB-C</code> analogy made precise)</h2>
<p>Before this protocol existed, connecting an AI model to an external tool meant writing a bespoke adapter for that exact tool and that exact model. A database connector for one assistant did not work with another assistant. A search tool built for one vendor's function calling format had to be rewritten from scratch for the next vendor. Every pairing of model and tool was its own one off project, and none of that work carried over.</p>
<p>The <code>USB-C</code> comparison is useful because it is precise, not just catchy. A <code>USB-C</code> port does not care what you plug into it. The same port charges a phone, drives a monitor, and moves files, because the devices on both ends agree on a shared interface. MCP does the same job for AI systems: it defines one interface between a model and any tool, database, or file system that speaks the protocol. You write a tool definition once, expose it through an MCP server, and any MCP aware client, including Claude Code and Claude Desktop, can discover and call it without custom glue code.</p>
<p>That single change is why teams building internal tooling now build one MCP server per system (a database, a ticketing tool, an internal API) instead of one integration per model per system. The server becomes reusable infrastructure rather than throwaway code tied to a single assistant.</p>
<h2>The three transport options: stdio, HTTP, and Server Sent Events</h2>
<p>An MCP server needs a way to exchange messages with the client that is calling it. There are three transports in common use, and picking the right one matters more than most guides let on.</p>
<p><strong>Stdio transport</strong> runs the server as a local subprocess and talks to it over standard input and standard output. This is the default choice for anything running on the same machine as the client, including most local developer tooling. It has no network layer to secure or debug, which makes it the simplest option to reason about.</p>
<p><strong>HTTP transport</strong> is what you reach for once the server needs to live somewhere else, for example behind an internal API gateway shared by a whole team. It supports authentication headers, load balancing, and the usual HTTP tooling you already run in production, at the cost of an extra network hop.</p>
<p><strong>Server Sent Events</strong>, often shortened to <code>SSE</code>, layers a persistent one way stream on top of HTTP so the server can push updates to the client as they happen, rather than waiting to be asked. It suits long running tool calls where partial results are useful before the call finishes.</p>
<p>Every one of these transports carries the same message format underneath: <code>JSON-RPC 2.0</code>. That is a meaningful design choice. <code>JSON-RPC 2.0</code> gives MCP a stateful session model, meaning the client and server track a shared session across multiple calls, something a plain REST API cannot replicate without you building custom session handling on top of it yourself. Here is what a tool call looks like on the wire:</p>
<pre><code class="language-json">{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "search_docs",
    "arguments": {
      "query": "authentication flow"
    }
  },
  "id": 7
}
</code></pre>
<h2>Writing your first MCP server in TypeScript</h2>
<p>The official TypeScript SDK gives you a small, well tested surface for defining tools and running a server. Install it alongside <code>zod</code>, which the SDK uses to validate tool arguments:</p>
<pre><code class="language-sh">npm install @modelcontextprotocol/sdk zod
</code></pre>
<p>A minimal server that exposes one tool looks like this:</p>
<pre><code class="language-typescript">import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "docs search server",
  version: "1.0.0",
});

server.tool(
  "search_docs",
  "Search internal documentation by keyword",
  { query: z.string() },
  async ({ query }) =&gt; {
    const result = `Found 3 matches for "${query}"`;
    return {
      content: [{ type: "text", text: result }],
    };
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);
</code></pre>
<p>Each <code>server.tool</code> call is a full tool definition: a name the model will refer to, a description that tells the model when to reach for this tool, a <code>zod</code> schema describing the arguments, and a handler that does the actual work. Everything past this point is regular application code. You can call a database, hit an internal API, or read a file inside that handler exactly as you would in any other TypeScript service.</p>
<h2>Connecting to Claude Code: the config file approach</h2>
<p>Once your server runs locally, Claude Code needs to know it exists. That registration lives in a config file at a path such as <code>~/.claude/mcp-config.json</code>. A minimal entry that points Claude Code at the server you just wrote looks like this:</p>
<pre><code class="language-json">{
  "mcpServers": {
    "docs-search": {
      "command": "node",
      "args": ["./dist/server.js"]
    }
  }
}
</code></pre>
<p>For a server exposed over <code>HTTP</code> instead of <code>stdio</code>, the entry carries a <code>url</code> field and, where the server requires it, an authentication header:</p>
<pre><code class="language-json">{
  "mcpServers": {
    "internal-api": {
      "url": "https://internal.example.com/mcp",
      "headers": {
        "Authorization": "Bearer your token here"
      }
    }
  }
}
</code></pre>
<p>Restart Claude Code after editing the file, then run <code>claude mcp list</code> from a terminal. A server that registered correctly shows up with a connected status; anything else means the command or path in the config entry is wrong, which is worth checking first before assuming the server code itself is broken.</p>
<h2>What MCP does to integration time</h2>
<p>This is the part that actually changes team behavior. Teams migrating to an MCP native architecture report integration deployment time dropping from three days to eleven minutes for new tool connections. That is not a rounding error, it is close to two orders of magnitude, and the reason is structural rather than a matter of writing faster code. The three day number reflects the old cost of a custom integration: understanding a vendor's function calling format, writing an adapter, testing it against that one model, then repeating the whole process for the next model. The eleven minute number reflects registering an existing, already tested MCP server in a config file. Once one team has published a well built server for a system, every other team calling that same system through MCP inherits the work for free.</p>
<h2>The mcp server production ecosystem: how many servers exist</h2>
<p>The best mcp servers today span a wide range of categories: databases, developer tools, communication platforms, and cloud infrastructure. The ecosystem includes over 50 official servers maintained directly, alongside more than 12,000 community implementations covering everything from niche internal tools to widely used SaaS products. Anthropic's MCP tooling has surpassed 97 million monthly SDK downloads and earned over 81,000 GitHub stars, numbers that reflect adoption well past the early experimentation phase.</p>
<p>For a claude code mcp server specifically, the practical advice is to check the community registry before writing your own. A large share of common integrations, ticketing systems, source control platforms, and search tools, already have a maintained server available, and registering an existing one is exactly the eleven minute path described above.</p>
<p>There is also a related concept worth knowing about even if you do not need it yet: agent to agent communication, often called <code>A2A</code>. Where MCP standardizes how a model talks to tools, <code>A2A</code> protocols standardize how separate autonomous agents coordinate with each other. The two are complementary layers rather than competitors, and production systems increasingly use both.</p>
<h2>FAQ</h2>
<h3>How do I connect MCP servers to Claude Code?</h3>
<p>Register the server in the Claude Code config file, typically at <code>~/.claude/mcp-config.json</code>, with either a <code>command</code> and <code>args</code> pair for a local stdio server or a <code>url</code> and optional <code>headers</code> for a remote HTTP server. Restart Claude Code, then confirm the connection with <code>claude mcp list</code>. A correctly registered server appears with a connected status immediately.</p>
<h3>What are the best mcp servers?</h3>
<p>There is no single best server, it depends on what you need to connect to. The strongest choices are official servers maintained by the tool vendor itself, followed by community servers with active maintainers and real usage. With over 50 official servers and more than 12,000 community implementations available, checking the registry before building your own is almost always the faster path.</p>
<h3>How long does it take to build an MCP integration?</h3>
<p>Writing a new server from scratch, including a handful of tool definitions and basic testing, typically takes a few hours for a simple internal tool. Registering an existing server that someone else already built and published takes closer to eleven minutes, which is the number teams report after moving to an MCP native workflow instead of writing custom per model adapters.</p>
]]></content:encoded></item><item><title><![CDATA[LiteLLM vs OpenRouter: When to Self Host Your LLM Gateway and When Not To]]></title><description><![CDATA[The LiteLLM vs OpenRouter question looks like a feature comparison and is really an operating model choice. One is a proxy you run inside your own…]]></description><link>https://mudassirworks.hashnode.dev/litellm-vs-openrouter-when-to-self-host-your-llm-gateway-and-when-not-to</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/litellm-vs-openrouter-when-to-self-host-your-llm-gateway-and-when-not-to</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[MachineLearning]]></category><category><![CDATA[infrastructure]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Fri, 14 Aug 2026 20:14:23 GMT</pubDate><content:encoded><![CDATA[<p>The LiteLLM vs OpenRouter question looks like a feature comparison and is really an operating model choice. One is a proxy you run inside your own infrastructure. The other is a managed endpoint you call across the public internet. Both hand you a unified API over many models, both do model routing and fallback, and both will serve production traffic without complaint. What actually separates them is who carries the pager at 3am when a provider starts returning 529s.</p>
<p>This guide walks through what each system does, where their routing controls diverge, what the latency and cost math looks like in practice, and a decision table you can take into a design review. By the end you will know which side of the self host line your workload belongs on, and exactly what you trade away in either direction.</p>
<h2>LLM gateway vs LLM router: what is the difference</h2>
<p>Get the definition straight first, because these two terms get swapped around constantly and they are not the same layer.</p>
<p>An <strong>LLM gateway</strong> is the infrastructure that sits between your application and every model provider. It owns authentication, a single unified API surface, rate limits, retries, caching, request logging, and cost attribution. An <strong>LLM router</strong> is one feature living inside that gateway: the logic picking which model or which provider serves a given request, based on price, latency, throughput, or availability.</p>
<p>Every router needs a gateway wrapped around it. Not every gateway routes intelligently. That asymmetry explains why a pure play router struggled as a standalone business while gateways kept expanding, which is the Martian story further down this page.</p>
<p>Both LiteLLM and OpenRouter are gateways with routers inside. The interesting difference is where the gateway runs.</p>
<h2>LiteLLM: a self hosted OpenAI compatible proxy for 100+ models</h2>
<p>LiteLLM exposes an OpenAI compatible interface to 100+ model providers and is the most widely adopted open source LLM proxy in production. That single sentence carries most of its value proposition. Your application keeps talking to the OpenAI SDK it already imports. You change a base URL and a key, and suddenly Anthropic, Bedrock, Vertex, Azure, and a local vLLM endpoint are all reachable through the same call shape.</p>
<p>The configuration lives in a YAML file you own:</p>
<pre><code class="language-yaml">model_list:
  - model_name: chat-primary
    litellm_params:
      model: anthropic/claude-sonnet-4-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: chat-primary          # same alias, second provider
    litellm_params:
      model: bedrock/anthropic.claude-sonnet-4-5-v1:0
      aws_region_name: us-east-1

router_settings:
  routing_strategy: latency-based-routing
  num_retries: 2
  fallbacks:
    - chat-primary: ["chat-cheap"]

litellm_settings:
  cache: true
  cache_params:
    type: redis
    ttl: 3600
</code></pre>
<p>Two entries share one <code>model_name</code>, so the router load balances across them and fails over automatically when one provider degrades. Your application code never learns that happened:</p>
<pre><code class="language-python">from openai import OpenAI

client = OpenAI(
    base_url="https://llm-gateway.internal/v1",
    api_key=os.environ["LITELLM_VIRTUAL_KEY"],
)

resp = client.chat.completions.create(
    model="chat-primary",
    messages=[{"role": "user", "content": prompt}],
)
</code></pre>
<h3>What a LiteLLM production deployment actually involves</h3>
<p>This is the part that gets skipped in comparison posts. Running the proxy properly means running a small service, not dropping in a library:</p>
<ul>
<li><p>A container running the proxy, ideally two or more replicas behind a load balancer.</p>
</li>
<li><p>Postgres for virtual keys, team budgets, and spend tracking.</p>
</li>
<li><p>Redis for the response cache and for rate limits shared across replicas.</p>
</li>
<li><p>Provider credentials in your own secret store, which is precisely the reason many teams choose this path.</p>
</li>
<li><p>Alerting on the proxy itself, because you have inserted a new single point of failure into every model call.</p>
</li>
</ul>
<p>None of that is exotic. It is roughly the operational weight of running your own Redis. But it is real work, and it recurs. Version upgrades on a fast moving open source proxy are not free either.</p>
<p>What you buy with that work: provider keys never leave your network, prompts never transit a third party, you can pin the proxy inside a VPC for compliance review, and your per token cost is exactly the provider list price with no intermediary margin.</p>
<h2>OpenRouter: the managed edge path to hundreds of models</h2>
<p>OpenRouter inverts the deal. There is nothing to deploy. You point at one base URL with one key and get access to hundreds of models across dozens of providers, with billing consolidated into a single invoice.</p>
<p>The routing controls are the genuinely strong part of the OpenRouter API. Out of the box it offers default provider load balancing, explicit provider ordering, model fallbacks, price based routing, throughput sorting, latency sorting, and data policy filters. That last one deserves attention: you can instruct the gateway to only touch providers that do not train on your data, which is a policy control most teams end up hand rolling elsewhere.</p>
<p>You express all of it inline per request:</p>
<pre><code class="language-json">{
  "model": "anthropic/claude-sonnet-4.5",
  "models": ["openai/gpt-5.1", "google/gemini-3-pro"],
  "provider": {
    "sort": "latency",
    "order": ["anthropic", "amazon-bedrock"],
    "allow_fallbacks": true,
    "data_collection": "deny"
  },
  "messages": [{ "role": "user", "content": "..." }]
}
</code></pre>
<p>The <code>models</code> array is the fallback chain. The <code>provider</code> block is the router configuration. Shipping a routing policy change means editing a request body, not redeploying infrastructure. For a small team moving fast, that speed difference is the whole argument.</p>
<p>The costs are equally concrete. Your prompts traverse a third party. You inherit their uptime, and an outage on their side is an outage on yours with no remediation lever beyond a status page. There is a margin on top of provider pricing. And for regulated workloads, adding a processor to the data path is a conversation with legal, not an afternoon of engineering.</p>
<h2>Head to head: routing controls, latency, and data policy</h2>
<table>
<thead>
<tr>
<th>Dimension</th>
<th>LiteLLM</th>
<th>OpenRouter</th>
</tr>
</thead>
<tbody><tr>
<td>Deployment</td>
<td>You run it, in your VPC</td>
<td>Managed, zero deployment</td>
</tr>
<tr>
<td>Model reach</td>
<td>100+ providers via config</td>
<td>Hundreds of models, no config</td>
</tr>
<tr>
<td>Routing config</td>
<td>YAML plus redeploy</td>
<td>Per request JSON</td>
</tr>
<tr>
<td>Data path</td>
<td>Never leaves your network</td>
<td>Transits a third party</td>
</tr>
<tr>
<td>Provider keys</td>
<td>Yours, held locally</td>
<td>Theirs, one key for you</td>
</tr>
<tr>
<td>Cost model</td>
<td>Provider list price</td>
<td>Provider price plus margin</td>
</tr>
<tr>
<td>Failure blast radius</td>
<td>Your proxy, your fix</td>
<td>Their edge, their fix</td>
</tr>
<tr>
<td>Best fit</td>
<td>Compliance, high volume, custom logic</td>
<td>Prototypes, breadth, small teams</td>
</tr>
</tbody></table>
<p>On latency, keep the numbers in proportion. A routing layer adds roughly 2 to 20ms of overhead per request, against model responses measured in hundreds or thousands of milliseconds. That overhead is noise. Chasing it is the wrong optimization.</p>
<p>The number worth chasing is cost. Correctly implemented caching plus deliberate provider selection can cut model inference cost by 40 to 90% for high volume workloads. That is not a rounding error, it is a budget line item, and it is the strongest reason to put a gateway of any kind in front of your models. Both options give you the mechanism. Only you can supply the discipline to use it.</p>
<p>One nuance teams miss: the self host path lets you cache across every application in the company against one shared Redis. Cache hit rates compound with traffic volume, so the larger your request count, the more the economics tilt toward running your own layer.</p>
<h2>Martian's exit and what it signals about the market</h2>
<p>Martian raised a $9M Series A specifically for model routing. It was acquired by Notion, and the team pivoted into AI interpretability research, effectively leaving the standalone router market.</p>
<p>Read that as a market signal rather than a product obituary. Routing on its own turned out not to be a business. It is a feature, and features get absorbed by the layer that owns the connection: the gateway holding your keys, your logs, and your spend data. That layer has the observability to route well and the switching cost to keep you.</p>
<p>The practical takeaway for anyone evaluating this category: prefer vendors whose routing sits inside a gateway you would want regardless of the routing. A router with nothing underneath it has nowhere to stand.</p>
<h2>Decision table: which to use when</h2>
<p>Pick the <strong>self hosted LLM proxy</strong> path if any of these are true:</p>
<ul>
<li><p>Prompts contain regulated or customer identifying data that cannot transit a third party.</p>
</li>
<li><p>Your volume is high enough that intermediary margin exceeds the cost of running two containers.</p>
</li>
<li><p>You need custom routing logic, per team budgets, or virtual keys tied to internal identity.</p>
</li>
<li><p>You already operate Postgres and Redis, so the marginal ops burden is small.</p>
</li>
<li><p>An audit will ask you to draw the data path on a whiteboard.</p>
</li>
</ul>
<p>Pick <strong>OpenRouter</strong> if any of these are true:</p>
<ul>
<li><p>You are still discovering which model fits, and breadth beats control.</p>
</li>
<li><p>Nobody on the team wants to own another service.</p>
</li>
<li><p>You want price based routing and data policy filters without building them.</p>
</li>
<li><p>Traffic is modest enough that the margin costs less than an engineer's attention.</p>
</li>
<li><p>You want to ship a routing policy change today, not next sprint.</p>
</li>
</ul>
<p>A pattern worth naming: many teams start managed, learn their real traffic shape and model mix, then move the top two or three high volume routes onto a self hosted proxy while leaving the long tail on the managed edge. Because both speak an OpenAI compatible API, that migration is a base URL change rather than a rewrite. Starting managed does not lock you in, which makes it a reasonable default when you are genuinely unsure.</p>
<h2>FAQ</h2>
<p><strong>What is the difference between LiteLLM and OpenRouter?</strong></p>
<p>LiteLLM is an open source proxy you deploy and operate yourself, giving you an OpenAI compatible interface to 100+ providers with your keys staying inside your network. OpenRouter is a managed service reachable at a single endpoint, offering hundreds of models with no infrastructure to run, at the cost of routing your prompts through a third party and paying a margin above provider pricing.</p>
<p><strong>Should I use LiteLLM or OpenRouter for production?</strong></p>
<p>Both run in production successfully. Choose LiteLLM when data residency, cost at scale, or custom routing logic drive the decision, and you have the team to operate a service. Choose OpenRouter when speed of iteration and model breadth matter more than control, or when nobody can own another piece of infrastructure. Volume is the clearest tiebreaker: heavy sustained traffic favors self hosting, spiky exploratory traffic favors managed.</p>
<p><strong>Does Martian still exist as a standalone LLM router?</strong></p>
<p>No. Martian raised a $9M Series A for model routing, was acquired by Notion, and pivoted to AI interpretability research. It has effectively exited the standalone router market, which is a useful signal that routing is a feature of a gateway rather than a product on its own.</p>
<p><strong>Does adding a gateway slow down my requests?</strong></p>
<p>Not meaningfully. Routing overhead lands around 2 to 20ms per request, which disappears against model response times measured in hundreds of milliseconds. The gateway pays for itself through caching and provider selection, which can reduce inference cost by 40 to 90% on high volume workloads.</p>
<h2>Wrapping up</h2>
<p>The honest summary of LiteLLM vs OpenRouter: they solve the same problem for different teams. Managed wins on time to first request and on breadth. Self hosted wins on data control, unit economics at scale, and how much of the routing logic you can shape.</p>
<p>Whichever you pick, put something between your application and the providers before you need it. The teams that suffer during a provider outage are the ones calling a single vendor SDK directly, with no fallback path and no cache to fall back on. The gateway is the cheap insurance. Which gateway is the smaller question.</p>
]]></content:encoded></item><item><title><![CDATA[Next.js Security Hardening: Middleware, Server Actions, and CSP Patterns That Hold Up]]></title><description><![CDATA[If you searched nextjs security after skimming an advisory and wondering whether your own app is exposed, this guide gives you the four places that…]]></description><link>https://mudassirworks.hashnode.dev/next-js-security-hardening-middleware-server-actions-and-csp-patterns-that-hold-up</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/next-js-security-hardening-middleware-server-actions-and-csp-patterns-that-hold-up</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Security]]></category><category><![CDATA[webdev]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[webdevelopment]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Tue, 11 Aug 2026 20:19:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/d90e202b-5c40-4adf-933c-01a285e98bfe.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you searched nextjs security after skimming an advisory and wondering whether your own app is exposed, this guide gives you the four places that actually break and the code that closes them. You will work through where the framework's real trust boundary sits, the middleware auth bypass class that keeps resurfacing, how to treat server actions as the public endpoints they are, a Content Security Policy setup that survives both dynamic and static rendering, and a patch cadence a small team can hold without heroics.</p>
<p>Everything below is written against the App Router. By the end you will have a hardening checklist you can run against a production deployment in an afternoon, plus a clear sense of which mitigations belong in your code and which belong at the edge.</p>
<h2>The Next.js security model in one minute</h2>
<p>Here is the definition to anchor everything else. Next.js security is the practice of enforcing authorization at the data access boundary rather than the routing boundary, because in a hybrid server and client framework the routing layer is reachable by attackers in ways your mental model does not predict.</p>
<p>That sentence carries the whole article. In a traditional server rendered app, a request hits one server, that server runs your auth check, and nothing downstream executes until the check passes. Next.js splits execution across at least four surfaces: the edge middleware runtime, the server component render pass, server action invocations, and route handlers. Each one is separately reachable. A request can arrive at a server action without ever passing through the page that renders the button which calls it.</p>
<p>So the model to hold in your head is simple. Every server side entry point is public until proven otherwise, and the only place an authorization check is trustworthy is immediately next to the data it protects.</p>
<h2>Why middleware only auth keeps failing: the bypass class</h2>
<p>Nextjs middleware security has produced the framework's most quoted vulnerability, and the shape of it is worth understanding because the same shape keeps reappearing under different names.</p>
<p>Next.js uses an internal request header called <code>x-middleware-subrequest</code> to stop middleware from recursing into itself when it triggers an internal subrequest. That header was trusted. An attacker who set it on an inbound request could convince the runtime that middleware had already run, and the middleware chain was skipped entirely. Any authorization living in <code>middleware.ts</code> was skipped with it. The advisory carried a CVSS score of 9.1, and patches shipped in 12.3.5, 13.5.9, 14.2.25, and 15.2.3.</p>
<p>Patched versions close that specific header trick. They do not fix the architecture that made it catastrophic. Here is the pattern that turns a routing bug into an auth bypass:</p>
<pre><code class="language-ts">// middleware.ts — the fragile pattern
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const session = req.cookies.get("session")?.value;
  if (!session) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ["/dashboard/:path*", "/api/admin/:path*"] };
</code></pre>
<p>Read that carefully. If middleware never executes, <code>/api/admin/delete-tenant</code> is an unauthenticated endpoint. There is no second gate. The redirect was the only thing standing between an anonymous request and your admin surface.</p>
<p>The fix is not a better middleware check. The fix is to demote middleware to what it is good at, which is cheap optimistic routing, and move the real check into a data access layer that every reader must go through:</p>
<pre><code class="language-ts">// lib/dal.ts — authorization next to the data
import { cache } from "react";
import { cookies } from "next/headers";
import { db } from "@/lib/db";

export const requireUser = cache(async () =&gt; {
  const token = (await cookies()).get("session")?.value;
  const user = token ? await db.session.resolve(token) : null;
  if (!user) throw new Error("UNAUTHENTICATED");
  return user;
});

export async function getTenantInvoices(tenantId: string) {
  const user = await requireUser();
  if (user.tenantId !== tenantId) throw new Error("FORBIDDEN");
  return db.invoice.findMany({ where: { tenantId } });
}
</code></pre>
<p>Now a skipped middleware pass costs you a wrong redirect, not a data breach. <code>getTenantInvoices</code> cannot be reached without <code>requireUser</code> running first, whatever routing games happen upstream. The <code>cache</code> wrapper means the session resolves once per request even when a dozen components call it.</p>
<p>One more habit worth building. Middleware should never be the only thing enforcing tenant isolation, because tenant isolation is an ownership question and middleware does not know which row you are about to read.</p>
<h2>Server actions are public endpoints: locking them down</h2>
<p>Nextjs api security discussions usually stop at route handlers, which leaves the larger surface untouched. Every server action compiles to an addressable POST endpoint with a stable identifier. Anyone who reads your client bundle can call it directly with a crafted body. The form component that normally invokes it is decoration, not a gate.</p>
<p>This has real consequences. One advisory rated CVSS 7.5 described crafted requests to App Router server function endpoints driving CPU usage up sharply, a denial of service reachable by anyone who could send a POST. It was fixed in 15.5.15 and 16.2.3, with WAF mitigations deployed at the platform edge while the patch rolled out. Separately, an upstream React Server Components denial of service was resolved through React 19.0.6, 19.1.7, and 19.2.6, which is a useful reminder that your React version is part of your attack surface, not just a peer dependency.</p>
<p>Treat every action like a public API handler. That means three things in order: authenticate, authorize the specific object, then validate the input shape before it touches anything.</p>
<pre><code class="language-ts">"use server";

import { z } from "zod";
import { requireUser } from "@/lib/dal";
import { db } from "@/lib/db";

const UpdateInvoice = z.object({
  invoiceId: z.string().uuid(),
  amountCents: z.number().int().min(0).max(50_000_00),
  note: z.string().max(500).optional(),
});

export async function updateInvoice(formData: FormData) {
  const user = await requireUser();

  const parsed = UpdateInvoice.safeParse({
    invoiceId: formData.get("invoiceId"),
    amountCents: Number(formData.get("amountCents")),
    note: formData.get("note") ?? undefined,
  });
  if (!parsed.success) return { error: "INVALID_INPUT" };

  const invoice = await db.invoice.findUnique({
    where: { id: parsed.data.invoiceId },
    select: { tenantId: true },
  });
  if (!invoice || invoice.tenantId !== user.tenantId) return { error: "FORBIDDEN" };

  await db.invoice.update({
    where: { id: parsed.data.invoiceId },
    data: { amountCents: parsed.data.amountCents, note: parsed.data.note },
  });
  return { ok: true };
}
</code></pre>
<p>Notice the ownership lookup happens before the write and uses a <code>select</code> that pulls only the field needed for the decision. Notice too that the error strings are opaque. Leaking "invoice not found" versus "not your invoice" hands an attacker a free enumeration oracle across your tenant boundary.</p>
<p>For nextjs secure api routes the same three steps apply, with one addition. Route handlers are the right home for anything that needs a non default runtime, custom rate limiting, or an idempotency key, because you control the full request and response cycle there:</p>
<pre><code class="language-ts">// app/api/webhooks/billing/route.ts
import { NextResponse } from "next/server";
import { verifySignature } from "@/lib/webhook";

export const runtime = "nodejs";

export async function POST(req: Request) {
  const raw = await req.text();
  const signature = req.headers.get("x-billing-signature");
  if (!signature || !verifySignature(raw, signature)) {
    return NextResponse.json({ error: "bad signature" }, { status: 401 });
  }
  return NextResponse.json({ received: true });
}
</code></pre>
<p>Read the raw body before parsing it. Signature verification over a re serialized JSON object is a check that passes for the wrong reasons.</p>
<h2>Content Security Policy in Next.js: nonces vs hashes</h2>
<p>Content security policy nextjs setups fail for a reason that is architectural rather than syntactic, so it helps to know the constraint before writing the header.</p>
<p>A nonce is a random value generated per request, attached to every inline script you trust, and echoed in the policy header. Because it is per request, it requires dynamic rendering. A statically generated page is rendered once at build time and served from cache to everyone, so there is no per request moment in which to mint a nonce. The documented alternative for static output is hash based subresource integrity, which is experimental and App Router only.</p>
<p>That gives you a clean decision rule. Dynamic routes get nonces. Static routes get hashes or a policy with no inline script allowance at all.</p>
<p>Here is the nonce path, generated in middleware and consumed in the layout:</p>
<pre><code class="language-ts">// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
  const csp = [
    `default-src 'self'`,
    `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,
    `style-src 'self' 'unsafe-inline'`,
    `img-src 'self' blob: data:`,
    `frame-ancestors 'none'`,
    `base-uri 'self'`,
    `form-action 'self'`,
  ].join("; ");

  const headers = new Headers(req.headers);
  headers.set("x-nonce", nonce);
  headers.set("content-security-policy", csp);

  const res = NextResponse.next({ request: { headers } });
  res.headers.set("content-security-policy", csp);
  return res;
}
</code></pre>
<pre><code class="language-tsx">// app/layout.tsx
import { headers } from "next/headers";
import Script from "next/script";

export default async function RootLayout({ children }: { children: React.ReactNode }) {
  const nonce = (await headers()).get("x-nonce") ?? undefined;
  return (
    &lt;html lang="en"&gt;
      &lt;body&gt;
        {children}
        &lt;Script src="/analytics.js" nonce={nonce} strategy="afterInteractive" /&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  );
}
</code></pre>
<p>Two details decide whether this holds. <code>frame-ancestors 'none'</code> is the modern clickjacking control and it belongs in the policy rather than in a legacy frame options header. And <code>strict-dynamic</code> is what lets a nonced loader script pull in the chunks the framework injects, without you maintaining an allowlist of hostnames that rots the moment a vendor changes their CDN.</p>
<p>A nonce implementation that goes wrong is also a documented risk rather than a theoretical one. A CSP nonce cross site scripting issue was among the advisories in the coordinated release described in the next section, which is a good argument for keeping the policy small enough that you can audit it in one screen.</p>
<h2>A patch cadence that actually works for SaaS teams</h2>
<p>The framework now ships coordinated security releases, where several advisories land together on a single announced date. One such release covered 13 advisories in one batch, spanning middleware and proxy bypasses, server side request forgery through a WebSocket upgrade path, cache poisoning, and the CSP nonce cross site scripting issue mentioned above. The fixed versions were 15.5.18 and 16.2.6.</p>
<p>Thirteen at once tells you something useful about how to plan. Patching is not a steady drip you can absorb inside normal sprint noise. It arrives in bursts, and the bursts are public, which means the exploitation window opens the moment the changelog does.</p>
<p>A cadence that survives contact with a real roadmap looks like this:</p>
<ul>
<li><p>Pin exact versions in <code>package.json</code>, never a caret range on the framework itself. You want upgrades to be a decision with a diff, not an accident of a lockfile refresh.</p>
</li>
<li><p>Subscribe the on call rotation to the framework and React advisory feeds, not a personal inbox. Advisories that land while one person is away are the ones that sit.</p>
</li>
<li><p>Keep a staging deploy that mirrors production runtime and rendering modes. Most upgrade breakage in this framework shows up in the difference between static and dynamic paths, which a local dev server will not reproduce.</p>
</li>
<li><p>Budget a fixed slot, roughly half a day every two weeks, for dependency work. Teams that treat patching as interrupt driven work always lose to teams that treat it as scheduled work.</p>
</li>
<li><p>Know your edge controls. WAF rules bought real time during at least one recent advisory, so knowing how to ship a request filter in minutes is a genuine mitigation while the version bump goes through review.</p>
</li>
</ul>
<p>The pinning point deserves emphasis. Reading a patch note that says a fix landed in 15.5.15 is useless if nobody can state which version production is running right now.</p>
<h2>Hardening checklist</h2>
<p>Run this nextjs security checklist against a live deployment. Each line is a yes or no you can verify, not an aspiration.</p>
<ul>
<li><p>Authorization is enforced in a data access layer, and no protected query is reachable without it.</p>
</li>
<li><p>Middleware performs optimistic routing only, and removing it entirely would leak no data.</p>
</li>
<li><p>Every server action authenticates, checks object ownership, and validates input with a schema, in that order.</p>
</li>
<li><p>Error strings returned to clients are opaque and identical for "missing" and "forbidden".</p>
</li>
<li><p>Route handlers verify webhook signatures against the raw body before parsing.</p>
</li>
<li><p>A Content Security Policy is set, with <code>frame-ancestors 'none'</code>, <code>base-uri 'self'</code>, and <code>form-action 'self'</code>.</p>
</li>
<li><p>Dynamic routes use per request nonces; static routes use hashes or ship no inline script.</p>
</li>
<li><p>Framework and React versions are pinned exactly and recorded somewhere a responder can read at speed.</p>
</li>
<li><p>Advisory feeds route to a rotation, and a patch slot exists on the calendar.</p>
</li>
<li><p>Rate limiting covers server actions, not only route handlers.</p>
</li>
<li><p>Secrets are read through server only modules, so a stray client import fails the build instead of shipping.</p>
</li>
</ul>
<p>If you can only do three, do the data access layer, the server action validation, and the version pinning. Those three remove most of the blast radius from the bug classes above.</p>
<h2>FAQ</h2>
<p><strong>Are nextjs routes secure?</strong></p>
<p>Routes are not a security boundary at all, so the question is slightly the wrong shape. Route segments control rendering and navigation. They do not authenticate anyone. A route is secure when every data read inside it passes through an authorization check that runs regardless of how the request arrived. Rely on the URL structure alone and you are one routing bug away from an exposed endpoint, which is exactly what the CVSS 9.1 middleware bypass demonstrated.</p>
<p><strong>Are nextjs server actions secure?</strong></p>
<p>They are as secure as the checks you write inside them, and no more. An action is a public POST endpoint with a stable identifier that anyone can call directly from outside your UI. The framework gives you protections around the transport, including origin checks and encrypted closure values, but it cannot know whether the current user owns the record being edited. Authenticate, check ownership, validate the input, and rate limit. An action without those four is an unauthenticated API you did not realise you shipped.</p>
<p><strong>Does a Content Security Policy work with static pages?</strong></p>
<p>Yes, with a caveat. The policy header itself is fine on any page. Per request nonces are the part that needs dynamic rendering, since a cached static response cannot carry a fresh random value. For static output, use the experimental hash based approach on the App Router or Write a policy that permits no inline script.</p>
<p><strong>How quickly do these patches need to ship?</strong></p>
<p>Treat any authorization bypass as same week, and anything rated above 9.0 as same day. Coordinated releases are announced publicly with fixed versions listed, so the details reach attackers and defenders at the same moment. Your advantage is knowing your current version before the announcement lands, not after.</p>
]]></content:encoded></item><item><title><![CDATA[LLM OCR for RAG: A Document Parsing Pipeline Guide That Protects Retrieval Quality]]></title><description><![CDATA[LLM OCR for RAG: A Document Parsing Pipeline Guide That Protects Retrieval Quality]]></description><link>https://mudassirworks.hashnode.dev/llm-ocr-for-rag-a-document-parsing-pipeline-guide-that-protects-retrieval-quality</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/llm-ocr-for-rag-a-document-parsing-pipeline-guide-that-protects-retrieval-quality</guid><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Sat, 08 Aug 2026 19:53:22 GMT</pubDate><content:encoded><![CDATA[<p>If you searched ocr llm because your retrieval augmented generation system keeps returning garbled answers from scanned PDFs, the problem almost never starts at the language model. It starts at the parsing step, weeks before any embedding gets created. This guide walks through how document parsing quality caps everything downstream, compares the current landscape of hosted OCR APIs against open source parsers, explains the two benchmarks people actually cite, breaks down real cost per thousand pages, and ends with a decision tree you can apply today.</p>
<p>By the end you will know which parser fits your document mix, what it costs at your volume, and how to structure the output so your chunking step does not throw away the layout information you just paid for.</p>
<h2>Why document parsing quality caps RAG quality</h2>
<p>Here is the definition to start with. Document parsing for RAG is the process of turning a PDF, scanned image, or photographed page into structured text your chunker and embedding model can actually use, while preserving enough layout information (tables, headings, reading order) that the meaning survives the trip.</p>
<p>Most teams treat this step as a throwaway utility function. That is the mistake. If your parser flattens a two column PDF into one long string that interleaves both columns, no amount of clever prompting fixes the answer your model gives later. If a table gets dumped as unstructured text with no cell boundaries, your embedding model has no way to represent which number belongs to which row. Retrieval quality is a ceiling set at parse time, and the LLM only ever gets to work with what survives that ceiling.</p>
<p>This is why llm ocr has become its own decision point rather than an afterthought bundled into "just use whatever library reads PDFs." The parser you pick determines whether your chunks contain clean markdown with intact tables and headings, or noisy text soup with confidence scores you cannot even inspect.</p>
<h2>The current landscape: hosted OCR APIs vs open source parsers</h2>
<p>There are two broad camps, and the right one depends on your volume, your compliance requirements, and how much engineering time you want to spend on infrastructure.</p>
<p>Hosted APIs like Mistral's OCR model, AWS Textract, and Azure Document Intelligence are pay per page, require no GPU management, and typically ship layout aware output out of the box. Mistral's current generation OCR model, for example, adds bounding boxes, typed block classification, and per word confidence scores, and supports 170 languages with a self contained container deployment option for teams that need the model on their own infrastructure while keeping the same API shape. That combination of bounding boxes plus confidence scores is exactly what you want feeding into a chunker, because you can filter out low confidence regions before they pollute an embedding.</p>
<p>Open source parsers, on the other hand, run on hardware you control. If a local llm ocr setup is the goal because of data residency rules or because you are processing millions of pages and the hosted pricing does not scale, models like olmOCR 2 from Allen AI are built for exactly that. These give you full control over batching, GPU allocation, and output format, at the cost of owning the operational burden yourself.</p>
<p>So which is the best ocr llm choice for your project? If you are processing under a few hundred thousand pages a month and want layout analysis without standing up infrastructure, start hosted. If you are past that volume, need air gapped deployment, or want to fine tune on your own document distribution, open source earns its complexity.</p>
<h2>Benchmarks that matter: olmOCR Bench and OmniDocBench explained</h2>
<p>Two benchmarks keep coming up in vendor comparisons, and they are testing different things.</p>
<p>OmniDocBench focuses on layout heavy documents (dense tables, multi column academic papers, mixed script pages) and scores how well a parser preserves structure, not just raw text accuracy. olmOCR Bench, built by Allen AI, is a broader test suite of unit tests run across a large sample of real PDFs, checking things like whether table cells align correctly and whether reading order survives multi column layouts.</p>
<p>The numbers are worth knowing because vendor marketing and independent leaderboards do not always agree. Mistral's OCR model reports 85.20 on olmOCR Bench and 93.07 on OmniDocBench in its own benchmarks, but on the independent olmOCR Bench leaderboard it ranks third, behind open models including Chandra OCR 2. olmOCR 2 itself scores 82.4 on olmOCR Bench, a result built from 7,010 unit tests run across 1,403 real PDFs, which is a large enough sample the number is hard to argue with.</p>
<p>The practical takeaway: treat vendor reported scores as a starting point, not a final answer, and if table extraction quality matters more to your use case than raw text accuracy, weight OmniDocBench results higher than a general leaderboard rank.</p>
<h2>Cost per thousand pages compared</h2>
<p>This is where the decision usually gets made in practice, because the accuracy difference between top tier parsers is often smaller than the price difference.</p>
<table>
<thead>
<tr>
<th>Parser</th>
<th>Cost per 1,000 pages</th>
<th>Notes</th>
</tr>
</thead>
<tbody><tr>
<td>Mistral OCR (standard)</td>
<td>4 dollars</td>
<td>2 dollars on batch processing</td>
</tr>
<tr>
<td>Mistral OCR (Document AI mode)</td>
<td>5 dollars</td>
<td>Adds structured extraction</td>
</tr>
<tr>
<td>AWSTextract (basic OCR)</td>
<td>about 1.50 dollars</td>
<td>Cheapest hosted option for plain text</td>
</tr>
<tr>
<td>AWS Textract (AnalyzeDocument, Forms)</td>
<td>50 dollars</td>
<td>Table and form extraction, much pricier</td>
</tr>
<tr>
<td>Azure Document Intelligence (Read tier)</td>
<td>1.50 dollars, dropping to about 0.53 dollars at commitment tier</td>
<td>Cheapest at scale with a volume commitment</td>
</tr>
<tr>
<td>olmOCR 2 (self hosted)</td>
<td>roughly 178 dollars per million pages</td>
<td>About 0.178 dollars per 1,000 pages once infrastructure is running</td>
</tr>
</tbody></table>
<p>A few things jump out once you line these up. Plain OCR without layout extraction is cheap almost everywhere, under 2 dollars per thousand pages across every hosted vendor. The price jumps hard the moment you need table and form structure, AWS Textract's AnalyzeDocument tier is more than 30 times the cost of its basic OCR tier for that reason. And once you clear the infrastructure hurdle, self hosted open source options like olmOCR 2 undercut every hosted vendor by a wide margin at real volume, which is exactly why teams processing millions of pages a month eventually migrate off pay per call APIs.</p>
<h2>Structuring parser output for chunking and retrieval</h2>
<p>Getting good OCR output and then chunking it badly wastes everything you just paid for. This is the step most document parsing for RAG guides skip, and it is where a lot of retrieval quality quietly disappears.</p>
<p>The naive approach treats parser output as one long string and chunks it by character count:</p>
<pre><code class="language-python">def naive_chunk(ocr_text, chunk_size=1000):
    # loses all table structure and heading boundaries
    return [ocr_text[i:i + chunk_size] for i in range(0, len(ocr_text), chunk_size)]
</code></pre>
<p>This throws away the bounding boxes, headings, and table cell boundaries the parser worked hard to produce. A table that spans two chunk boundaries becomes two useless fragments, neither of which makes sense on its own.</p>
<p>A structure aware approach instead converts the parser's layout output into markdown first, chunking along heading and table boundaries rather than raw character counts:</p>
<pre><code class="language-python">def structured_chunk(parsed_blocks, min_confidence=0.7):
    chunks = []
    current = []
    for block in parsed_blocks:
        # drop low confidence regions before they pollute an embedding
        if block.confidence &lt; min_confidence:
            continue
        if block.type == "heading":
            if current:
                chunks.append("\n".join(current))
            current = [f"## {block.text}"]
        elif block.type == "table":
            # keep whole tables intact, never split mid table
            chunks.append("\n".join(current) + "\n" + block.to_markdown())
            current = []
        else:
            current.append(block.text)
    if current:
        chunks.append("\n".join(current))
    return chunks
</code></pre>
<p>Notice the confidence score check. Any decent llm ocr pipeline attaches a confidence value to each detected block, and filtering below a threshold before chunking is one of the cheapest wins available. A blurry scanned signature or a smudged page number does not need to end up embedded next to your actual content.</p>
<h2>A decision tree for picking your parser</h2>
<p>Use this as a starting checklist rather than a rigid rule:</p>
<ol>
<li><p><strong>Under 50,000 pages a month, mixed document types, no compliance restrictions.</strong> Start with a hosted API's basic OCR tier. You do not need layout extraction pricing yet.</p>
</li>
<li><p><strong>Tables and forms matter for your use case.</strong> Pay for the structured extraction tier (Document AI mode, AnalyzeDocument with Forms) rather than trying to reconstruct table structure from plain OCR text yourself. The accuracy difference is large enough to justify the cost jump.</p>
</li>
<li><p><strong>Data residency or air gapped requirements.</strong> Go open source from day one. A hosted API is not an option regardless of cost, so evaluate olmOCR 2 and similar models on your actual document sample before committing.</p>
</li>
<li><p><strong>Over a few hundred thousand pages a month.</strong> Run the math on self hosted infrastructure cost against your current hosted bill. This is usually where the best llm model for ocr stops being about accuracy and starts being about unit economics.</p>
</li>
<li><p><strong>Whatever you pick, structure the output before you chunk.</strong> Bounding boxes and confidence scores are wasted if your chunker throws them away in step two.</p>
</li>
</ol>
<p>None of these choices are permanent. Parsing pipelines are cheap to swap compared to the cost of re embedding a corpus, so start with whatever gets you shipping and revisit once you have real volume and real failure cases to learn from.</p>
<h2>FAQ</h2>
<p><strong>What is OCR in LLM?</strong></p>
<p>OCR in the context of an LLM pipeline means using optical character recognition, often now paired with a vision capable model, to turn scanned or image based documents into text and structured layout data (headings, tables, bounding boxes) that a retrieval system or language model can process. Modern OCR for LLM use cases goes beyond plain text extraction; it typically outputs markdown or structured blocks with confidence scores attached, specifically so the output plugs cleanly into a RAG chunking pipeline.</p>
]]></content:encoded></item><item><title><![CDATA[Agentic Search vs Traditional RAG: When One Query Is Not Enough]]></title><description><![CDATA[Agentic search is retrieval where an LLM plans the search instead of firing one embedding lookup. It decomposes a complex question into focused subqueries…]]></description><link>https://mudassirworks.hashnode.dev/agentic-search-vs-traditional-rag-when-one-query-is-not-enough</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/agentic-search-vs-traditional-rag-when-one-query-is-not-enough</guid><category><![CDATA[AI]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[webdev]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Fri, 07 Aug 2026 19:35:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/7cf6b4ef-973d-49cc-896f-32c0a436492e.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Agentic search is retrieval where an LLM plans the search instead of firing one embedding lookup. It decomposes a complex question into focused subqueries, runs them in parallel against your knowledge sources, reranks the results, and synthesizes everything into one grounded response instead of stuffing raw chunks into a prompt.</p>
<p>By the end of this guide you will know exactly where traditional single query retrieval breaks, how the agentic retrieval loop works step by step, what Azure and Elastic actually ship today, what it costs versus classic RAG, and when you genuinely do not need any of this.</p>
<h2>How traditional single query retrieval works and where it fails</h2>
<p>Classic RAG is simple on purpose. You embed the user's question, run a nearest neighbor search against your vector index, grab the top k chunks, and hand them to the LLM as context. For a factual lookup like "what is our refund window," that pipeline is fast, cheap, and accurate enough that adding anything more is wasted engineering effort.</p>
<p>The failure mode shows up the moment a question needs more than one fact pulled from more than one place. Ask "how does our refund policy differ from our warranty policy for international orders" and a single embedding vector has to somehow represent three separate concepts at once. The nearest neighbor search returns chunks that are each partially relevant and none of them fully answer the question, so the LLM ends up guessing at the gaps or quietly dropping part of the question. Multi hop questions, comparisons, and anything requiring the model to first figure out what to look up before it knows what to search for are exactly where classic retrieval falls over.</p>
<h2>The agentic retrieval loop: query decomposition, parallel subqueries, reranking, synthesis</h2>
<p>Agentic retrieval fixes this by giving the LLM a planning step before the search step. According to Microsoft's own documentation, Azure AI Search's agentic retrieval is a multi query pipeline where an LLM decomposes a complex query into focused subqueries, runs them in parallel, semantically reranks the combined results, and synthesizes everything into one grounded response.</p>
<p>Walk through what that looks like in practice. The model reads the user's question plus recent chat history context, and instead of embedding the raw question, it drafts a small set of narrower subqueries, each aimed at one piece of the original ask. Those subqueries hit your knowledge sources in parallel rather than one after another, which keeps latency from stacking up linearly. The combined candidate set then goes through a semantic reranker that scores relevance against the original question rather than the individual subqueries, so results that are technically on topic but do not actually help the user get pushed down. Only after reranking does the LLM synthesize a single grounded response, citing which subquery pulled which fact.</p>
<p>This is why agentic retrieval and agentic RAG show real gains on comparison and multi part questions specifically. You are not making retrieval smarter in the abstract, you are giving the system a chance to ask better questions before it starts searching.</p>
<h2>What the vendors ship: Azure agentic retrieval and Elastic hybrid patterns</h2>
<p>Microsoft reports its agentic retrieval engine delivers up to 40 percent better relevance for complex queries compared with classic single query RAG. That is a meaningful jump for exactly the multi hop and comparison cases described above, and it lines up with the mechanism: reranking a broader, better targeted candidate set naturally beats reranking chunks pulled from one imprecise vector lookup.</p>
<p>On the platform side, the underlying REST API for Azure's agentic retrieval has already reached general availability, while portal level support for configuring it visually is still in preview. If you are evaluating this today, expect to configure the pipeline through the API rather than clicking through a console.</p>
<p>Elastic takes a different but related path with hybrid search, combining BM25 keyword scoring with vector search rather than routing everything through an LLM planner first. An independent benchmark of Elasticsearch's agentic hybrid search setup, not an official Elastic published number, reported 21 percent higher relevance than BM25 alone and 12 percent higher than vector search alone, roughly 0.87 versus 0.72 for BM25 only and 0.87 versus 0.78 for vector only on their test set. The takeaway is not that one vendor wins. It is that both hybrid search and full agentic retrieval outperform a single retrieval strategy run in isolation, and the gap grows with query complexity.</p>
<h2>Cost model: per query vs per token retrieval</h2>
<p>This is the tradeoff that gets skipped in most comparisons and it matters more than the relevance numbers. Classic Azure AI Search bills per query. Agentic retrieval bills per token, and it consumes tokens on both sides, the retrieval calls themselves plus the LLM planning and synthesis work that wraps around them.</p>
<p>Concretely, if a single user question turns into three or four subqueries plus a synthesis pass, you are paying for the equivalent of several LLM calls where classic RAG cost you one embedding lookup. For a support bot answering thousands of straightforward questions a day, that multiplier adds up fast. For a research assistant answering a few dozen genuinely hard, multi source questions a day, the token bill is a rounding error next to the cost of a wrong answer.</p>
<p>Before you flip this on for a whole product, run the numbers on your actual query mix. Pull a sample of real user questions, tag which ones are single fact lookups versus genuinely multi part, and price out agentic retrieval against just that harder subset rather than your whole traffic.</p>
<h2>When you do not need agentic search</h2>
<p>Skip agentic retrieval, at least for now, if most of your traffic looks like single fact lookups where a good embedding model and a solid reranker already get you a correct answer most of the time. It also is not worth the added latency and token billing if your corpus is small enough that a single query can realistically surface everything relevant, or if your team cannot yet monitor and debug a multi step retrieval pipeline when it produces a wrong subquery decomposition.</p>
<p>Agentic search earns its cost on genuinely compound questions: comparisons across documents, "how does X relate to Y" queries, and anything where the user is really asking two or three questions wrapped in one sentence. If you are not seeing that pattern in your logs yet, classic retrieval with a good reranker will outperform an agentic pipeline on cost and simplicity while you wait for the harder queries to show up.</p>
<h2>FAQ</h2>
<p><strong>What is agentic search?</strong></p>
<p>Agentic search is a retrieval approach where an LLM plans the search itself. It decomposes a complex query into smaller subqueries, retrieves for each one in parallel, semantically reranks the combined candidates, and synthesizes one grounded response from your knowledge sources instead of returning raw chunks tied to a single embedding lookup.</p>
<p><strong>Is agentic search the same as agentic RAG?</strong></p>
<p>They describe the same underlying pattern from two angles. Agentic retrieval is the search mechanism itself, the decomposition and reranking loop. Agentic RAG is the broader system that wraps that retrieval loop with generation, chat history context, and citation of sources in the final answer.</p>
<p><strong>Does agentic retrieval replace reranking?</strong></p>
<p>No, it depends on it. The semantic reranker is what scores the combined subquery results against the original question so the synthesis step works from a clean candidate set rather than a noisy one pulled from several parallel searches.</p>
]]></content:encoded></item><item><title><![CDATA[Structuring Next.js AI Apps for Scale: Architecture Patterns That Hold Under Production Load]]></title><description><![CDATA[By the end of this article, you will have a working mental model for nextjs ai app architecture: where LLM calls belong in the App Router, how to keep…]]></description><link>https://mudassirworks.hashnode.dev/structuring-next-js-ai-apps-for-scale-architecture-patterns-that-hold-under-production-load</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/structuring-next-js-ai-apps-for-scale-architecture-patterns-that-hold-under-production-load</guid><category><![CDATA[Next.js]]></category><category><![CDATA[AI]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[React]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Mon, 03 Aug 2026 19:17:55 GMT</pubDate><content:encoded><![CDATA[<p>By the end of this article, you will have a working mental model for nextjs ai app architecture: where LLM calls belong in the App Router, how to keep streaming responses fast without fighting React, and how to structure a service layer so your framework code never talks to a model provider directly. These are nextjs llm integration patterns pulled from apps that are already carrying real production traffic, not a toy demo.</p>
<h2>Why standard Next.js patterns break under AI load</h2>
<p>Most Next.js patterns were shaped around requests that finish in well under a second. You fetch a row from a database, render it, done. An LLM call does not behave that way. It can take several seconds to complete, it often needs to stream partial output back to the reader instead of returning everything at once, and its cost scales with every token you send and receive rather than with a fixed query.</p>
<p>Treat an AI call like any other short fetch and you get a page that appears frozen while the model thinks, a serverless function that times out mid generation, or a client side spinner that has no idea whether the request is still alive. None of that is a Next.js bug. It is a mismatch between a request response mental model and a workload that is closer to a long running stream.</p>
<p>The fix is not a new framework. It is choosing the right primitive for each part of the flow: a route handler when you need a raw streaming HTTP surface, a server action when you need a simple mutation triggered from a form, and a dedicated service layer that owns every call to a model provider so the rest of your app never has to think about retries, timeouts, or prompt construction again.</p>
<h2>Route handler vs server action for LLM calls: the decision matrix</h2>
<p>The two ways to call an LLM from Next.js look similar on the surface but solve different problems, and picking the wrong one is where most nextjs ai app architecture goes wrong early.</p>
<p>Reach for a route handler under <code>app/api/*/route.ts</code> when any of the following is true: you need to stream the response back token by token, the call originates from a client component using <code>fetch</code>, you need custom response headers or status codes (returning a 429 when you are rate limited, for example), or the endpoint needs to be callable from outside your own app, such as a webhook or a public API surface.</p>
<pre><code class="language-typescript">// app/api/chat/route.ts
import { NextRequest } from "next/server";
import { streamModelResponse } from "@/lib/ai/service-layer";

export const runtime = "nodejs";

export async function POST(req: NextRequest) {
  const { prompt } = await req.json();

  const stream = await streamModelResponse(prompt);

  return new Response(stream, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
    },
  });
}
</code></pre>
<p>Reach for a server action instead when the call is a straightforward mutation triggered by a form submission inside a Server Component tree, and you do not need a separate HTTP surface at all. A server action for, say, "summarize this uploaded document and save the result" does not need its own route, its own client side fetch wiring, or its own CORS story. It is just a function the form calls directly.</p>
<pre><code class="language-typescript">// app/actions/summarize.ts
"use server";

import { runSummary } from "@/lib/ai/service-layer";

export async function summarizeDocument(formData: FormData) {
  const text = formData.get("text") as string;
  const summary = await runSummary(text);
  return { summary };
}
</code></pre>
<p>One detail that trips people up here: pushing the <code>use client</code> directive down to only the leaf level interactive components, and keeping layouts and page shells as Server Components, is current production best practice for React Server Components. That rule applies just as much to your AI UI. Do not mark an entire chat page <code>use client</code> because one button needs interactivity. Isolate the interactive leaf, keep the shell on the server, and both your route handlers and your server actions stay easy to reason about.</p>
<h2>Streaming architecture with Suspense and React Flight</h2>
<p>Streaming is where nextjs ai streaming production setups either feel instant or feel broken, and the difference usually comes down to how many things you are awaiting in a single component.</p>
<p>Splitting async data fetching into sibling Server Components, rather than one large component that awaits everything, lets Next.js run those fetches in parallel and stream each piece in as it resolves. That is the official guidance behind the streaming model, and it applies directly to AI responses: wrap the part of the page that depends on a model call in its own Suspense boundary, and let everything else on the page render immediately.</p>
<pre><code class="language-tsx">// app/chat/page.tsx
import { Suspense } from "react";
import { AiAnswer } from "./ai-answer";
import { PageHeader } from "./page-header";

export default function ChatPage({ searchParams }: { searchParams: { q: string } }) {
  return (
    &lt;main&gt;
      &lt;PageHeader /&gt;
      &lt;Suspense fallback={&lt;p&gt;Thinking...&lt;/p&gt;}&gt;
        {/* AiAnswer is an async Server Component that awaits the model call */}
        &lt;AiAnswer query={searchParams.q} /&gt;
      &lt;/Suspense&gt;
    &lt;/main&gt;
  );
}
</code></pre>
<p><code>AiAnswer</code> itself is an async Server Component that calls into your service layer and awaits the model response. Because it sits behind its own Suspense boundary, React Flight can send the shell of the page to the browser first and stream the AI generated content in once it is ready, instead of blocking the whole page on one slow call. If you have multiple AI powered sections on a page, give each one its own boundary rather than one shared wrapper. A single shared boundary means the fastest section still waits for the slowest one.</p>
<h2>State management for async AI responses at scale</h2>
<p>Global client side state managers were built for state that changes in discrete, synchronous steps: a value updates, every subscriber re renders. A streaming AI response does not fit that shape. It is a sequence of partial chunks arriving over time, and funneling every chunk through a global store adds a layer of indirection that fights the streaming model instead of supporting it.</p>
<p>The pattern that holds up is to keep state as close to the Server Component tree as the framework allows, and reserve client side, optimistic state for the leaf components that actually need to react to a keystroke or a click while the server does the real work. A chat input that needs to show a message the instant the user hits send is a good candidate for local optimistic state. The eventual model output streaming back in is not something a global store needs to own; the component reading the stream can hold that state itself.</p>
<p>This also keeps your service layer boundary honest. If model output has to travel through global state before it reaches the UI, it becomes very easy for some other part of the app to reach into that store and start depending on the shape of a specific provider's response. Keep the stream close to where it is consumed and that coupling never gets a chance to form.</p>
<h2>The AI service layer: separating concerns from your Next.js app</h2>
<p>The single most useful architectural decision in a Next.js AI app is extracting every call to a model provider, every retry policy, and every piece of prompt construction into one dedicated service layer module that both route handlers and server actions call into. Neither the framework layer nor your UI components should ever import a model provider's SDK directly.</p>
<pre><code class="language-typescript">// lib/ai/service-layer.ts
import { createProviderClient } from "./provider-client";

const client = createProviderClient();

export async function streamModelResponse(prompt: string) {
  return client.stream({
    prompt,
    maxRetries: 2,
    timeoutMs: 30000,
  });
}

export async function runSummary(text: string) {
  const result = await client.complete({
    prompt: buildSummaryPrompt(text),
    maxRetries: 2,
  });
  return result.output;
}

function buildSummaryPrompt(text: string) {
  return `Summarize the following text in three sentences.\n\n${text}`;
}
</code></pre>
<p>This is not just tidiness. When a provider changes its API shape, or you decide to route certain prompts to a different model, you change one file. Your route handlers and server actions keep calling <code>streamModelResponse</code> and <code>runSummary</code> exactly as before. It also gives you one place to enforce timeouts and retry limits consistently, instead of every call site reinventing its own error handling.</p>
<p>Treat this service layer the same way you would treat a payments module: narrow surface, one owner, everything else in the app depends on it rather than on the provider directly.</p>
<h2>Deployment and edge considerations for AI heavy apps</h2>
<p>Nextjs ai deployment edge decisions come down to one tradeoff: the edge runtime gives you fast cold starts and global distribution, but it enforces a much tighter execution time limit than the Node runtime, and a long running streaming completion can bump into that ceiling.</p>
<p>For short, bounded calls, the edge runtime is a reasonable default. For anything that streams a longer generation, or that calls out to a provider whose latency you do not fully control, keep the route on the Node runtime, where execution time limits are far more forgiving and you have full access to the Node standard library for things like connection pooling. Setting <code>export const runtime = "nodejs"</code> at the top of a route handler, as shown earlier, is the explicit way to opt out of the edge runtime for a specific endpoint.</p>
<p>A practical rule that has held up: if a route's response time is bounded and predictable, let it run at the edge and get the latency win. If a route depends on a model provider's generation time, which can vary a lot request to request, keep it off the edge runtime entirely so a slow completion does not turn into a hard timeout for the user.</p>
<h2>FAQ</h2>
<h3>How do I structure a Next.js AI app?</h3>
<p>Separate concerns into three layers: a service layer that owns all calls to your model provider, route handlers or server actions that expose that service layer to the rest of the app, and Server Components that render the result behind a Suspense boundary. Keep <code>use client</code> limited to the small interactive pieces that genuinely need it, and let the server own the rest of the tree.</p>
<h3>Should I use route handlers or server actions for LLM calls in Next.js?</h3>
<p>Use a route handler when you need a streaming HTTP response, a call from a client component's <code>fetch</code>, custom headers or status codes, or a publicly callable endpoint. Use a server action when the call is a simple mutation triggered from a form inside a Server Component tree and does not need its own HTTP surface. Both should call into the same service layer underneath.</p>
<h3>How do I scale a Next.js AI application?</h3>
<p>Split async work into sibling Server Components so independent fetches stream in parallel instead of blocking on each other, keep state close to the components that consume a stream instead of funneling it through a global store, centralize provider calls in a service layer so retries and timeouts are consistent, and put only bounded, predictable routes on the edge runtime while keeping longer running generations on the Node runtime.</p>
]]></content:encoded></item><item><title><![CDATA[LLM Knowledge Leakage Prevention: Retrieval Permissions, Gateway Scrubbing, and Audit Trails]]></title><description><![CDATA[Your access control is probably correct and your model is probably still leaking. That is the uncomfortable part of llm knowledge leakage prevention: the…]]></description><link>https://mudassirworks.hashnode.dev/llm-knowledge-leakage-prevention-retrieval-permissions-gateway-scrubbing-and-audit-trails</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/llm-knowledge-leakage-prevention-retrieval-permissions-gateway-scrubbing-and-audit-trails</guid><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[Security]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Fri, 31 Jul 2026 20:48:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/05fa5b45-d0ad-4b76-975e-662679d8064f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Your access control is probably correct and your model is probably still leaking. That is the uncomfortable part of llm knowledge leakage prevention: the permission check runs at the document store, and the thing that actually reaches the user is a sentence the model wrote afterwards. Nothing in a traditional authorization layer inspects that sentence.</p>
<p>This article covers what LLM knowledge leakage is, why it differs from the llm data leakage enterprise teams already control for, and how to close it at three layers: retrieval time permissions, a scrubbing gateway on both sides of the model call, and an audit trail that can answer a regulator's question later. By the end you will have a checklist and three pieces of code you can drop into a Node service.</p>
<h2>What is LLM knowledge leakage and how it differs from data leakage</h2>
<p>LLM knowledge leakage is when a model reveals sensitive information to someone who was never entitled to see it, without any system being breached. No credential was stolen. No unauthorized query hit your database. The model just produced the information, and your logs show a perfectly ordinary request.</p>
<p>Data leakage, the version your security team already has controls for, is about access: a misconfigured bucket, an over broad IAM role, a token that outlived its owner. Knowledge leakage is about output, and that distinction decides where the control has to live.</p>
<p>There are three separate paths, and they need three separate fixes.</p>
<p><strong>Memorization.</strong> Language models unintentionally retain and reproduce sensitive information from their training data, including personally identifiable information. If your team fine tuned a model on support transcripts or clinical notes, some of that text is now recoverable from the weights under the right prompt. llm training data memorization is not something you can patch at request time, because the information never travels through the request path at all.</p>
<p><strong>Context bleed.</strong> One caller's retrieved documents end up answering another caller's question. This usually is not a vector store bug. It is a cache keyed on the question instead of on the question plus the caller, or a conversation summary that survived a tenant switch, or a shared few shot example set built from real customer data.</p>
<p><strong>Inference.</strong> The model reassembles a sensitive conclusion out of fragments that were each individually harmless. Three chunks the caller is fully entitled to read, combined, produce a sentence the caller is not entitled to know. No single document was misclassified, so reviewing the retrieval set finds nothing.</p>
<p>Classic access control misses all three because the permission check happens at the document store and the leak happens at the sentence the model emits. Between those two points the model has read everything you handed it and is free to recombine it. If your only gate is "can this user read this document", you have gated the input and left the output unguarded.</p>
<h2>The semantic spill: anonymization that still reveals too much</h2>
<p>The semantic spill happens when data is anonymized by removing names but retains enough specific context that the individual is still identifiable. You stripped the field labelled <code>name</code> and declared the record safe. It is not.</p>
<p>Two examples that pass every name scrubber I have shipped against:</p>
<p>A job title plus a location plus a period of employment. "The only female engineering director at a logistics startup in Rotterdam who left after eleven months" identifies exactly one person, and every token in that sentence is a common noun.</p>
<p>A rare diagnosis plus a small town. Prevalence does the work a name would have done. In a town of four thousand people, the condition is the identifier.</p>
<p>A regex based scrubber passes both, and no better pattern fixes that. Regex matches formats. It finds things shaped like an email address, a card number, a national identifier. It has no concept of meaning, so it cannot notice that a handful of ordinary words has narrowed the population down to one.</p>
<p>What works instead is treating quasi identifiers as sensitive in their own right and scoring the residual identifiability of a chunk before it enters a prompt. In practice: tag the fields that behave as quasi identifiers (role, employer, locality, dates of service, rare attributes), count how many survive inside a chunk, and route anything above your threshold through generalisation rather than deletion. Replace "Rotterdam" with "Western Europe". Replace "eleven months" with "under a year". Replace the rare diagnosis with its category. The sentence stays useful to the model and the population it could describe gets much wider.</p>
<p>The threshold is a policy decision, not a technical one. Set it with whoever owns privacy risk and enforce it in code.</p>
<h2>Data minimization at the retrieval layer</h2>
<p>The cheapest leak to prevent is the one where the document never enters the prompt. This is llm pii protection production work, and it belongs inside the retrieval call.</p>
<p>Filter at query time, inside the vector search, never afterwards in application code. A post filter is the most common mistake in this whole area: you fetch the top fifty neighbours, drop the ones the caller cannot see, then pass the rest along. The problem is that you already loaded those vectors and their payloads into your process. Any bug downstream puts them back in play: a rerank step that runs before the filter, a debug log, an error handler that dumps the candidate set into a trace. Most vector databases accept a metadata filter as part of the query itself. Use it.</p>
<p>You have two structural options and they trade off differently.</p>
<p>Per tenant index partitioning gives you the strongest isolation. A query against tenant A's index physically cannot return tenant B's vectors, so a filter bug degrades into an empty result instead of a leak. The cost is operational: more indexes to build, warm, and migrate, and poor economics once you have thousands of small tenants.</p>
<p>Metadata filtering keeps one index and attaches an access tag to every vector. Cheaper and simpler, but correctness now depends on every query carrying the right filter, which means it depends on every code path being right forever. If you go this way, wrap the client so that constructing a query without an access filter is impossible rather than merely discouraged.</p>
<p>Go finer than the document. Permissions usually sit at document level because that is where your existing system put them, but retrieval operates on chunks. A contract might be readable by the whole account team while one clause inside it is restricted to legal. Store the access tag on the chunk and derive it from the strictest rule that applies to any content in that chunk.</p>
<p>Then trim the chunk before it becomes prompt text. A retrieved record often carries far more than the model needs: internal identifiers, the full author record, timestamps, adjacent columns from the same row. Project down to the fields that answer questions. Everything you remove here is something the model cannot repeat.</p>
<pre><code class="language-typescript">type Caller = { id: string; tenantId: string; scopes: string[] };

const PROMPT_FIELDS = ["title", "body", "sourceId"] as const;

export async function retrieve(caller: Caller, query: string, k = 8) {
  const vector = await embed(query);

  // Permissions go INSIDE the query. A post filter would already have
  // loaded restricted payloads into this process.
  const hits = await vectors.search({
    vector,
    topK: k,
    filter: {
      tenantId: { $eq: caller.tenantId },
      accessTag: { $in: caller.scopes },
    },
  });

  // Project down: the model only ever sees fields it needs to answer.
  return hits.map((h) =&gt; ({
    id: h.id,
    text: PROMPT_FIELDS.map((f) =&gt; h.payload[f]).filter(Boolean).join("\n"),
  }));
}
</code></pre>
<h2>Gateway side input and output scrubbing</h2>
<p>Everything above assumes the retrieval set is the only source of sensitive text. Memorization breaks that assumption, so you need a control at the model boundary itself.</p>
<p>The design worth copying is a two sided guardrail. A research system called SafeGPT combines input redaction, output moderation, and human feedback to reduce data leakage, and that shape generalises cleanly to a production gateway: scrub on the way in, screen on the way out, feed reviewed catches back into your rules.</p>
<p>On the way in, redact and replace with stable tokens rather than deleting. Blank out a customer name and the model loses the thread, then starts answering about nobody in particular. Replace it with <code>PERSON_1</code> consistently across the whole request and the model can still reason about that person, resolve pronouns, and contrast them with <code>PERSON_2</code>. You hold the mapping in the gateway, never in the prompt, and rehydrate on the way out only for callers entitled to the real values. Everyone else keeps the placeholder tokens.</p>
<p>On the way out, run two checks rather than one. The first is obvious: does this completion contain anything the caller is not entitled to see, judged against the same policy the retriever used. The second is the one most teams skip: is every sensitive value in this completion actually present in the retrieved context. A value that appears in the output but never appeared in the input is either a hallucination or a memorized fact, and both deserve a flag. That grounding check is what catches the ai gateway output scrubbing gaps an entitlement check alone cannot see.</p>
<p>Streaming forces a real decision, because you cannot unsend a token that already reached the client. Either buffer the completion until the scrubber has run and accept the latency, or stream through a sliding window of a few hundred characters so the scrubber always holds enough context to catch a pattern spanning token boundaries. What you must not do is stream raw model output straight to a browser and check it afterwards.</p>
<pre><code class="language-typescript">import { redact, rehydrate } from "./pii";

export async function guardedComplete(caller: Caller, prompt: string, ctx: Doc[]) {
  // Inbound: stable tokens, so the model keeps its referents.
  const { text: safePrompt, map } = redact(prompt);
  const { text: safeCtx } = redact(ctx.map((d) =&gt; d.text).join("\n\n"), map);

  const completion = await model.complete({ system: safeCtx, user: safePrompt });

  // Outbound check 1: entitlement.
  const violations = screen(completion, caller.scopes);

  // Outbound check 2: grounding. A sensitive value that was never in the
  // context came from the weights, not from your data.
  const ungrounded = sensitiveSpans(completion).filter(
    (s) =&gt; !safeCtx.includes(s.value)
  );

  if (violations.length || ungrounded.length) {
    audit.flag({ caller: caller.id, violations, ungrounded });
    return { text: "[redacted]", blocked: true };
  }

  return { text: rehydrate(completion, map, caller), blocked: false };
}
</code></pre>
<h2>Monitoring and audit trails for LLM interactions</h2>
<p>When something does go wrong, the question you get asked is narrow and specific: which sources produced this answer, and who saw it. An audit trail that cannot answer that is decoration.</p>
<p>Log identifiers and hashes, never the sensitive values themselves. An audit store full of plaintext PII is a second copy of your problem, and it usually carries weaker controls because nobody thinks of logs as a data store. Hash the redacted spans so you can correlate repeats without holding the content.</p>
<p>Keep the retrieval document ids for every call. This is the field teams wish they had and almost never captured. Without it you cannot reconstruct what the model was looking at, which turns root cause analysis into guesswork.</p>
<p>Alert on rates, not on single events. One redaction hit is normal traffic. A caller whose redaction rate jumps from a baseline of a couple of percent to forty percent of requests is either probing your boundaries or has found a prompt that works. Same for the grounding check: a rising share of ungrounded sensitive spans is your memorization signal, and it is the only realtime signal you get that the model is repeating its training data.</p>
<p>The regulatory side is why this pays for itself. Breach costs in the United States remain the highest in the world at just over $10 million per incident, driven by regulatory penalties and litigation rather than by technical cleanup. Those are exactly the cost drivers an audit trail moves: showing which records were exposed, to whom, and for how long is the difference between a scoped disclosure and an assumption that everything was compromised.</p>
<pre><code class="language-typescript">audit.write({
  requestId,
  callerId: caller.id,
  tenantId: caller.tenantId,
  ts: Date.now(),
  model: model.name,
  promptHash: sha256(safePrompt),
  completionHash: sha256(completion),
  retrievedDocIds: ctx.map((d) =&gt; d.id),      // the field everyone forgets
  redactionCount: map.size,
  redactedTypes: [...new Set([...map.values()].map((v) =&gt; v.type))],
  ungroundedSpanCount: ungrounded.length,
  blocked,
  // Never write the values themselves. Hashes correlate; plaintext leaks.
});
</code></pre>
<h2>Checklist: hardening your LLM pipeline against leakage</h2>
<ul>
<li><p>Pass the caller's tenant and scopes as a filter inside the vector query, and make a query without them fail to compile.</p>
</li>
<li><p>Move access tags from the document to the chunk, deriving each chunk's tag from the strictest rule that applies to its content.</p>
</li>
<li><p>Project retrieved records down to the fields the model needs before they become prompt text.</p>
</li>
<li><p>Tag quasi identifiers (role, employer, locality, dates of service, rare attributes) as sensitive and generalise them instead of deleting them.</p>
</li>
<li><p>Replace redacted values with stable tokens so the model keeps its referents, and hold the mapping in the gateway.</p>
</li>
<li><p>Screen every completion twice: once against the caller's entitlements, once against what actually appeared in the retrieved context.</p>
</li>
<li><p>Buffer streamed output through a sliding window so the scrubber sees patterns that span token boundaries.</p>
</li>
<li><p>Key every cache on the caller identity as well as the question, and never reuse a conversation summary across tenants.</p>
</li>
<li><p>Record retrieval document ids on every call so you can answer which sources produced an answer.</p>
</li>
<li><p>Alert on redaction rate and ungrounded span rate per caller rather than on individual events.</p>
</li>
</ul>
<h2>FAQ</h2>
<h3>What is LLM knowledge leakage?</h3>
<p>LLM knowledge leakage is a model revealing sensitive information to someone who was never entitled to see it, with no system breached and no unauthorized query made. It arrives by three paths: memorization of training data, context bleed where one caller's documents answer another caller's question, and inference where the model reassembles a restricted conclusion from fragments that were each harmless alone.</p>
<h3>How do I prevent data leakage in LLM applications?</h3>
<p>Apply the caller's permissions inside the retrieval query rather than after it, tag permissions at chunk level, and trim retrieved records to the fields the model actually needs. Then wrap the model call in a two sided gateway: redact inbound values into stable tokens, and screen every completion against both the caller's entitlements and the retrieved context. Log document ids and alert on redaction rates.</p>
<h3>What is the difference between data leakage and knowledge leakage in AI?</h3>
<p>Data leakage is an access failure. Someone reached data they should not have reached, usually through a misconfiguration, a stolen credential, or an over broad role. Knowledge leakage is an output failure. Every access check passed and the model still produced information the reader was not entitled to, either by memorizing training data or by combining permitted fragments into a restricted conclusion.</p>
]]></content:encoded></item><item><title><![CDATA[TypeScript Design Patterns for LLM Applications: From Prototype to Production]]></title><description><![CDATA[By the end of this article you will be able to structure a TypeScript AI application architecture that survives contact with production: a swappable LLM…]]></description><link>https://mudassirworks.hashnode.dev/typescript-design-patterns-for-llm-applications-from-prototype-to-production</link><guid isPermaLink="true">https://mudassirworks.hashnode.dev/typescript-design-patterns-for-llm-applications-from-prototype-to-production</guid><category><![CDATA[AI]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[webdev]]></category><category><![CDATA[React]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Mudassir Khan]]></dc:creator><pubDate>Wed, 29 Jul 2026 20:05:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a15c0d4da253d50d4c74169/759d1cb6-3386-4140-87f8-cae025096963.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>By the end of this article you will be able to structure a TypeScript AI application architecture that survives contact with production: a swappable LLM layer, typed tool calling, streaming responses, and a test suite that does not collapse into mock soup. These are the typescript design patterns llm teams reach for once the demo works and the real users show up.</p>
<h2>What changes when TypeScript meets LLMs</h2>
<p>A quick script that calls an API and prints a string does not need architecture. A product does. The moment you have more than one model provider, a retry policy, a tool calling loop, and a frontend that streams tokens, you are writing a distributed system that happens to have a language model as one of its nodes.</p>
<p>Three ideas carry almost all of the weight here: dependency injection so your business logic never imports a vendor SDK directly, the adapter pattern so swapping OpenAI for Anthropic or a local model is a config change rather than a rewrite, and type safety pushed all the way to the edge of the network boundary so a malformed model response fails loudly in development instead of quietly in production.</p>
<p>The pressure to get this right is not hypothetical. One widely cited industry estimate has enterprise adoption of AI agents jumping from under 5 percent of applications to roughly 40 percent within a few years, and a codebase without clear seams for the AI layer will not absorb that kind of growth gracefully.</p>
<h2>Repository pattern for LLM call abstraction</h2>
<p>The single most useful typescript llm wrapper pattern is treating the model provider like a data store: define an interface your application code depends on, then write one adapter per vendor behind it.</p>
<pre><code class="language-typescript">interface CompletionRequest {
  prompt: string;
  maxTokens: number;
  temperature: number;
}

interface CompletionResult {
  text: string;
  model: string;
  tokensUsed: number;
}

interface LlmRepository {
  complete(req: CompletionRequest): Promise&lt;CompletionResult&gt;;
}

class OpenAiRepository implements LlmRepository {
  constructor(private client: OpenAiClient, private model: string) {}

  async complete(req: CompletionRequest): Promise&lt;CompletionResult&gt; {
    const res = await this.client.chat.completions.create({
      model: this.model,
      messages: [{ role: "user", content: req.prompt }],
      max_tokens: req.maxTokens,
      temperature: req.temperature,
    });
    return {
      text: res.choices[0].message.content ?? "",
      model: this.model,
      tokensUsed: res.usage?.total_tokens ?? 0,
    };
  }
}
</code></pre>
<p>Your route handlers, background jobs, and agent loop all depend on <code>LlmRepository</code>, never on <code>OpenAiClient</code> directly. Swapping providers, or running two providers side by side for an A over B comparison, becomes a matter of injecting a different implementation at the composition root instead of grepping the codebase for every place a vendor SDK got imported.</p>
<p>This is also where you get your first real return on type safety: the repository interface is the contract. If a new provider cannot satisfy <code>CompletionResult</code> without lying about a field, that mismatch shows up as a compile error, not a support ticket three weeks later.</p>
<h2>Circuit breaker for model failures and fallbacks</h2>
<p>Model providers fail in ways plain HTTP retries handle badly: slow degradation, partial outages, and rate limiting that returns a 429 for a stretch and then recovers. A circuit breaker gives you a typed state machine around that behaviour instead of a pile of ad hoc try and catch blocks.</p>
<pre><code class="language-typescript">type BreakerState = "closed" | "open" | "halfOpen";

class ModelCircuitBreaker {
  private state: BreakerState = "closed";
  private failureCount = 0;
  private readonly failureThreshold = 5;
  private readonly resetTimeoutMs = 30000;
  private openedAt = 0;

  async call&lt;T&gt;(fn: () =&gt; Promise&lt;T&gt;, fallback: () =&gt; Promise&lt;T&gt;): Promise&lt;T&gt; {
    if (this.state === "open") {
      if (Date.now() - this.openedAt &lt; this.resetTimeoutMs) {
        return fallback();
      }
      this.state = "halfOpen";
    }

    try {
      const result = await fn();
      this.failureCount = 0;
      this.state = "closed";
      return result;
    } catch (err) {
      this.failureCount += 1;
      if (this.failureCount &gt;= this.failureThreshold) {
        this.state = "open";
        this.openedAt = Date.now();
      }
      return fallback();
    }
  }
}
</code></pre>
<p>Wire this around your <code>LlmRepository</code> call, with the fallback pointing at a cheaper or faster secondary model, a cached response, or a graceful degraded reply. The point of the breaker is not to hide failures. It is to stop hammering a struggling upstream and to make the failure path an explicit, typed branch instead of an unhandled rejection three layers up the stack.</p>
<p>One practitioner observation worth internalizing: engineers who have shipped several of these systems now describe designing the control flow and state transitions around model calls, sometimes called flow engineering, as more valuable day to day than clever prompt wording. A breaker is one small, concrete piece of that flow.</p>
<h2>Typed tool calling with Zod: the practical guide</h2>
<p>Tool calling is where untyped LLM code gets dangerous fastest, because the model is deciding which function to call and with what arguments. Zod schema llm tool calling is the pattern that closes that gap: define each tool's arguments as a schema, derive the TypeScript type from the schema, and validate every model generated call before it touches real code.</p>
<pre><code class="language-typescript">import { z } from "zod";

const SearchOrdersArgs = z.object({
  customerId: z.string().min(1),
  status: z.enum(["pending", "shipped", "cancelled"]).optional(),
  limit: z.number().int().min(1).max(50).default(10),
});

type SearchOrdersArgs = z.infer&lt;typeof SearchOrdersArgs&gt;;

const tools = {
  searchOrders: {
    description: "Search a customer's orders by status",
    schema: SearchOrdersArgs,
    handler: async (args: SearchOrdersArgs) =&gt; {
      return db.orders.findMany({
        where: { customerId: args.customerId, status: args.status },
        take: args.limit,
      });
    },
  },
} as const;

async function dispatchToolCall(name: string, rawArgs: unknown) {
  const tool = tools[name as keyof typeof tools];
  if (!tool) throw new Error(`Unknown tool: ${name}`);
  const parsed = tool.schema.safeParse(rawArgs);
  if (!parsed.success) {
    throw new Error(`Invalid arguments for ${name}: ${parsed.error.message}`);
  }
  return tool.handler(parsed.data as never);
}
</code></pre>
<p>Structured output validated against a schema, rather than free text parsed with regular expressions, is fast becoming the standard way serious teams handle this. The schema does three jobs at once: it documents the tool for the model, it is the single source of truth for the TypeScript type, and it is the runtime guard that stops a hallucinated argument from reaching your database layer. When the model gets creative with an enum value or forgets a required field, <code>safeParse</code> catches it before <code>handler</code> ever runs.</p>
<h2>Streaming handlers and typed event emitters</h2>
<p>Users expect tokens to appear as they are generated, and an untyped event bus for that stream is a common source of production bugs: a typo in an event name silently drops a whole class of updates.</p>
<pre><code class="language-typescript">type StreamEvent =
  | { type: "token"; value: string }
  | { type: "toolCall"; name: string; args: unknown }
  | { type: "done"; totalTokens: number }
  | { type: "error"; message: string };

class TypedStream {
  private handlers: Partial&lt;{ [K in StreamEvent["type"]]: Array&lt;(e: Extract&lt;StreamEvent, { type: K }&gt;) =&gt; void&gt; }&gt; = {};

  on&lt;K extends StreamEvent["type"]&gt;(type: K, handler: (e: Extract&lt;StreamEvent, { type: K }&gt;) =&gt; void) {
    (this.handlers[type] ??= []).push(handler as never);
  }

  emit(event: StreamEvent) {
    for (const handler of this.handlers[event.type] ?? []) {
      handler(event as never);
    }
  }
}
</code></pre>
<p>The discriminated union on <code>type</code> means your editor knows exactly which fields exist on each event, and a renamed event type becomes a compile error everywhere it is consumed rather than a silent no op handler. Wire the emitter's <code>error</code> event into your logging and metrics pipeline early. Observability on the streaming path (first token latency, tokens per second, and how often a stream ends in <code>error</code> rather than <code>done</code>) is usually the fastest way to notice a provider degrading before your users file a ticket about it.</p>
<h2>Testing your LLM layer without mocking everything</h2>
<p>The typical failure mode here is a test suite that mocks the model client so thoroughly that it verifies nothing except that your mocks return what you told them to return. Three techniques keep tests honest without hitting a real API on every run.</p>
<p>First, test against the <code>LlmRepository</code> interface with a deterministic fake implementation, not a mock of the vendor SDK. The fake returns realistic <code>CompletionResult</code> shapes so you are exercising your own parsing and error handling code, not rehearsing a stub.</p>
<p>Second, record real responses once (a small, versioned fixture set) and replay them in CI. This catches schema drift, like a provider adding a field your Zod schema does not expect, without a live network call on every commit.</p>
<p>Third, write property style tests for your Zod schemas directly: generate a batch of arguments that should pass and a batch that should fail validation, and assert both. This is where teams find that the schema itself was too loose long before a user does.</p>
<p>None of this replaces a small number of real end to end runs against a staging model before a release. It just moves the bulk of your coverage to something that runs in milliseconds and does not depend on an external service being up.</p>
<h2>FAQ</h2>
<h3>What TypeScript patterns work best for LLM apps?</h3>
<p>In practice, four patterns cover most of the surface area: the repository pattern for abstracting the model provider behind an interface, the adapter pattern for supporting multiple providers without branching logic scattered through the codebase, a circuit breaker for handling provider failures and rate limits gracefully, and schema validated tool calling so the model's decisions are checked before they run. Together these give you dependency injection at the seams that actually change (the provider, the tool set) and strong type safety everywhere else.</p>
<h3>How do I type tool calling in TypeScript?</h3>
<p>Define each tool's arguments as a Zod schema and derive the TypeScript type from that schema with <code>z.infer</code>, rather than writing the interface by hand and hoping it stays in sync. Validate every model generated call with <code>safeParse</code> before your handler runs, and keep the tool registry itself typed as a const object so an unknown tool name is caught at the dispatch step instead of deep inside a handler.</p>
<h3>Should I use a framework or build my own LLM wrapper in TypeScript?</h3>
<p>It depends on how much of the typescript agent framework patterns you actually need versus how much control you want over failure handling. A published comparison found that LlamaIndex.TS needs roughly 30 to 40 percent less code than an equivalent raw LangChain pipeline for a typical retrieval setup, which is a real argument for reaching for a framework once your use case is a standard retrieval or agent loop. If your requirements are unusual (a custom circuit breaker policy, a nonstandard streaming protocol, strict internal typing conventions) a thin hand rolled repository plus adapter layer, like the ones shown above, often ends up easier to reason about than fighting a framework's abstractions. Many teams land on a middle path: a framework for retrieval and orchestration, with a hand written typed layer around the actual model calls.</p>
]]></content:encoded></item></channel></rss>