<?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[Engineer At Caffeine]]></title><description><![CDATA[Documenting what I build, what I learn, and the ideas worth sharing.]]></description><link>https://engineer-at-caffeine.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 20:22:55 GMT</lastBuildDate><atom:link href="https://engineer-at-caffeine.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How I Would Build a Document Versioning System]]></title><description><![CDATA[Whenever I get a new feature request, especially "Version History," the immediate temptation is to build something complex like Git. Diffs, branches, merge…]]></description><link>https://engineer-at-caffeine.hashnode.dev/document-versioning-system</link><guid isPermaLink="true">https://engineer-at-caffeine.hashnode.dev/document-versioning-system</guid><dc:creator><![CDATA[Kartikey Bhatnagar]]></dc:creator><pubDate>Tue, 21 Jul 2026 13:26:54 GMT</pubDate><content:encoded><![CDATA[<p>Whenever I get a new feature request, especially "Version History," the immediate temptation is to build something complex like Git. Diffs, branches, merge conflicts. it sounds like a cool engineering challenge, right?</p>
<p>But as an Softwar Engineer, my main focus is always: <strong>Simple, reliable, and maintainable.</strong></p>
<p>Today, I’m going to share how I would design a practical document versioning system. My goal isn't to show off complexity, but to build a system that works flawlessly in production and is easy for future developers to understand and extend.</p>
<hr />
<h3>1. Architecture: Keep "Now" and "History" Strictly Separate</h3>
<p>The biggest mistake beginners make is trying to manage the current document state and the version history in the same data structure. I always keep them strictly separate.</p>
<p>I would use two tables:</p>
<ol>
<li><p><code>documents</code>: Stores the <em>current, mutable</em> state. This is what the user is actively editing right now.</p>
</li>
<li><p><code>document_versions</code>: Stores <em>immutable snapshots</em>. Once written, a version is never updated or deleted.</p>
</li>
</ol>
<pre><code class="language-sql">-- The current, editable document
CREATE TABLE documents (
    id UUID PRIMARY KEY,
    title TEXT,
    content TEXT,
    updated_at TIMESTAMP,
    created_at TIMESTAMP
);

-- The immutable history
CREATE TABLE document_versions (
    id UUID PRIMARY KEY,
    document_id UUID REFERENCES documents(id),
    version INT,
    content TEXT,
    content_hash TEXT, -- Crucial for preventing duplicates!
    created_at TIMESTAMP,
    created_by UUID,
    change_type TEXT -- 'AUTO_SAVE', 'MANUAL_SAVE', 'RESTORE', 'PUBLISH'
);
</code></pre>
<hr />
<h3>2. The Auto-Save Dilemma: Why Debounce and Throttle Fail</h3>
<p>When should the system automatically create a version? Most developers immediately reach for <strong>debouncing</strong> or <strong>throttling</strong>. Both are flawed for version history.</p>
<p><strong>Why Debounce Fails:</strong> Debounce waits for the user to <em>stop</em> typing before saving. Imagine a user types continuously for 30 minutes. Because they never pause long enough for the debounce timer to fire, <strong>no version is ever saved</strong>. If the browser crashes, 30 minutes of work is lost.</p>
<p><strong>Why Throttle is Sub-optimal:</strong> Throttle saves every <em>X</em> seconds while typing. It prevents data loss, but it might save a version when the user has only added a single space, or it might capture an incomplete thought mid-sentence. The history gets cluttered with junk.</p>
<p><strong>My Strategy: Interval + Dirty Flag</strong> This is the industry standard (used by Notion, Google Docs, etc.). I keep an <code>isDirty</code> flag.</p>
<pre><code class="language-typescript">let isDirty = false;

// Mark as dirty when the user types
editor.onChange(() =&gt; {
    isDirty = true;
});

// Check every 10 minutes
setInterval(() =&gt; {
    if (!isDirty) return; // Do nothing if no changes were made

    createVersion('AUTO_SAVE');
    isDirty = false;
}, 10 * 60 * 1000); // 10 minutes
</code></pre>
<p><strong>Why this approach:</strong> It guarantees periodic checkpoints without creating unnecessary versions for static documents. I combine this with immediate saves on manual "Save" clicks, "Publish" actions, and <code>beforeunload</code> (tab close) events for a bulletproof setup.</p>
<hr />
<h3>3. Preventing Duplicate Versions: The Hash Trick</h3>
<p>What happens if the 10-minute auto-save timer fires, but the user hasn't actually changed the text since the last save? I don't want to clutter the database with identical snapshots.</p>
<p>Instead of doing an expensive string comparison on the entire document, I use a <strong>SHA-256 hash</strong>.</p>
<pre><code class="language-typescript">const newHash = sha256(currentContent);
const lastVersionHash = getLastVersion().content_hash;

if (newHash === lastVersionHash) {
    return; // Content hasn't changed, skip saving!
}

// Proceed to save the new version
</code></pre>
<p>This makes duplicate detection lightning-fast and keeps the version history perfectly clean.</p>
<hr />
<h3>4. The "Restore" Trap: Never Rewrite History</h3>
<p>When a user decides to revert to an older version, how should the system handle it?</p>
<p><strong>The Bad Way (Rewriting History):</strong> If the user is on Version 5 and restores Version 2, some systems delete V3, V4, and V5, and overwrite the current document. This completely destroys the audit trail.</p>
<p><strong>The Good Way (Linear Progression):</strong> I treat a "restore" as just another edit. If the user is on V5 and restores V2, the system copies the content of V2 into the current document and creates a <strong>new Version 6</strong>.</p>
<pre><code class="language-text">v1 -&gt; v2 -&gt; v3 -&gt; v4 -&gt; v5
                     ↑
               User restores v2
                     ↓
v1 -&gt; v2 -&gt; v3 -&gt; v4 -&gt; v5 -&gt; v6 (Content matches v2)
</code></pre>
<p>History remains strictly linear, immutable, and fully auditable.</p>
<hr />
<h3>5. Storage Strategy: Full Snapshots vs. Diffs</h3>
<p>Should I store the entire markdown text for every version, or just the "diffs" (changes) like Git does?</p>
<p><strong>For an project, I always store the full text.</strong></p>
<p>Markdown files are incredibly small (usually just a few Kilobytes). Storing full snapshots provides massive benefits:</p>
<ul>
<li><p><strong>Easy to implement:</strong> No complex diff/patch algorithms required.</p>
</li>
<li><p><strong>Easy to restore:</strong> Just copy the <code>content</code> column.</p>
</li>
<li><p><strong>Easy to debug:</strong> I can query the database and read any version in plain text.</p>
</li>
</ul>
<p>Diff-based storage is reserved for systems handling massive enterprise documents or millions of versions. I follow the <strong>KISS (Keep It Simple, Stupid)</strong> principle here.</p>
<hr />
<h3>6. UI and Retention Policy</h3>
<p><strong>The UI:</strong> I wouldn't clutter the main editor with version history. I’d put it in a <strong>side sheet or drawer</strong>. Each entry should clearly display:</p>
<ul>
<li><p>Version Number (e.g., <code>v15</code>)</p>
</li>
<li><p>Timestamp (e.g., <code>Today at 10:20 AM</code>)</p>
</li>
<li><p>Change Type (e.g., <code>Auto Saved</code>, <code>Manual Save</code>, <code>Restored from v2</code>)</p>
</li>
</ul>
<p>I’d also allow users to preview the version and compare it side-by-side with the current version (using libraries like <code>diff-match-patch</code> or <code>jsdiff</code>).</p>
<p><strong>Retention Policy:</strong> I wouldn't keep infinite auto-saves; the database will bloat. I’d implement a simple retention policy:</p>
<ul>
<li><p>Keep <strong>all</strong> manual saves and publishes forever.</p>
</li>
<li><p>Keep auto-saves for the last <strong>30 days</strong>.</p>
</li>
<li><p>After 30 days, thin out auto-saves to one snapshot per day or week.</p>
</li>
</ul>
<hr />
<h3>Final Thoughts</h3>
<p>Building a versioning system doesn't require a computer science degree in distributed systems. By focusing on the fundamentals, I can build a robust feature in a fraction of the time:</p>
<ol>
<li><p><strong>Separate</strong> the current document from immutable version snapshots.</p>
</li>
<li><p>Use a <strong>Dirty Flag + Interval</strong> for auto-saving, avoiding debounce/throttle pitfalls.</p>
</li>
<li><p>Use <strong>SHA-256 hashing</strong> to prevent duplicate versions.</p>
</li>
<li><p>Always create a <strong>new version</strong> when restoring, preserving linear history.</p>
</li>
<li><p>Store <strong>full content snapshots</strong>, not diffs.</p>
</li>
</ol>
<p>This design is production-friendly, easy to test, and provides a fantastic user experience. More importantly, it leaves the door open: if the app eventually scales to the point where diffs <em>are</em> needed, I can swap out the storage layer without changing the core application logic.</p>
<p>Keep it simple, keep it reliable, and just ship it!</p>
]]></content:encoded></item><item><title><![CDATA[The Day Offset Pagination Broke My App (And How Cursor Pagination Saved It)]]></title><description><![CDATA[Today, I was working on a new feature and asked an AI assistant to generate some pagination code for my Node.js backend. It gave me the classic OFFSET and…]]></description><link>https://engineer-at-caffeine.hashnode.dev/offset-vs-cursor-pagination</link><guid isPermaLink="true">https://engineer-at-caffeine.hashnode.dev/offset-vs-cursor-pagination</guid><dc:creator><![CDATA[Kartikey Bhatnagar]]></dc:creator><pubDate>Mon, 20 Jul 2026 14:50:29 GMT</pubDate><content:encoded><![CDATA[<p>Today, I was working on a new feature and asked an AI assistant to generate some pagination code for my Node.js backend. It gave me the classic <code>OFFSET</code> and <code>LIMIT</code> approach.</p>
<p>In development, with just 100 rows in my database, it worked flawlessly. But when I pushed it to production with over a million rows? <strong>The API started crawling.</strong> Queries that took milliseconds were suddenly taking seconds.</p>
<p>After some research, I realized the villain: <strong>Offset Pagination</strong>. I quickly refactored my code to use <strong>Cursor Pagination</strong>, and the performance improvement was mind-blowing.</p>
<p>If you are building an app with a lot of data (like an infinite scroll feed), here is why you need to ditch <code>OFFSET</code> and switch to <code>CURSOR</code> pagination, along with the exact Node.js code to do it.</p>
<hr />
<h3>The Problem: Why is Offset Pagination Slow?</h3>
<p>Offset pagination is what we all learn first. It looks like this in SQL:</p>
<pre><code class="language-sql">-- Get Page 1
SELECT * FROM posts ORDER BY id ASC LIMIT 10 OFFSET 0;

-- Get Page 5
SELECT * FROM posts ORDER BY id ASC LIMIT 10 OFFSET 40;
</code></pre>
<p><strong>What’s wrong with this?</strong> Imagine you are reading a book, and you want to read page 50. With offset pagination, you have to start from page 1, read pages 1 to 49, throw them away, and then read page 50.</p>
<p>In database terms: To get the 5th page (offset 40), the database has to fetch <strong>50 rows</strong>, discard the first 40, and return the last 10. As the user goes deeper into the pages (e.g., Page 100), the database has to scan and discard hundreds of rows just to give you 10. This makes the query time grow linearly with the page number.</p>
<hr />
<h3>The Solution: Enter Cursor Pagination</h3>
<p>Cursor pagination (also known as keyset pagination) changes the approach. Instead of saying <em>"skip 40 rows"</em>, we say <em>"give me 10 rows that come</em> <em><strong>after</strong></em> <em>this specific ID"</em>.</p>
<pre><code class="language-sql">-- First Page
SELECT * FROM posts ORDER BY id ASC LIMIT 10;

-- Next Page (assuming the last ID we saw was 105)
SELECT * FROM posts WHERE id &gt; 105 ORDER BY id ASC LIMIT 10;
</code></pre>
<p><strong>Why is this lightning fast?</strong> Because <code>id</code> is indexed! The database doesn't scan or discard anything. It uses the B-Tree index to jump directly to <code>id = 105</code> and fetches the next 10 rows. Whether you are on page 2 or page 2,000, the query takes the exact same amount of time.</p>
<hr />
<h3>The Node.js Implementation</h3>
<p>Let’s write the actual Node.js (Express) code for this. We will use a simple SQL database (this logic works for MySQL, PostgreSQL, etc.).</p>
<h4>The "Limit + 1" Trick</h4>
<p>Before we write the code, there is a pro-trick you need to know: <strong>How do we know if there is a "Next Page"?</strong> Instead of running a separate <code>COUNT()</code> query (which is slow), we just fetch <code>limit + 1</code> rows. If we get 11 rows back, we know there is a next page. We just pop the 11th row out and use its ID as the <code>nextCursor</code>.</p>
<h4>The Code</h4>
<pre><code class="language-javascript">const express = require('express');
const app = express();

// Mock database connection (Replace with your actual DB setup like mysql2, pg, or Prisma)
const db = require('./db'); 

app.get('/api/posts', async (req, res) =&gt; {
    try {
        // 1. Get query parameters
        const limit = parseInt(req.query.limit) || 10;
        const cursor = req.query.cursor; // This will be the ID of the last item from the previous page

        // 2. Build the SQL Query
        let query = 'SELECT id, title, content, created_at FROM posts WHERE ';
        let params = [];

        if (cursor) {
            // If we have a cursor, fetch records AFTER this cursor
            query += 'id &gt; ? ';
            params.push(cursor);
        } else {
            // If no cursor, it's the first page
            query += '1=1 ';
        }

        query += 'ORDER BY id ASC LIMIT ?';
        
        // PRO TIP: Fetch limit + 1 to check if there's a next page
        params.push(limit + 1); 

        // 3. Execute Query
        const rows = await db.query(query, params);

        // 4. Handle Pagination Logic
        let hasNextPage = false;
        let nextCursor = null;

        if (rows.length &gt; limit) {
            hasNextPage = true;
            // Remove the extra row we fetched just for checking
            rows.pop(); 
        }

        // The cursor for the next page is the ID of the last item in our current result
        if (hasNextPage) {
            nextCursor = rows[rows.length - 1].id;
        }

        // 5. Send Response
        return res.json({
            success: true,
            data: rows,
            pagination: {
                hasNextPage,
                nextCursor,
                // Note: In cursor pagination, we don't usually return "totalPages" 
                // because counting total rows in a million-row table is expensive.
            }
        });

    } catch (error) {
        console.error('Error fetching posts:', error);
        return res.status(500).json({ success: false, message: 'Internal Server Error' });
    }
});

app.listen(3000, () =&gt; console.log('Server running on port 3000'));
</code></pre>
<h3>How the Frontend Calls This</h3>
<p><strong>First Request:</strong></p>
<pre><code class="language-http">GET /api/posts?limit=10
</code></pre>
<p><em>Response gives 10 items, and</em> <code>nextCursor: 10</code><em>.</em></p>
<p><strong>Second Request (Load More / Infinite Scroll):</strong></p>
<pre><code class="language-http">GET /api/posts?limit=10&amp;cursor=10
</code></pre>
<p><em>Response gives the next 10 items, and</em> <code>nextCursor: 20</code><em>.</em></p>
<hr />
<h3>Offset vs Cursor</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Offset Pagination (<code>LIMIT/OFFSET</code>)</th>
<th>Cursor Pagination (<code>WHERE id &gt; cursor</code>)</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Performance</strong></td>
<td>Degrades on higher pages (Slow)</td>
<td>Consistent across all pages (Fast)</td>
</tr>
<tr>
<td><strong>Data Consistency</strong></td>
<td>Can skip/duplicate rows if data is added/removed while paginating</td>
<td>Safe from skipping/duplicating rows</td>
</tr>
<tr>
<td><strong>Jump to Page</strong></td>
<td>Easy (e.g., "Go to Page 50")</td>
<td>Impossible (Can only go Next/Previous)</td>
</tr>
<tr>
<td><strong>Best Used For</strong></td>
<td>Admin dashboards, small datasets, traditional numbered pages</td>
<td>Infinite scrolls, feeds, large datasets, mobile apps</td>
</tr>
</tbody></table>
<h3>Final Thoughts</h3>
<p>AI tools are great for boilerplate, but they don't always know the scale of your production database. Always evaluate the generated code against your expected data size. If your table is going to cross 100k rows, drop the <code>OFFSET</code> and embrace the <code>CURSOR</code>. Your database (and your users) will thank you!</p>
<hr />
<h3><strong>Some extra tips</strong></h3>
<ul>
<li><p><strong>Indexing:</strong> Make sure the column used as the cursor (such as <code>id</code> or <code>created_at</code>) has a database index. Without an index, cursor pagination won't perform efficiently.</p>
</li>
<li><p><strong>UUIDs:</strong> If you're using UUIDs as your primary key, <code>id &gt; cursor</code> can be unreliable because UUIDs are randomly generated. In that case, use a sequential field like <code>created_at</code> (or another ordered timestamp) as the cursor. If you're using an auto-incrementing <code>id</code>, then <code>id &gt; cursor</code> works perfectly.</p>
</li>
<li><p><strong>Total Count:</strong> With cursor pagination, it's common <strong>not</strong> to return <code>totalPages</code> or <code>totalItems</code>. Counting millions of rows is an expensive operation. Instead, use a <strong>"Load More"</strong> button or <strong>infinite scrolling</strong> on the frontend.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Stop Using POST for Search Queries: Enter HTTP QUERY]]></title><description><![CDATA[If you’ve been building RESTful APIs for the last decade, you’ve lived by a strict set of rules. You fetch data with GET, create entities with POST, update…]]></description><link>https://engineer-at-caffeine.hashnode.dev/stop-using-post-for-search-queries-enter-http-query</link><guid isPermaLink="true">https://engineer-at-caffeine.hashnode.dev/stop-using-post-for-search-queries-enter-http-query</guid><dc:creator><![CDATA[Kartikey Bhatnagar]]></dc:creator><pubDate>Thu, 02 Jul 2026 18:40:25 GMT</pubDate><content:encoded><![CDATA[<h3>The New HTTP <code>QUERY</code> Method: Finally, a Proper Way to Send Complex Requests</h3>
<p>If you’ve been building RESTful APIs for the last decade, you’ve lived by a strict set of rules. You fetch data with <code>GET</code>, create entities with <code>POST</code>, update with <code>PUT</code>, and delete with <code>DELETE</code>. The HTTP method tells the server exactly what your intention is.</p>
<p>But recently, a new Request for Comments was published: <strong>RFC 10008</strong>, which officially defines the <code>QUERY</code> method for HTTP.</p>
<p>If your first reaction is, <em>"Wait, why do we need a new HTTP method? Can't we just use what we already have?"</em> , you aren't alone. This exact question has sparked massive debates in Hacker News ( Lowkey fun to read 😼)</p>
<p><a href="https://news.ycombinator.com/item?id=48640974">Hacker News Debate</a></p>
<p>Let’s break down why the <code>QUERY</code> method exists, the messy workarounds we’ve been forced to use, and what this means for the future of API design.</p>
<hr />
<h3>The Problem: When <code>GET</code> Just Isn't Enough</h3>
<p>Traditionally, if you wanted to filter a resource, you used query parameters in a <code>GET</code> request: <code>GET /api/v1/users?role=admin&amp;status=active&amp;sort=desc</code></p>
<p>This works beautifully for simple filters. But what happens when you need to perform complex relational queries, deep nesting, or pass an array of 500 specific IDs?</p>
<p>Suddenly, you run into a wall of issues:</p>
<ol>
<li><p><strong>URL Length Limits:</strong> Browsers and servers have maximum character limits for URLs. Massive queries will just get truncated or rejected.</p>
</li>
<li><p><strong>Encoding Nightmares:</strong> Sending non-ASCII or special characters requires URL encoding, bloating the request size.</p>
</li>
<li><p><strong>Inconsistent Arrays:</strong> How do you represent an array in a URL? Is it <code>?roles[]=admin&amp;roles[]=reporter</code>, <code>?roles=admin&amp;roles=reporter</code>, or <code>?roles=admin,reporter</code>? It’s entirely implementation-specific.</p>
</li>
<li><p><strong>Security &amp; Logging:</strong> URLs are logged everywhere (proxies, web servers, browser history). You definitely don't want sensitive filtering criteria or massive payloads sitting in plaintext logs.</p>
</li>
</ol>
<hr />
<h2>The Two Workarounds Everyone Tries</h2>
<p>Since <code>GET</code> falls short for complex queries, developers have historically relied on two workarounds. Both come with heavy compromises.</p>
<h3>Workaround 1: GET with a Request Body</h3>
<p>From a purely theoretical standpoint, older HTTP RFCs didn't explicitly forbid a body in a <code>GET</code> request. So, developers tried it.</p>
<p><strong>Why it’s a bad idea:</strong> The ecosystem hates it. Proxies, corporate firewalls (WAFs), and even CDNs like AWS CloudFront will often silently strip the body off a <code>GET</code> request or reject it outright.</p>
<p>Furthermore, the browser's native <code>fetch</code> API doesn't even support sending a body with a <code>GET</code> request.  </p>
<p>And then I read the comment that changed my perspective:</p>
<blockquote>
<p><em>A GET request with a body is an attack-shaped</em> design flaw*. It blurs the lines of request validation and opens the door to request smuggling attacks.*</p>
</blockquote>
<h3>Workaround 2: Using <code>POST</code> for Everything</h3>
<p>Since <code>GET</code> with a body is blocked, the standard workaround is to use <code>POST</code>. After all, <code>POST</code> allows request bodies .</p>
<p><strong>Why it’s a bad idea:</strong> Semantics. <code>POST</code> is defined as <strong>non-safe</strong> and <strong>non-idempotent</strong>. It is meant for creating resources or triggering state-changing processes.</p>
<p>Because <code>POST</code> is non-idempotent, CDNs and reverse proxies <strong>will not cache it</strong> by default. If you use <code>POST</code> for a read-only search query, you lose all the performance benefits of edge caching. You also lose the ability to safely auto-retry failed requests without worrying about side effects.</p>
<p><code>The crazy part ? Because GraphQL uses POST for all its queries, CDNs like Cloudflare have to use hacky workarounds—like creating a fake GET request under the hood just to cache GraphQL responses!</code></p>
<hr />
<h2>Enter the Hero: HTTP <code>QUERY</code></h2>
<p>To finally solve this long-standing problem , RFC 10008 introduces the <code>QUERY</code> method.</p>
<p>The spec is straightforward: <code>QUERY</code> <strong>is exactly like</strong> <code>GET</code><strong>, but it officially supports a request body.</strong></p>
<pre><code class="language-http">QUERY /api/v1/users/search HTTP/1.1
Content-Type: application/json

{
  "role": "admin",
  "departments": ["engineering", "product"],
  "filters": {
    "active_since": "2023-01-01"
  }
}
</code></pre>
<h3>Why <code>QUERY</code> is a Game Changer</h3>
<ol>
<li><p><strong>It is Safe and Idempotent:</strong> Just like <code>GET</code>, making a <code>QUERY</code> request does not change the state of the server. You can retry it safely.</p>
</li>
<li><p><strong>It is Cacheable:</strong> Because it is idempotent, proxies and CDNs can cache it.</p>
</li>
<li><p><strong>Semantic Clarity:</strong> Middleboxes now have concrete guidance. They know this request is read-only, but carries a payload.</p>
</li>
<li><p><strong>No URL Limits:</strong> You can send massive, deeply nested JSON payloads without worrying about URL character limits.</p>
</li>
</ol>
<hr />
<h3><strong>The Comment Section Had Some Strong Opinions.</strong></h3>
<p>While <code>QUERY</code> sounds perfect on paper, the Hacker News community has pointed out some very real-world hurdles , we are going to face during adoption.</p>
<h3>1. The Caching <strong>Normalization</strong> Problem</h3>
<p>CDNs and proxies terminate TLS, meaning they cam read the request body to cache it.</p>
<p>But how do you generate a cache key from a JSON body?</p>
<p>If Client A sends <code>{"a": 1, "b": 2}</code> and Client B sends <code>{"b": 2, "a": 1}</code>, those are semantically the exact same query. But as raw strings, they are different.</p>
<p>Proxies will need to implement complex JSON Normalization to ensure they aren't caching the same query multiple times just because the keys were ordered differently.</p>
<h3>2. The Legacy Infrastructure Wall</h3>
<p>Just because the RFC is published doesn't mean the internet is ready.</p>
<ul>
<li><p><strong>WAFs and Proxies:</strong> Many enterprise firewalls are configured to only allow a strict whitelist of HTTP methods (<code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>). They will likely reject <code>QUERY</code> with a <code>405 Method Not Allowed</code>.</p>
</li>
<li><p><strong>Old Servers:</strong> Some ancient, unpatched proxy appliances might not know how to parse an unknown verb and could crash or drop the connection.  </p>
<p>Updating the spec is easy; updating millions of unattended black-box routers and legacy enterprise proxies will take years.</p>
</li>
</ul>
<h3>3. Goodbye, Link Sharing</h3>
<p>One of the best features of <code>GET</code> is that the entire state of the request is in the URL. You can copy the URL, bookmark it, or email it to a colleague, and they will see the exact same filtered data.</p>
<p>Because <code>QUERY</code> relies on a request body, <strong>you cannot share a</strong> <code>QUERY</code> <strong>URL</strong>. If your users rely on bookmarking search results or sharing filtered views via URL, you must stick to <code>GET</code>.</p>
<hr />
<h2>So, Should You Use <code>QUERY</code> Today?</h2>
<p>The short answer is: <strong>Probably not yet, but you should prepare for it.</strong></p>
<p>Support for HTTP <code>QUERY</code> is still in its infancy. API clients, major browsers, and enterprise proxies need time to update their firmware and software to recognize and properly handle the new verb.</p>
<p>However, there are massive use cases that will benefit immensely once the ecosystem catches up:</p>
<ul>
<li><p><strong>GraphQL:</strong> APIs could finally use <code>QUERY</code> for read operations (allowing for proper edge caching) and reserve <code>POST</code> strictly for mutations.</p>
</li>
<li><p><strong>Search Engines:</strong> Tools like ElasticSearch and OpenSearch, which currently suffer from the <code>GET</code> vs <code>POST</code> dilemma for complex search payloads, will have a native, semantically correct HTTP method.</p>
</li>
<li><p><strong>Complex Dashboards:</strong> Internal tools that rely on heavy, nested filtering can finally send clean JSON bodies without hacking together <code>POST</code> requests.</p>
</li>
</ul>
<h3>The One Rule That Matters</h3>
<ul>
<li><p><strong>Stick to</strong> <code>GET</code> if your filters are simple and you want your URLs to be shareable and easily cacheable.</p>
</li>
<li><p><strong>Use</strong> <code>QUERY</code> for complex, read-only searches that require a JSON body, <em>provided</em> you have tested that your intermediate proxies and CDNs won't block it.</p>
</li>
<li><p><strong>Never use</strong> <code>GET</code> <strong>with a body.</strong> It’s a hack that will eventually break.</p>
</li>
<li><p><strong>Stop using</strong> <code>POST</code> <strong>for read-only queries.</strong> It ruins your caching strategy.</p>
</li>
</ul>
<p>The web is finally getting a tool designed specifically for the complex, data-heavy applications we build today. It might take a few years for the dust to settle, but HTTP <code>QUERY</code> is a welcome addition to the RESTful toolkit.</p>
]]></content:encoded></item><item><title><![CDATA[Structuring Context for AI Agents: Inside Google's Open Knowledge Format]]></title><description><![CDATA[Most of us build RAG pipelines the same way: chunk the data, generate embeddings, and dump everything into a vector database. It works, but I've always…]]></description><link>https://engineer-at-caffeine.hashnode.dev/google-open-knowledge-format</link><guid isPermaLink="true">https://engineer-at-caffeine.hashnode.dev/google-open-knowledge-format</guid><dc:creator><![CDATA[Kartikey Bhatnagar]]></dc:creator><pubDate>Sun, 28 Jun 2026 21:23:52 GMT</pubDate><content:encoded><![CDATA[<p>Most of us build RAG pipelines the same way: chunk the data, generate embeddings, and dump everything into a vector database. It works, but I've always felt it's a bit blunt. Once text gets chunked, a lot of structural context disappears, and that's exactly the information an AI agent often needs to reason effectively.</p>
<p>Recently, I came across Google's <strong>Open Knowledge Format (OKF)</strong>. Instead of treating your knowledge base as a collection of unrelated chunks, OKF defines a standardized directory structure of Markdown files specifically designed for AI agents. Think of it as giving your knowledge base a proper schema.</p>
<p>The interesting part is that instead of forcing an agent to infer context after retrieval, every piece of knowledge already tells the agent what it represents before the model even starts reading the actual content.</p>
<h3>How an OKF Bundle Is Structured</h3>
<p>An OKF bundle is simply a directory of Markdown files.</p>
<p>Instead of dumping an entire webpage into one document, each file represents a single concept, entity, or procedure. One article could easily become several smaller concept files, each focused on one idea.</p>
<p>Every file has two parts i) YAML frontmatter ii) Markdown body</p>
<h3>The Metadata Layer (YAML Frontmatter)</h3>
<p>The YAML frontmatter acts like a schema. Before an agent reads the content itself, it already knows what kind of document it's dealing with.</p>
<pre><code class="language-yaml">type: concept
title: AI Overviews
tags: [search, google, ai, ranking]
related: [search-console, core-web-vitals]
status: active
</code></pre>
<p>Rather than having to parse the entire document just to understand its purpose, the agent gets that information immediately.</p>
<p>Typically, you'll define different document types such as:</p>
<ul>
<li><p><strong>Concepts</strong> — definitions and core ideas.</p>
</li>
<li><p><strong>Entities</strong> — people, companies, products, or services.</p>
</li>
<li><p><strong>Playbooks</strong> — step-by-step procedures.</p>
</li>
<li><p><strong>References</strong> — documentation, raw data, or external resources.</p>
</li>
</ul>
<h3>The Payload (Markdown Body)</h3>
<p>Everything below the frontmatter is just normal Markdown.</p>
<p>There isn't a strict format here. You can use headings, lists, tables, diagrams, code blocks—whatever makes sense.</p>
<p>The important part is that because every file follows the same metadata schema, the agent already knows where this document fits before reading the actual content.</p>
<h3>The Routing Table (<code>index.md</code>)</h3>
<p>An OKF bundle usually includes an <code>index.md</code>.</p>
<p>I like thinking of this as the routing table for the knowledge base.</p>
<p>Instead of blindly searching thousands of files, the agent first reads the index to understand which concepts are relevant for the current task. That makes retrieval much more intentional instead of purely semantic.</p>
<h3>Knowledge Graphs and the LLM Wiki</h3>
<p>One part that immediately reminded me of Andrej Karpathy's <strong>LLM Wiki</strong> idea is how OKF naturally becomes a knowledge graph.</p>
<p>The goal isn't just retrieving documents anymore.</p>
<p>The agent continuously builds and maintains a structured understanding of your knowledge.</p>
<p>Whenever new information is added, the agent extracts important concepts, creates new Markdown files if needed, and links them to existing concepts using the <code>related</code> field.</p>
<img src="https://cdn.hashnode.com/uploads/covers/682ea41c27e50783383435b2/952e949d-4efd-406a-993d-b3333cd1b597.png" alt="" style="display:block;margin:0 auto" />

<p>In practice, every Markdown file becomes a node, while the <code>related</code> entries become the edges connecting everything together.</p>
<p>That allows an agent to traverse relationships instead of simply retrieving isolated chunks.</p>
<h3>Playbooks as Executable Logic</h3>
<p>One feature I find especially useful is documenting operational playbooks.</p>
<p>Instead of writing procedures purely for humans, you're writing them in a way AI agents can actually execute.</p>
<p>I think of a playbook almost like a state machine written in Markdown.</p>
<p>Instead of documenting isolated steps, you define the entire workflow:</p>
<ul>
<li><p><strong>Initial State</strong> — Where the process begins.</p>
</li>
<li><p><strong>Sequence of Actions</strong> — The steps performed to reach the goal.</p>
</li>
<li><p><strong>Transition Conditions</strong> — The rules that determine what happens next.</p>
</li>
<li><p><strong>Expected Output</strong> — The desired end state or artifact.</p>
</li>
</ul>
<p>This approach works well for workflows such as:</p>
<ul>
<li><p>Generating a client proposal</p>
</li>
<li><p>Investigating a traffic drop after a migration</p>
</li>
<li><p>Debugging production incidents</p>
</li>
<li><p>Onboarding a new customer</p>
</li>
</ul>
<p>Rather than manually following dozens of notes every time, the agent can synthesize your documentation, execute the playbook step by step, and produce a report that follows your existing workflow.</p>
<h3>CI/CD for Knowledge (The Lint Function)</h3>
<p>Another idea I really liked comes from Karpathy's concept of a <strong>Lint</strong> function.</p>
<p>Just like we use ESLint or Prettier to keep codebases consistent, an LLM can periodically review the knowledge graph itself.</p>
<p>The lint process checks for things like:</p>
<ul>
<li><p>contradictory information,</p>
</li>
<li><p>outdated documentation,</p>
</li>
<li><p>broken references,</p>
</li>
<li><p>duplicate concepts,</p>
</li>
<li><p>inconsistent playbooks.</p>
</li>
</ul>
<p>Whenever new knowledge gets added, the system compares it against the existing graph and flags anything that doesn't line up.</p>
<p>Instead of manually auditing documentation, the knowledge base continuously validates itself.</p>
<h3>Bootstrapping Your Own OKF System</h3>
<p>The nice part is that you don't need to build custom parsers to start experimenting.</p>
<p>I'd begin by collecting the foundational resources:</p>
<ol>
<li><p>Google's official Open Knowledge Format documentation.</p>
</li>
<li><p>The <code>SPEC.md</code> from the Google Cloud Platform knowledge catalog.</p>
</li>
<li><p>Andrej Karpathy's notes on the LLM Wiki concept.</p>
</li>
</ol>
<p>Then I'd feed those into an AI coding agent with a prompt like:</p>
<blockquote>
<p>"I want to build an OKF system. Read the provided documentation and specifications. Give me ideas on how to structure this for my specific domain. Then ask me questions one at a time so we can decide exactly what concepts and playbooks to build first."</p>
</blockquote>
<p>From there, I'd start small.</p>
<p>Take your existing documentation, extract individual concepts into separate Markdown files, define a consistent YAML schema, and gradually build the relationships between them.</p>
<p>As AI agents continue getting better, I think having a structured, graph-aware knowledge base like this will matter much more than simply storing embeddings in a vector database.</p>
<p>The difference is subtle but important: instead of building an agent that only <strong>searches</strong> your data, you're building one that can actually <strong>understand how everything connects together.</strong></p>
]]></content:encoded></item></channel></rss>