<?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[Build & Ship]]></title><description><![CDATA[Build & Ship]]></description><link>https://mubert.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 24 Nov 2026 12:18:11 GMT</lastBuildDate><atom:link href="https://mubert.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Rebuilt My Product Demo Video Workflow Around Image-to-Video Models]]></title><description><![CDATA["So it's a spreadsheet?" That's what a friend said after three seconds of my landing page demo video. He wasn't entirely wrong — my habit tracker does have…]]></description><link>https://mubert.hashnode.dev/rebuilt-my-product-demo-video-workflow-around-image-to-video-models</link><guid isPermaLink="true">https://mubert.hashnode.dev/rebuilt-my-product-demo-video-workflow-around-image-to-video-models</guid><dc:creator><![CDATA[mubert woo]]></dc:creator><pubDate>Fri, 13 Nov 2026 09:31:01 GMT</pubDate><content:encoded><![CDATA[<p>"So it's a spreadsheet?"</p>
<p>That's what a friend said after three seconds of my landing page demo video. He wasn't entirely wrong — my habit tracker does have grids — but the video was a screen recording with lo-fi music underneath, and it communicated nothing about why anyone would want the product.</p>
<p>I'd shipped demo videos the same way for years: record the screen, trim the dead air, add a caption. It's the default because it requires no new skills. The problem is that it also sells no feeling. A screen recording shows the interface. It doesn't show someone reaching for their phone at 6 a.m., or the small satisfaction of closing a laptop with the day's plan done.</p>
<p>This is the workflow I rebuilt after that conversation. It produces a 20-second demo with generated footage in an evening — no hires, no After Effects, no camera crew. If you can cut a timeline in a free video editor, you can run it.</p>
<h2>The pipeline at a glance</h2>
<table>
<thead>
<tr>
<th>Stage</th>
<th>You produce</th>
<th>Rough time</th>
</tr>
</thead>
<tbody><tr>
<td>1. Shot list</td>
<td>3 shots, ~20 seconds total</td>
<td>30 min</td>
</tr>
<tr>
<td>2. Reference images</td>
<td>2–3 stills</td>
<td>30 min</td>
</tr>
<tr>
<td>3. Motion references</td>
<td>2–3 clips of yourself</td>
<td>30 min</td>
</tr>
<tr>
<td>4. Generation</td>
<td>2–3 video clips</td>
<td>minutes per clip, plus retries</td>
</tr>
<tr>
<td>5. Assembly</td>
<td>The final cut</td>
<td>1–2 hours</td>
</tr>
</tbody></table>
<p>The first three stages are the ones developers skip, and skipping them is why AI-generated footage ends up looking random. Each stage is cheap. Do them in order.</p>
<h2>Write the shot list before touching any tool</h2>
<p>A demo video has one job: make a stranger care for twenty seconds. That's three shots, one idea each. My rule after a few failed attempts: if you can't caption a shot with a single sentence, it doesn't make the list.</p>
<p>The shot list for my habit tracker:</p>
<ul>
<li><strong>Shot 1 (6s).</strong> A person picks up their phone in morning light and starts a focus session. Sentence: "It fits into a real morning."</li>
<li><strong>Shot 2 (8s).</strong> The app's weekly grid on a phone propped on a desk, slow push-in. Sentence: "Progress you can actually see."</li>
<li><strong>Shot 3 (6s).</strong> A person closes their laptop at night and leans back. Sentence: "The day is done — and it went to plan."</li>
</ul>
<p>Notice what's missing: feature tours, logo animations, settings screens. Those are what the screen-recording segment is for later. The generated shots carry feeling; the interface carries facts.</p>
<h2>Build reference images</h2>
<p>Motion transfer animates a still image, so the still decides half of your footage quality. Two kinds of stills cover a typical demo:</p>
<ul>
<li><strong>Product stills.</strong> The phone or laptop on a clean surface, screen visible, nothing else in frame. I just photograph my own desk setup — no mockup tools needed.</li>
<li><strong>People stills.</strong> Any clear photo works: a portrait, a full-body shot, yourself. Keep the whole subject in frame with some margin around them, plain background, even light. Tight face crops leave the model nowhere to put body motion.</li>
</ul>
<p>png or jpg, either is fine. One still can serve several shots if the framing differs.</p>
<h2>Shoot your own motion references</h2>
<p>This is the trick that keeps the whole pipeline free: you are the motion capture studio.</p>
<p>A motion reference is a short clip of you (or anyone) performing the exact movement you want in the final shot. Stand against a plain wall, hold the phone at chest height, and record:</p>
<ul>
<li>picking up the phone and tapping it,</li>
<li>closing a laptop and leaning back,</li>
<li>a slow pan across the desk, if you want a camera-style move.</li>
</ul>
<p>The constraints that matter: MP4, between 3 and 30 seconds, under 100 MB. That sounds limiting until you notice a 10-second clip covers a 6-second shot with room to trim. Two habits that paid off for me:</p>
<ul>
<li><strong>Perform slower than feels natural.</strong> About 20% slower. Generation amplifies energy, and an energetic reference comes back frantic.</li>
<li><strong>Keep hands away from the face when possible.</strong> Hands near faces are where generated footage breaks most often. Wide shots first; close-ups only when a shot truly needs them.</li>
</ul>
<h2>Generate the shots</h2>
<p>Two families of tools can produce this footage, and they fail differently.</p>
<p>General text-to-video generators — Runway, Pika, and their peers — are prompt-driven. They're excellent for abstract b-roll, but the motion is whatever the model improvises from your words. Getting the same specific gesture twice is luck, and a demo shot usually needs a specific interaction: tap here, close there.</p>
<p>Motion-transfer tools are take-driven: you supply the still and the performance, and the model applies the motion frame by frame while keeping the subject's face, clothing, and identity stable. For demo shots, take-driven wins, because "the same take, but with my product" is exactly the deliverable.</p>
<p>The tool I settled on is an <a href="https://motioncontrol.app/generate/motion-control">image-to-video motion transfer tool</a> built on Kling Motion Control. The flow is four steps: upload the reference image, upload the motion reference video, optionally add a text prompt to set the scene and style ("wooden desk, warm morning light, shallow depth of field"), then pick a model — Kling Motion Control 2.6 or 3.0 — and generate. Each clip takes a few minutes.</p>
<p>Honest notes from a few sessions with it: simple shots — the phone pickup, the laptop close, a slow push-in — landed on the first or second take. Fast hand motion near a face is still where takes go wrong, which matches the pitfalls above. And since generation isn't instant, queue all of your shots up front, then edit while they render. The same service also hosts other video models — Veo 3.1, Seedance — and I used one of them for an abstract background shot where I didn't need precise motion.</p>
<p>[TODO: 3-frame strip of generated Shot 1 — phone pickup in morning light]</p>
<h2>Assemble like a lazy editor</h2>
<p>Everything after generation is ordinary editing, and ordinary editing has one rule for demos: shorter.</p>
<ul>
<li>Cut in CapCut or DaVinci Resolve — both free.</li>
<li>Generated shots first, screen recording last. The footage earns attention; the recording proves the product is real. My 20-second cut is roughly 14 seconds generated, 6 seconds screen recording.</li>
<li>Captions on everything. Most people watch muted.</li>
<li>Music low — it's a floor, not a feature.</li>
<li>Export 1080p. A landing page doesn't need 4K.</li>
</ul>
<p>[TODO: screenshot of the final 20-second timeline in the editor]</p>
<h2>What I got wrong the first time</h2>
<ul>
<li><strong>I wrote a 60-second script.</strong> Solo-dev demos don't need a minute. Twenty seconds, three shots, done.</li>
<li><strong>My motion references were too energetic.</strong> The first generated clip looked like the character was late for a train. Slow the performance down.</li>
<li><strong>I expected one-take perfection.</strong> Budget two or three generations per shot and pick the best. It's still faster than driving to a shoot.</li>
<li><strong>I started with a close-up of hands typing.</strong> Small fast objects next to other small fast objects. Wide shots first.</li>
</ul>
<h2>The checklist</h2>
<ul>
<li><input disabled type="checkbox" /> 3 shots, ~20 seconds, one sentence per shot</li>
<li><input disabled type="checkbox" /> Reference images: clean background, whole subject in frame</li>
<li><input disabled type="checkbox" /> Motion references: MP4, 3–30 s, under 100 MB, performed slower than natural</li>
<li><input disabled type="checkbox" /> 2–3 takes per shot, best one wins</li>
<li><input disabled type="checkbox" /> One real screen-recording segment in the final cut</li>
<li><input disabled type="checkbox" /> Captions on, music low, 1080p export</li>
</ul>
<p>The first video took me an evening and one stubborn regeneration session. The second took two hours. The screen recording didn't disappear from my demos — it just stopped being the whole story.</p>
]]></content:encoded></item><item><title><![CDATA[How I Debug Production Issues I Can't Reproduce Locally]]></title><description><![CDATA[Every developer eventually meets the bug that made them question their career choices. Mine was an endpoint that returned 500 errors for roughly one in…]]></description><link>https://mubert.hashnode.dev/how-i-debug-production-issues-i-can-t-reproduce-locally</link><guid isPermaLink="true">https://mubert.hashnode.dev/how-i-debug-production-issues-i-can-t-reproduce-locally</guid><dc:creator><![CDATA[mubert woo]]></dc:creator><pubDate>Fri, 13 Nov 2026 09:22:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a9bafc5bb5e5c1a615e1dd6/50a9269e-de62-42f0-a0c3-9377497a4880.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Every developer eventually meets the bug that made them question their career choices. Mine was an endpoint that returned 500 errors for roughly one in twenty requests — only in production, only sometimes, and never once on my laptop.</p>
<p>I could send the exact same request with the exact same payload and get a 200 on my machine and a 500 in production. Staging? Fine. A colleague's machine? Fine. Production? Broken, intermittently, for two days.</p>
<p>This article is the workflow I've converged on after a few incidents like that one. It's not clever or novel. But it's repeatable, and repeatability is what you want on a Friday afternoon when the on-call channel has gone quiet and everyone is waiting for you to say something useful.</p>
<h2>Why "reproduce it locally" is a trap</h2>
<p>The instinct when a bug won't reproduce is to keep trying to reproduce it. I've watched people — including me — burn entire days on this: matching dependency versions, copying database dumps, replaying recorded traffic, adjusting clocks.</p>
<p>The problem is that production differs from your laptop in three ways, and you rarely can replicate all three at once:</p>
<ul>
<li><strong>Data.</strong> Production has real data: a user with fifty thousand records, a field that's null only for accounts created before some migration, a name with a combining character that breaks your string comparison. Your test fixtures have three tidy rows.</li>
<li><strong>Environment.</strong> Config values, environment variables, dependency versions, load balancer behavior, cache layers, disk space, even the system clock and time zone.</li>
<li><strong>Time and concurrency.</strong> Production runs under load. Requests interleave, background jobs overlap, caches expire mid-request, two deploys race each other. Locally, you're one user clicking slowly.</li>
</ul>
<p>So the first mental shift: <strong>treat "reproduce locally" as one hypothesis, not a prerequisite.</strong> Sometimes you'll get lucky and reproduce it. Often you won't, and the search for a perfect reproduction becomes procrastination with extra steps.</p>
<h2>Step 0: Stop the bleeding first</h2>
<p>Before root-causing anything, mitigate. In rough order of preference:</p>
<ul>
<li><strong>Roll back the last deploy</strong> if the timing matches. Boring, effective, and you can always ship the real fix later.</li>
<li><strong>Turn the feature off</strong> with a feature flag if the failing path is behind one.</li>
<li><strong>Shed load or rate-limit</strong> if the pattern looks like capacity or contention.</li>
<li><strong>Fail over or retry around a dependency</strong> if the errors point at something you call rather than something you run.</li>
</ul>
<p>One rule here: mitigation and root-cause hunting are two separate tasks. Don't try to debug while the fire is burning, and don't declare victory when the fire goes out — a rollback that hides a data bug can make tomorrow worse.</p>
<p>Also, write down what you changed and when. A timestamped log of your own actions becomes part of the evidence later. I keep this in the incident channel, not in my head.</p>
<h2>Step 1: Rebuild the timeline from logs</h2>
<p>With the fire contained, the first real debugging step is narrative, not code: reconstruct what actually happened to one failing request.</p>
<p>This only works well if your logs are structured and carry a correlation ID. If they aren't, that's the first thing to fix after the incident — but for now, work with what you have:</p>
<ol>
<li>Pick one failing request. An error report, a support ticket, whatever gives you a request ID or a timestamp plus user.</li>
<li>Pull every log line for that request ID, across all services.</li>
<li>Read them as a story: what came in, what was decided, what was called, what came back.</li>
<li>Then pull the same story for a healthy request at roughly the same time, and diff the two.</li>
</ol>
<p>The diff between a failing request and a healthy one is worth more than an hour of staring at code. Look for the <em>first</em> divergence, not the loudest error — the loudest error is often downstream noise from something that went quietly wrong three steps earlier: a timeout that was swallowed and retried, a cache that served a stale entry, a default value that masked a missing field.</p>
<p>In my 500-errors bug, this step is what cracked it: the failing requests all showed a retry against a dependency that the healthy requests never made. That single observation reframed the whole investigation.</p>
<h2>Step 2: Shrink the search space with metrics and traces</h2>
<p>One failing request gives you a story. Aggregated metrics give you the <em>boundary</em> of the problem: when does it happen, and when does it not?</p>
<p>Slice the error rate by every dimension you have:</p>
<ul>
<li>Endpoint and status code</li>
<li>Deploy version</li>
<li>Instance or container</li>
<li>Region or availability zone</li>
<li>User segment: new vs. old accounts, free vs. paid, tenant size</li>
<li>Time: the exact minute it started</li>
</ul>
<p>Each slice either splits the problem or eliminates a hypothesis:</p>
<ul>
<li><strong>One instance only?</strong> Think host-specific: config drift, disk pressure, a hot key in local memory, a zombie process.</li>
<li><strong>Started with a deploy?</strong> Bisect the deploy (more on that below).</li>
<li><strong>Correlates with traffic spikes?</strong> Think capacity, connection pool exhaustion, contention.</li>
<li><strong>Only one tenant or data shape?</strong> Think data, not code.</li>
</ul>
<p>If you have distributed tracing, this is its moment: find where latency or errors concentrate across the request path. If you don't, structured logs with timestamps can approximate a trace well enough to find the slow or failing hop.</p>
<p>You're still not looking for the bug at this stage. You're looking for the fence around it.</p>
<h2>Step 3: Run controlled experiments</h2>
<p>Once you have a hypothesis, test it without touching production data. In rough order of how much I trust each:</p>
<ul>
<li><strong>Replay in staging.</strong> Take the failing request — payload, headers, auth context — and replay it against staging with production-shaped data. If it fails there, congratulations: you now have a reproduction and can debug like a normal human again.</li>
<li><strong>Shadow or dry-run mode.</strong> If the suspect change is behind a flag, run the new path in "log what you would do" mode against real traffic, and compare its output with the old path.</li>
<li><strong>Turn up observability on a sample.</strong> Enable verbose logging or tracing for a small fraction of requests via a flag, then wait for the failure to walk through your new microscope.</li>
<li><strong>Copy the failing record to a sandbox.</strong> Effective, but mind your data-handling policies — anonymize, or shape a synthetic record after the real one.</li>
</ul>
<p>The discipline that matters: <strong>change one variable at a time.</strong> If you flip three flags and replay against a modified payload and it works, you've learned nothing about which of the four changes mattered.</p>
<h2>Step 4: Bisect when you have a suspect range</h2>
<p>If the metrics point at a deploy or a config change, bisect instead of reading code:</p>
<ul>
<li><strong>Deploy bisect.</strong> Step forward or back through versions — or better, if your changes are flag-gated, toggle them off in groups and narrow down. Two or three rounds usually isolate the culprit.</li>
<li><code>git bisect</code><strong>.</strong> Works when you can reproduce in staging or with a test. Automate the check and let git do the walking.</li>
<li><strong>Config diff.</strong> Compare the running configuration against the last known good. Infra changes count as suspects too: DNS records, certificate renewals, dependency upgrades, database migrations, autoscaling limits.</li>
</ul>
<p>My 500-errors bug ended here, embarrassingly: a migration had backfilled a field with a value that one code path treated as valid and another treated as invalid, depending on which cache the request hit first. No single line of code was wrong. The system was, in a way nobody had looked at.</p>
<h2>The checklist I keep open during incidents</h2>
<p>The condensed version of the above, for future me:</p>
<ol>
<li>Mitigate first: rollback, flag off, shed load. Log what you did and when.</li>
<li>Pick one failing request and rebuild its timeline from logs.</li>
<li>Diff it against a healthy request from the same period.</li>
<li>Slice error metrics by deploy, instance, region, tenant, and time.</li>
<li>Find the boundary: when it happens, when it doesn't.</li>
<li>Form one hypothesis. Write it down, including what evidence would disprove it.</li>
<li>Test it with one controlled change: staging replay, shadow mode, or sampled verbose logging.</li>
<li>Bisect deploys, flags, or config when the timing points at a change.</li>
<li>Fix, verify against the original failing case, then re-enable what you disabled.</li>
<li>Write the postmortem while the details are fresh.</li>
</ol>
<h2>After the incident: make the next one easier</h2>
<p>The bug is fixed, but the investigation you just ran is a map of your observability gaps. Every "I wish I could see X" moment is a to-do:</p>
<ul>
<li>Add the log line or metric that would have found this in minutes instead of hours.</li>
<li>Alert on the <em>early</em> signal, not the customer report — in my case, the retry pattern was visible in metrics well before anyone filed a ticket.</li>
<li>Add a canary or synthetic check for the path that broke.</li>
<li>Keep the incident timeline. Six months later, "has anyone seen anything like this?" becomes a search instead of a shrug.</li>
</ul>
<h2>The part I actually believe</h2>
<p>"Reproduce it locally" is a nice-to-have. It's not the prerequisite for debugging — <strong>observability is</strong>. A bug you can't reproduce but can observe is an inconvenience. A bug you can't observe is a mystery, and mysteries are expensive.</p>
<p>Every hour I've spent on structured logging, correlation IDs, tracing, and feature flags has been paid back during some future incident I couldn't predict. The workflow above doesn't require any of it to get started, but each piece makes the next incident shorter.</p>
<p>And the next incident is coming. It always is.</p>
]]></content:encoded></item><item><title><![CDATA[API Design Mistakes That Come Back to Haunt You]]></title><description><![CDATA[Most API design mistakes are free on day one. The endpoint works, the tests pass, the demo goes fine. The bill arrives months later — when you have real…]]></description><link>https://mubert.hashnode.dev/api-design-mistakes-that-come-back-to-haunt-you</link><guid isPermaLink="true">https://mubert.hashnode.dev/api-design-mistakes-that-come-back-to-haunt-you</guid><dc:creator><![CDATA[mubert woo]]></dc:creator><pubDate>Mon, 09 Nov 2026 08:32:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6a9bafc5bb5e5c1a615e1dd6/0728ab04-f8c4-4770-b299-7dfe3c5f2476.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most API design mistakes are free on day one. The endpoint works, the tests pass, the demo goes fine. The bill arrives months later — when you have real data, real users, and a frontend that depends on your mistakes.</p>
<p>These are the mistakes I've watched (and made) that age the worst, with the fixes I'd apply from day one.</p>
<h2>1. Shipping list endpoints without pagination</h2>
<p>Day one: <code>GET /users</code> returns 12 users. Six months later it returns 120,000, and every call drags a database and a mobile app down with it.</p>
<p><strong>The fix:</strong> Every list endpoint gets pagination from the first commit — even if you cap it at 100 "temporarily." Prefer cursor-based pagination (<code>?cursor=...&amp;limit=...</code>) over offset for anything that grows; offsets break when rows are inserted and get slow at depth.</p>
<pre><code class="language-json">{
  "data": ["..."],
  "next_cursor": "eyJpZCI6NDJ9",
  "has_more": true
}
</code></pre>
<h2>2. Leaking internal errors to clients</h2>
<p><code>{"error": "TypeError: Cannot read properties of undefined (reading 'id') at handlers/user.js:42"}</code></p>
<p>Congratulations: you've told every attacker exactly what your stack looks like, and told every frontend developer nothing about what to do.</p>
<p><strong>The fix:</strong> One error envelope, stable machine-readable codes, human-readable messages, and a request ID for support:</p>
<pre><code class="language-json">{
  "error": {
    "code": "USER_NOT_FOUND",
    "message": "No user with id 42",
    "request_id": "req_8fk2"
  }
}
</code></pre>
<h2>3. Launching without a version, "just for now"</h2>
<p>"We'll add /v1 when we need it." You won't. The day you need a breaking change is the day you discover you can't, because three mobile app versions in the wild depend on the current shape.</p>
<p><strong>The fix:</strong> <code>/v1/...</code> from the very first endpoint, even if v1 is the only version that will ever exist. Versioning is cheap on day one and impossible on day 400.</p>
<h2>4. Inconsistent naming across endpoints</h2>
<p><code>userId</code> here, <code>user_id</code> there, <code>id</code> somewhere else, <code>createdAt</code> in one response and <code>created_at</code> in another. Every consumer writes a mapping layer. Every new endpoint starts a debate.</p>
<p><strong>The fix:</strong> Pick one convention (I'd suggest snake_case for JSON, but it genuinely doesn't matter which), write it on one page, and enforce it in code review. Consistency beats taste.</p>
<h2>5. Booleans that will need a third state</h2>
<p><code>is_banned: true/false</code> — until legal asks you to distinguish "banned" from "suspended" from "pending review." Now <code>is_banned</code> is a lie, and every client has logic baked into it.</p>
<p><strong>The fix:</strong> Model states as enums from the start, even when there are only two states today:</p>
<pre><code class="language-json">{ "status": "active" }
</code></pre>
<p>Booleans are for things that are physically binary. Account states are not.</p>
<h2>6. Money as floating point</h2>
<p><code>{"price": 19.99}</code> — and one day your totals are 19.990000000000002 and your accounting is off by cents. Floats cannot represent most decimal fractions exactly. This is not an opinion; it's IEEE 754.</p>
<p><strong>The fix:</strong> Integer minor units (<code>1999</code> cents) or a decimal type. Do all arithmetic in integers, format for display at the edge.</p>
<h2>7. Write endpoints without idempotency</h2>
<p>The user double-clicks "Pay." The mobile app retries on a flaky connection. Now you have two charges and one very angry customer.</p>
<p><strong>The fix:</strong> Accept an <code>Idempotency-Key</code> header on every write that costs money or creates records. Store the first response and return it for duplicates. Combine with unique constraints in the database — the DB is the last line of defense, not the first.</p>
<h2>8. Removing or renaming fields silently</h2>
<p>You rename <code>name</code> to <code>full_name</code> in a refactor, ship it, and three integrations break at once.</p>
<p><strong>The fix:</strong> Additive changes only: add the new field, keep the old one, mark it deprecated in the docs, watch which clients still use it, then remove it — months later, with a version bump. Deleting a field should feel like an event, not a cleanup.</p>
<h2>The pattern behind all of this</h2>
<p>Notice the theme: none of these mistakes hurt when the API is small. They hurt when it's <em>used</em> — which is the goal. So the question for every design decision is: "What does this look like with 100x the data, 100x the clients, and a breaking change I need to make?"</p>
<p>Design for the day the API succeeds. That day comes faster than you think.</p>
]]></content:encoded></item><item><title><![CDATA[Why Your AI App Forgets Things Mid-Conversation (And How to Fix It)]]></title><description><![CDATA[A practical guide to understanding context window limits in LLMs and building apps that stay coherent If you've ever built a chatbot powered by an LLM and…]]></description><link>https://mubert.hashnode.dev/why-your-ai-app-forgets-things-mid-conversation-and-how-to-fix-it</link><guid isPermaLink="true">https://mubert.hashnode.dev/why-your-ai-app-forgets-things-mid-conversation-and-how-to-fix-it</guid><dc:creator><![CDATA[mubert woo]]></dc:creator><pubDate>Sat, 05 Sep 2026 06:44:54 GMT</pubDate><content:encoded><![CDATA[<p><em>A practical guide to understanding context window limits in LLMs and building apps that stay coherent</em></p>
<hr />
<p>If you've ever built a chatbot powered by an LLM and watched it slowly "lose the plot" as a conversation gets longer, you're not alone. The user asks a question, the assistant answers perfectly. Ten messages later, the assistant contradicts something it said three turns ago, or forgets a constraint the user stated at the beginning.</p>
<p>This isn't a bug in your code. It's a fundamental property of how large language models work — and understanding it is the difference between an AI app that feels intelligent and one that feels broken.</p>
<h2>The Problem: Context Windows Are Finite</h2>
<p>Every LLM has a <strong>context window</strong> — a maximum number of tokens it can process in a single request. This window includes everything: the system prompt, the conversation history, the user's new message, and the space reserved for the model's response.</p>
<p>Here are the context window sizes for some widely used models (as of 2025):</p>
<table>
<thead>
<tr>
<th>Model</th>
<th>Context Window</th>
</tr>
</thead>
<tbody><tr>
<td>GPT-4o</td>
<td>128,000 tokens</td>
</tr>
<tr>
<td>Claude 3.5 Sonnet</td>
<td>200,000 tokens</td>
</tr>
<tr>
<td>Gemini 1.5 Pro</td>
<td>1,000,000 tokens</td>
</tr>
<tr>
<td>Llama 3.1 70B</td>
<td>128,000 tokens</td>
</tr>
<tr>
<td>Mistral Large 2</td>
<td>128,000 tokens</td>
</tr>
</tbody></table>
<p>To put this in perspective: 128K tokens is roughly 96,000 words — about the length of a short novel. That sounds like a lot, but it fills up faster than you'd think:</p>
<ul>
<li><p>A system prompt with instructions and persona definition: 500–2,000 tokens</p>
</li>
<li><p>Each user message: 50–500 tokens</p>
</li>
<li><p>Each assistant response: 200–1,000 tokens</p>
</li>
<li><p>Tool call results (e.g., search output, API responses): 500–5,000+ tokens each</p>
</li>
</ul>
<p>A 20-turn conversation with tool use can easily consume 30,000–50,000 tokens. Get into long-running agent workflows with multiple tool calls, and you'll hit the ceiling sooner than expected.</p>
<h2>What Actually Happens When You Exceed the Limit</h2>
<p>There are two common behaviors when a conversation exceeds the context window:</p>
<ol>
<li><p><strong>Hard truncation</strong>: The API silently drops the oldest messages from the conversation. The model has no idea those messages ever existed. This is the most common behavior in production APIs.</p>
</li>
<li><p><strong>Explicit error</strong>: The API returns an error indicating the token limit was exceeded. Your app crashes or shows an error to the user.</p>
</li>
</ol>
<p>Neither is good. The first is worse because it fails silently — the user doesn't know the AI forgot something, and the AI doesn't know it forgot something.</p>
<h2>The Real-World Symptoms</h2>
<p>Before we get to solutions, here's how this problem manifests in practice. If you're seeing any of these, you likely have a context window issue:</p>
<ul>
<li><p><strong>Contradiction</strong>: The model says X at turn 3, then says "not X" at turn 15</p>
</li>
<li><p><strong>Constraint forgetting</strong>: The user said "always respond in JSON" at the start, but by turn 10 the model returns plain text</p>
</li>
<li><p><strong>Repetition</strong>: The model starts repeating information it already provided, as if encountering it for the first time</p>
</li>
<li><p><strong>Personality drift</strong>: A system prompt defining tone and behavior gradually loses influence</p>
</li>
<li><p><strong>Tool misuse</strong>: The model stops calling tools correctly or forgets which tools are available</p>
</li>
</ul>
<h2>Solutions: Five Strategies That Work</h2>
<h3>1. Sliding Window with System Prompt Protection</h3>
<p>The simplest approach: keep only the most recent N messages in the conversation history, but always preserve the system prompt.</p>
<pre><code class="language-python">def build_messages(system_prompt, conversation_history, user_message, max_messages=20):
    messages = [{"role": "system", "content": system_prompt}]
    
    # Keep only the most recent messages
    recent_history = conversation_history[-max_messages:]
    messages.extend(recent_history)
    
    messages.append({"role": "user", "content": user_message})
    return messages
</code></pre>
<p><strong>When to use</strong>: Simple chatbots, short interactions, low-stakes applications.</p>
<p><strong>Limitation</strong>: Anything older than <code>max_messages</code> is permanently forgotten. No recovery.</p>
<h3>2. Conversation Summarization</h3>
<p>Instead of dropping old messages entirely, periodically summarize them and include the summary as a system message.</p>
<pre><code class="language-python">def maybe_summarize(messages, llm_client, threshold=15):
    if len(messages) &lt;= threshold:
        return messages
    
    # Split into old and recent
    old_messages = messages[:-5]
    recent_messages = messages[-5:]
    
    # Generate a summary of the old conversation
    summary_prompt = "Summarize the key facts, decisions, and context from this conversation. Be concise but preserve all important details."
    summary_response = llm_client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "system", "content": summary_prompt}] + old_messages
    )
    
    summary = summary_response.choices[0].message.content
    
    return [
        {"role": "system", "content": f"Previous conversation summary: {summary}"},
        *recent_messages
    ]
</code></pre>
<p><strong>When to use</strong>: Long-running conversations where retaining context matters but exact wording doesn't.</p>
<p><strong>Limitation</strong>: Summarization itself costs tokens and latency. Details can be lost in summarization. Use a smaller/cheaper model for summarization to manage cost.</p>
<h3>3. Token-Aware Truncation</h3>
<p>Instead of counting messages, count actual tokens. This gives you precise control over context usage.</p>
<pre><code class="language-python">import tiktoken

def count_tokens(messages, model="gpt-4o"):
    encoding = tiktoken.encoding_for_model(model)
    total = 0
    for msg in messages:
        # ~4 tokens overhead per message (role, separators)
        total += 4
        for key, value in msg.items():
            total += len(encoding.encode(value))
            if key == "name":
                total += -1  # name role is shorter
    return total

def truncate_to_token_limit(messages, system_prompt, max_tokens=120000, reserve_for_response=4096):
    budget = max_tokens - reserve_for_response - count_tokens([{"role": "system", "content": system_prompt}])
    
    result = [{"role": "system", "content": system_prompt}]
    
    # Work backwards from the most recent messages
    kept = []
    for msg in reversed(messages):
        msg_tokens = count_tokens([msg])
        if budget - msg_tokens &lt; 0:
            break
        kept.insert(0, msg)
        budget -= msg_tokens
    
    result.extend(kept)
    return result
</code></pre>
<p><strong>When to use</strong>: Production applications where you need predictable behavior and cost control.</p>
<p><strong>Limitation</strong>: Still drops old context. Combine with summarization for best results.</p>
<h3>4. Retrieval-Augmented Memory (RAG for Conversation History)</h3>
<p>Store all conversation messages in a vector database. For each new user message, retrieve the most relevant past messages and include them in the context.</p>
<pre><code class="language-python">from datetime import datetime

def store_message(vector_store, message, conversation_id):
    vector_store.add(
        texts=[message["content"]],
        metadatas=[{
            "role": message["role"],
            "conversation_id": conversation_id,
            "timestamp": datetime.now().isoformat()
        }]
    )

def retrieve_relevant_context(vector_store, user_message, conversation_id, top_k=5):
    results = vector_store.similarity_search(
        user_message,
        k=top_k,
        filter={"conversation_id": conversation_id}
    )
    return [{"role": r.metadata["role"], "content": r.page_content} for r in results]
</code></pre>
<p><strong>When to use</strong>: Long-running conversations where specific past details matter (customer support, research assistants, coding helpers).</p>
<p><strong>Limitation</strong>: Adds infrastructure complexity (vector database). Retrieval quality depends on embedding quality and relevance scoring. Not all "relevant" messages are "important" messages.</p>
<h3>5. Hybrid Approach (Recommended for Production)</h3>
<p>Combine the above strategies for robust context management:</p>
<ol>
<li><p><strong>Always</strong> keep the system prompt</p>
</li>
<li><p><strong>Always</strong> keep the last 3–5 messages verbatim (recent context)</p>
</li>
<li><p><strong>Summarize</strong> older messages periodically</p>
</li>
<li><p><strong>Store</strong> all messages in a vector store for on-demand retrieval</p>
</li>
<li><p><strong>Retrieve</strong> relevant past context based on the current user message</p>
</li>
</ol>
<pre><code class="language-python">def build_context_aware_messages(
    system_prompt,
    conversation_history,
    user_message,
    vector_store,
    conversation_id,
    llm_client
):
    messages = [{"role": "system", "content": system_prompt}]
    
    # 1. Retrieve relevant past context
    relevant = retrieve_relevant_context(
        vector_store, user_message, conversation_id, top_k=3
    )
    if relevant:
        context_text = "\n".join([f"[{m['role']}]: {m['content']}" for m in relevant])
        messages.append({
            "role": "system",
            "content": f"Relevant earlier context:\n{context_text}"
        })
    
    # 2. Add summarized history if conversation is long
    if len(conversation_history) &gt; 15:
        summarized = maybe_summarize(conversation_history, llm_client)
        messages.extend(summarized)
    else:
        messages.extend(conversation_history)
    
    # 3. Add current user message
    messages.append({"role": "user", "content": user_message})
    
    # 4. Token-aware truncation as safety net
    messages = truncate_to_token_limit(messages, system_prompt)
    
    return messages
</code></pre>
<h2>A Common Pitfall: System Prompt Erosion</h2>
<p>One subtle issue developers miss: as conversations grow longer, the system prompt's influence weakens. This isn't because the model "forgets" the system prompt — it's still in the context. The issue is <strong>attention dilution</strong>.</p>
<p>In transformer-based models, attention is distributed across all tokens in the context. As the conversation grows, the system prompt's tokens receive less relative attention. This is why a model that was politely refusing off-topic requests at turn 2 might comply with them at turn 20.</p>
<p><strong>Mitigation</strong>: Re-inject key constraints as a system message midway through long conversations:</p>
<pre><code class="language-python">def reinforce_constraints(messages, constraints, every_n_turns=10):
    if len(messages) % every_n_turns == 0:
        messages.insert(-1, {
            "role": "system",
            "content": f"Reminder — follow these rules: {constraints}"
        })
    return messages
</code></pre>
<h2>Measuring Context Usage</h2>
<p>Most LLM API providers return token usage in their responses. Use this to monitor how close you are to the limit:</p>
<pre><code class="language-python">response = llm_client.chat.completions.create(
    model="gpt-4o",
    messages=messages
)

usage = response.usage
print(f"Prompt tokens: {usage.prompt_tokens}")
print(f"Completion tokens: {usage.completion_tokens}")
print(f"Total tokens: {usage.total_tokens}")
print(f"Context utilization: {usage.prompt_tokens / 128000 * 100:.1f}%")
</code></pre>
<p>In production, log this metric and set alerts when utilization exceeds 70%. This gives you time to intervene before hitting the hard limit.</p>
<h2>Choosing the Right Strategy for Your App</h2>
<table>
<thead>
<tr>
<th>App Type</th>
<th>Recommended Strategy</th>
<th>Why</th>
</tr>
</thead>
<tbody><tr>
<td>Simple FAQ bot</td>
<td>Sliding window (1)</td>
<td>Short conversations, low stakes</td>
</tr>
<tr>
<td>Customer support chatbot</td>
<td>Summarization + RAG (2+4)</td>
<td>Needs to recall specific details</td>
</tr>
<tr>
<td>Coding assistant</td>
<td>Hybrid (5)</td>
<td>Long sessions, code context matters</td>
</tr>
<tr>
<td>Research assistant</td>
<td>Hybrid (5)</td>
<td>Extended conversations, cross-referencing</td>
</tr>
<tr>
<td>Quick one-shot tool</td>
<td>None needed</td>
<td>Single-turn, no history</td>
</tr>
</tbody></table>
<h2>Key Takeaways</h2>
<ul>
<li><p><strong>Context windows are finite</strong> — know your model's limit and plan for it</p>
</li>
<li><p><strong>Silent truncation is the enemy</strong> — don't let your app forget things without you knowing</p>
</li>
<li><p><strong>Summarization is your best friend</strong> for long conversations — it's cheaper than you think</p>
</li>
<li><p><strong>RAG isn't just for documents</strong> — it works for conversation history too</p>
</li>
<li><p><strong>System prompts erode</strong> in long conversations — reinforce them periodically</p>
</li>
<li><p><strong>Measure token usage</strong> in production — you can't manage what you don't monitor</p>
</li>
</ul>
<p>The gap between a toy AI app and a production-grade one often isn't about the model you choose — it's about how well you manage the context the model sees. Get this right, and your users will notice.</p>
]]></content:encoded></item></channel></rss>