<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Varun Arora]]></title><description><![CDATA[Varun Arora]]></description><link>https://varunarora.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 26 Nov 2026 13:03:39 GMT</lastBuildDate><atom:link href="https://varunarora.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Context Compaction: Working Memory for AI Agents]]></title><description><![CDATA[Why AI coding agents degrade over long tasks and how to keep long-running AI coding agents from drifting or crashing]]></description><link>https://varunarora.hashnode.dev/context-compaction-working-memory-for-ai-agents</link><guid isPermaLink="true">https://varunarora.hashnode.dev/context-compaction-working-memory-for-ai-agents</guid><category><![CDATA[ai agents]]></category><category><![CDATA[llm]]></category><category><![CDATA[System Design]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[architecture]]></category><dc:creator><![CDATA[Varun Arora]]></dc:creator><pubDate>Wed, 25 Nov 2026 16:29:32 GMT</pubDate><content:encoded><![CDATA[<p>If you have ever watched an AI coding agent work on a real task, you have probably seen this pattern: the first five steps are sharp and accurate, the next ten get noticeably slower, and by step twenty the agent forgets your original instructions or crashes with a context limit error.</p>
<p>The model did not suddenly get worse at reasoning. Its working memory got polluted.</p>
<p>In most basic agent loops, conversation history is just an append-only list. Every user prompt, assistant reply, file read, search result, and terminal log gets pushed onto the end of that list and the entire list gets sent back to the model on every single turn.</p>
<p>Managing that growing history without breaking the agent's train of thought is called <strong>context compaction</strong>.</p>
<hr />
<h2>Why Append-Only History Breaks Down</h2>
<p>A single file read or test run can easily dump 3,000 to 10,000 tokens into the conversation. Over 15 or 20 steps, an unmanaged message list causes three predictable failures:</p>
<ul>
<li><strong>Attention drift ("lost in the middle"):</strong> Language models pay the most attention to the very beginning and the very end of a prompt. When 40,000 tokens of stale terminal logs pile up in the middle, the model starts missing rules you gave it at the start.</li>
<li><strong>Rising latency and cost:</strong> Because every turn re-sends the full history, step 20 pays to re-process everything from steps 1 through 19. Tasks slow down and token costs compound quickly.</li>
<li><strong>Hard crashes:</strong> Even large context windows have a ceiling. One massive <code>grep</code> output or stack trace can push the request over the limit and kill the run mid-task.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/67141d2a12f6a817966b4331/6b2ee4d3-d9ba-462f-b139-f0308c1bd4df.png" alt="U-shaped attention curve showing high LLM focus on the system prompt at the start and recent turns at the end, with steep recall drop-off across stale logs in the middle" style="display:block;margin:0 auto" />

<hr />
<h2>Why Naive Fixes Fail</h2>
<p>When developers first hit token limits, they usually reach for one of two quick fixes. Both create new bugs.</p>
<h3>1. Dropping the Oldest Messages (Sliding Window)</h3>
<p>The simplest approach is to keep only the last N messages and delete older ones. The problem is that the oldest messages hold your <strong>system prompt, original goal, and key constraints</strong>. Once those fall off the window, the agent loses track of what it is actually trying to build.</p>
<h3>2. Blindly Truncating Long Outputs</h3>
<p>Another common shortcut is cutting off tool outputs at a fixed character count. Say, keeping only the first 2,000 characters of a terminal log. In practice, the useful signal (like the actual error message at the end of a build log or stack trace) sits at the bottom, so blind slicing throws away the exact detail the model needed.</p>
<hr />
<h2>How Context Compaction Works</h2>
<p>A better way to design agent memory is to treat the context window like <strong>RAM</strong>, not a permanent log file. Active work stays hot and detailed; older work gets compressed or cleared out once it has served its purpose.</p>
<p>Building a reliable compaction loop comes down to four mechanics.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67141d2a12f6a817966b4331/7e5b3940-0438-43b9-afd8-fb4b830ba081.png" alt="Before-and-after diagram showing a bloated append-only message list compressed into a system prompt, structured state checkpoint, pruned tool output stubs, and recent turns" style="display:block;margin:0 auto" />

<h3>1. Trigger Early With a High-Watermark Threshold</h3>
<p>Do not wait for the API to throw a token-limit error. Before every model call, estimate the total tokens in the current message list. Once usage crosses a safe threshold, typically <strong>75% to 80%</strong> of the model's context window, run compaction first.</p>
<p>Leaving that 20–25% buffer guarantees the model always has room to read a large file or write a detailed response on its next turn.</p>
<h3>2. Prune Stale Tool Outputs First</h3>
<p>Not all tokens age at the same rate. Raw tool payloads (full file contents, directory listings, search dumps) take up the most space and lose their value the fastest. Once the agent has read a 600-line file and decided what to edit, those 600 lines do not need to stay in history forever.</p>
<p>Instead of deleting the message completely, replace the bulky output with a short placeholder:</p>
<pre><code class="language-text">[Contents of src/config.ts omitted after reading]
</code></pre>
<p>Keeping the original tool call and this lightweight stub is an important detail: the agent still sees <em>that</em> it already inspected <code>src/config.ts</code>, so it does not waste turns reading the same file again.</p>
<h3>3. Summarize Old Turns Into a State Checkpoint</h3>
<p>For older conversational turns that still contain useful decisions, run a focused summarization step. Rather than asking the model for a vague "summary of the chat so far," force the output into a strict state structure:</p>
<ul>
<li><strong>Primary goal:</strong> What the user originally asked for.</li>
<li><strong>Completed work:</strong> Steps already finished and verified.</li>
<li><strong>Modified files:</strong> Which files were created or edited.</li>
<li><strong>Current state &amp; blockers:</strong> What still needs to be done or fixed.</li>
</ul>
<p>This checkpoint replaces the older middle section of the conversation, while the <strong>system prompt</strong> at the top and the <strong>most recent 4 to 6 turns</strong> at the bottom remain untouched. The agent keeps both its long-term direction and its immediate short-term context.</p>
<h3>4. Respect Message Pairing Rules</h3>
<p>Most LLM APIs enforce strict structural rules on message history. In particular, an assistant message requesting a <code>tool_call</code> must always be followed immediately by its matching <code>tool_result</code> message.</p>
<p>If compaction slices the message array right between a <code>tool_call</code> and its <code>tool_result</code>, the next API request will fail validation. Any compaction boundary has to move cleanly around complete interaction pairs.</p>
<hr />
<h2>Why You Should Not Compact on Every Turn</h2>
<p>A tempting mistake is to summarize or prune history after every single step to keep the prompt as small as possible. In practice, that backfires because of how LLM inference engines use <strong>prefix KV caching</strong>.</p>
<p>Providers cache the internal attention states of your prompt from the very first token onward. When you only <strong>append</strong> new messages to the end of the conversation, the engine reuses the cached prefix, charging a fraction of the normal input token rate and responding much faster.</p>
<p>If you summarize or edit earlier messages on every turn, you change the prefix. Prefix matching stops at the very first altered token, invalidating the cache for the rest of the prompt and forcing you to pay full uncached input rates on every step.</p>
<table>
<thead>
<tr>
<th align="left">Strategy</th>
<th align="left">Tokens Sent / Turn</th>
<th align="left">KV Cache Behavior</th>
<th align="left">Relative Input Cost (10 Turns)</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><strong>Append-only + batch compaction</strong></td>
<td align="left">~40,000</td>
<td align="left">Prefix stays cached across turns</td>
<td align="left"><strong>~1x</strong> (Baseline)</td>
</tr>
<tr>
<td align="left"><strong>Summarize on every turn</strong></td>
<td align="left">~25,000</td>
<td align="left">Prefix mutates every turn (<strong>0% cache hits</strong>)</td>
<td align="left"><strong>~3x higher</strong> (+ summary calls)</td>
</tr>
</tbody></table>
<p><strong>The fix is batch compaction:</strong> keep the conversation strictly append-only until it hits your high-watermark threshold, rewrite and prune everything in a single checkpoint pass, and then let the new prefix stay cached for the next stretch of turns.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67141d2a12f6a817966b4331/2f89f942-3005-4cc8-8cca-e8ccdfb2780a.png" alt="Sawtooth graph showing token usage growing across append-only KV-cached turns until hitting the 75–80% high-watermark threshold, then dropping after a single batch compaction pass" style="display:block;margin:0 auto" />

<hr />
<h2>The Core Trade-Off</h2>
<p>Context compaction is <strong>lossy compression</strong>. If you compact too aggressively, the agent forgets subtle details and wastes turns re-reading files it already checked. If you compact too late, noise builds up and reasoning quality drops.</p>
<p>The goal is not to preserve every raw byte of history—it is to preserve <strong>decisions and state</strong> while discarding raw bulk once it has been processed.</p>
<p>Larger context windows will keep arriving, and they help. But throwing more memory at an unbounded loop only delays the problem. Reliable long-running agents come from treating context as a finite resource and managing it deliberately.</p>
]]></content:encoded></item><item><title><![CDATA[Designing Crash-Safe In-Memory Systems with a WAL]]></title><description><![CDATA[How high-throughput backends combine sequential Write-Ahead Logs (WAL), in-memory state, and deterministic replay for fast crash recovery.]]></description><link>https://varunarora.hashnode.dev/designing-crash-safe-in-memory-systems-with-a-wal</link><guid isPermaLink="true">https://varunarora.hashnode.dev/designing-crash-safe-in-memory-systems-with-a-wal</guid><category><![CDATA[distributed systems]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Databases]]></category><category><![CDATA[backend]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Varun Arora]]></dc:creator><pubDate>Mon, 23 Nov 2026 15:10:03 GMT</pubDate><content:encoded><![CDATA[<p>Most backend applications start with a simple pattern: a request arrives, the server updates a row in PostgreSQL, and it sends back a response.</p>
<p>For everyday traffic, this works well. Under heavy concurrent writes, however, updating rows in place hits a physical bottleneck. Every mutation has to acquire row locks, update B-tree indexes, and perform random disk writes across scattered pages. Latency climbs from microseconds to milliseconds, and throughput stalls.</p>
<p>To build systems that are both fast and crash-safe, we have to go back to how storage hardware actually works.</p>
<hr />
<h2>Random Writes vs. Sequential Appends</h2>
<p>RAM gives nanosecond access, which makes it ideal for holding active application state. The problem is volatility: if the process crashes or the server loses power, everything in RAM disappears.</p>
<p>On disk, not all writes cost the same:</p>
<ul>
<li><strong>Random Writes (Slow):</strong> Updating existing database records and indexes requires jumping across different disk locations, managing page splits, and coordinating locks.</li>
<li><strong>Sequential Appends (Fast):</strong> Writing strictly to the end of a single file avoids disk seeks, lock contention, and index overhead. Even on modern NVMe SSDs, sequential appends avoid write amplification and run orders of magnitude faster than in-place relational updates.</li>
</ul>
<p>This difference gives us the core building block of durable storage engines: <strong>the Write-Ahead Log (WAL).</strong></p>
<hr />
<h2>Deriving the Write-Ahead Log</h2>
<p>Instead of forcing a relational database to handle every live mutation, we split responsibilities across three layers:</p>
<ol>
<li><strong>Write-Ahead Log (Source of Truth):</strong> Every incoming state change is first written to the end of an append-only log file on local disk and flushed (<code>fsync</code>). Because the log lives on disk, it survives process crashes and power cuts without paying network latency on every write.</li>
<li><strong>Application RAM (Microsecond Speed):</strong> Once the log entry hits disk, the application updates its in-memory maps or queues and immediately acknowledges the client. RAM acts purely as a fast, disposable view of the log.</li>
<li><strong>PostgreSQL (Compacted Store):</strong> A background worker periodically flushes settled state into PostgreSQL so data stays queryable and protected even if the local machine or disk fails permanently.</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/67141d2a12f6a817966b4331/754278c3-e2af-46b9-ba45-e9abf3e43631.png" alt="Three-layer WAL write path: local WAL disk append, in-memory state, and background PostgreSQL persistence" style="display:block;margin:0 auto" />

<p>Because the log only ever appends to the end of a file, writes stay fast while guaranteeing that no acknowledged request is lost in a crash.</p>
<hr />
<h2>Checkpoints: Keeping Recovery Fast</h2>
<p>An append-only log solves write speed, but it creates a new problem: the file grows forever. If a server runs for six months and crashes, replaying 500 million log entries from day one would take far too long.</p>
<p>To keep restart times predictable, systems pair the WAL with <strong>checkpoints</strong>:</p>
<ul>
<li>Every record written to the WAL receives a monotonically increasing <strong>Log Sequence Number (</strong><code>LSN</code><strong>)</strong>.</li>
<li>Periodically, a background worker saves the current state into PostgreSQL along with the <code>LSN</code> of the last included event (<code>checkpointLSN</code>).</li>
<li>Once PostgreSQL confirms that transaction, any WAL entries older than <code>checkpointLSN</code> are no longer needed for crash recovery and can be safely truncated.</li>
</ul>
<hr />
<h2>Deterministic Crash Recovery</h2>
<p>When a crashed server restarts, its RAM is completely empty. Recovery works by combining the last checkpoint in PostgreSQL with the recent tail of the WAL:</p>
<ol>
<li><strong>Block incoming traffic:</strong> Keep HTTP and WebSocket ports closed so live requests cannot interleave with recovery.</li>
<li><strong>Load the checkpoint:</strong> Read the last saved state and <code>checkpointLSN</code> from PostgreSQL into memory.</li>
<li><strong>Replay the WAL tail:</strong> Open the WAL file and replay only records where <code>record.LSN &gt; checkpointLSN</code>, passing them through the exact same state-transition function used during live traffic.</li>
<li><strong>Open the gates:</strong> Once the end of the WAL is reached, open the ports and begin serving requests.</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/67141d2a12f6a817966b4331/a40b3185-60aa-4322-a4b7-bd76ff672a3f.png" alt="Deterministic crash recovery flow loading the PostgreSQL checkpoint and replaying the WAL tail" style="display:block;margin:0 auto" />

<pre><code class="language-go">type Record struct {
	LSN   uint64
	Key   string
	Delta int
}

type WAL interface {
	AppendAndSync(rec Record) error
}

type StateStore struct {
	mu      sync.RWMutex
	wal     WAL
	state   map[string]int
	lastLSN uint64
}

// apply is the single deterministic state-transition function.
func (s *StateStore) apply(rec Record) {
	if rec.LSN &lt;= s.lastLSN {
		return
	}
	s.state[rec.Key] += rec.Delta
	s.lastLSN = rec.LSN
}

// Execute persists the change to the WAL before updating RAM.
func (s *StateStore) Execute(rec Record) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	if rec.LSN &lt;= s.lastLSN {
		return nil
	}
	if err := s.wal.AppendAndSync(rec); err != nil {
		return err
	}

	s.apply(rec)
	return nil
}

// Recover restores the checkpoint and replays newer WAL entries.
func (s *StateStore) Recover(snapshot map[string]int, checkpointLSN uint64, tail []Record) {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.state = snapshot
	s.lastLSN = checkpointLSN

	for _, rec := range tail {
		s.apply(rec)
	}
}
</code></pre>
<hr />
<h2>Three Guardrails for Log-Based Recovery</h2>
<p>Building a WAL from scratch introduces edge cases that only show up during real failures. Three rules prevent silent data corruption:</p>
<ul>
<li><strong>Checksum every log entry (CRC32):</strong> If power cuts out mid-write, the last record in the WAL may be half-written (a "torn write"). Storing a checksum with each entry lets recovery detect an incomplete tail record and safely discard it instead of loading garbage into memory.</li>
<li><strong>Keep transitions deterministic:</strong> Never call <code>time.Now()</code> or generate random IDs inside your state-transition logic. Capture timestamps and IDs <em>before</em> writing the WAL record so replaying the log produces the exact same state every time.</li>
<li><strong>Enforce idempotency via</strong> <code>LSN</code><strong>:</strong> A crash can happen right after PostgreSQL commits a checkpoint, before the old WAL segment is deleted. Checking <code>rec.LSN &lt;= s.lastLSN</code> ensures overlapping records are skipped rather than applied twice.</li>
</ul>
<p>True durability does not come from hoping a database stays fast under load—it comes from writing sequentially to disk first, mutating memory second, and keeping recovery deterministic.</p>
]]></content:encoded></item></channel></rss>