<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hamzaaliics on Medium]]></title>
        <description><![CDATA[Stories by Hamzaaliics on Medium]]></description>
        <link>https://medium.com/@hamzaaliics?source=rss-d4839cebae07------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UMDVh4TLW944YOEa</url>
            <title>Stories by Hamzaaliics on Medium</title>
            <link>https://medium.com/@hamzaaliics?source=rss-d4839cebae07------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:29:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamzaaliics/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Built 2FA From Scratch With Zero Auth Libraries. Here’s How Those 6 Digits Actually Work.]]></title>
            <link>https://medium.com/@hamzaaliics/i-built-2fa-from-scratch-with-zero-auth-libraries-heres-how-those-6-digits-actually-work-40026a93982a?source=rss-d4839cebae07------2</link>
            <guid isPermaLink="false">https://medium.com/p/40026a93982a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Hamzaaliics]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 06:43:00 GMT</pubDate>
            <atom:updated>2026-11-17T06:43:00.756Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A shared secret, a shared clock, and 40 lines of Node. Plus the hardening most tutorials skip.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pCSA5MuuG3ORZFj9LFYwA.png" /></figure><p>Put your phone in airplane mode. Open your authenticator app. It still shows a six-digit code, and the server will still accept it.</p><p>Your phone and that server have not exchanged a single byte since the day you scanned the QR code. So how do they agree on the same number, every 30 seconds, forever?</p><p>Last week I shipped two-factor authentication for a payroll admin tool I maintain. I wrote the whole TOTP engine by hand on Node’s built-in crypto module. No otplib, no speakeasy.</p><p>The code generator took an afternoon. The hardening around it took the rest of the week. This post covers both: how the six digits work, byte by byte, and the security details that separate a demo from something you can put in front of payroll data.</p><h3>Why not just npm install a 2FA library?</h3><p>Two reasons, and neither is “libraries are bad.”</p><p><strong>The codebase already works this way.</strong> This app hand-rolls its security plumbing on Node’s crypto: scrypt for passwords, CSRF tokens, session hashing. A heavy auth dependency would have been the odd one out. TOTP is a small, stable spec (<a href="https://datatracker.ietf.org/doc/html/rfc6238">RFC 6238</a>), so it fit the same style.</p><p><strong>I wanted to understand what guards my users.</strong> This 2FA protects who gets paid and who can approve payments. I did not want a black box sitting on top of that.</p><p>One clarification before the comments arrive: I did not write my own cryptography. HMAC, SHA-1 and AES all come from Node’s standard library. I wrote the protocol on top of them, which is a much smaller thing to get right.</p><p>The only package I added was qrcode.react, purely to draw the QR image in the browser.</p><h3>How TOTP works: a shared secret and a shared clock</h3><p>The phone and the server share exactly two things: a secret, and the time. Everything else is arithmetic.</p><p><strong>Step 1: the secret is shared once, through the QR code.</strong> At setup the server generates random bytes (the HOTP spec, <a href="https://datatracker.ietf.org/doc/html/rfc4226">RFC 4226</a>, recommends 160 bits) and puts them in a URI the authenticator app understands:</p><pre>otpauth://totp/Payroll:hamza@example.com?secret=GEZDGNBVGY3TQOJQ...&amp;issuer=Payroll</pre><p>The QR code is just that string as an image. The app scans it and stores the secret. That is the last time the two sides ever talk.</p><p><strong>Step 2: both sides turn the clock into a counter.</strong> Take Unix time in seconds, divide by 30, drop the remainder. Every device on Earth with a correct clock gets the same integer for the same 30-second window.</p><pre>const step = Math.floor(Date.now() / 1000 / 30);</pre><p><strong>Step 3: both sides run the same function.</strong> HMAC the counter with the secret, then squeeze the result down to six digits.</p><pre>import { createHmac } from &quot;node:crypto&quot;;</pre><pre>function hotp(secret: Buffer, counter: number, digits = 6): string {<br>  const msg = Buffer.alloc(8);<br>  msg.writeBigUInt64BE(BigInt(counter));          // counter as 8 big-endian bytes</pre><pre>  const mac = createHmac(&quot;sha1&quot;, secret).update(msg).digest(); // 20 bytes</pre><pre>  const offset = mac[mac.length - 1] &amp; 0x0f;      // dynamic truncation<br>  const bin = mac.readUInt32BE(offset) &amp; 0x7fffffff;</pre><pre>  return (bin % 10 ** digits).toString().padStart(digits, &quot;0&quot;);<br>}</pre><pre>const totp = (secret: Buffer) =&gt; hotp(secret, Math.floor(Date.now() / 1000 / 30));</pre><p>That is the entire generator. TOTP is HOTP with the clock as the counter.</p><p><strong>Step 4: verification is recomputation.</strong> When the user types a code, the server runs the same function with the stored secret and the current time, then compares. There is no table of issued codes and no round trip to the phone.</p><p>The analogy I like: a secret recipe, shared once, plus an ingredient that changes every 30 seconds. Same recipe, same ingredient, same dish, in two kitchens that never call each other.</p><h3>The part tutorials skip: how 20 bytes become 6 digits</h3><p>Most explanations stop at “truncate to 6 digits.” The truncation is the clever bit, so here it is with real numbers from the RFC’s own test case: the ASCII secret 12345678901234567890 at Unix time 59, which is counter 1.</p><ol><li>HMAC-SHA1 returns 20 bytes: 75a48a19 d4cbe100 644e8ac1 397eea74 7a2d33ab</li><li>Look at the last byte, ab. Its low four bits are b, which is 11. That is the offset.</li><li>Read four bytes starting at position 11: c1 39 7e ea</li><li>Clear the top bit so the number is never negative on any platform: 41 39 7e ea, which is 1,094,287,082.</li><li>Keep the last six digits: <strong>287082</strong></li></ol><p>The offset comes from the hash itself, so an observer cannot predict which four bytes get used. And because HMAC is one-way, seeing a thousand codes tells an attacker nothing about the secret or the next code.</p><p>A common question: isn’t SHA-1 broken? Its collision resistance is. HMAC does not rely on collision resistance, and SHA-1 is what every authenticator app supports by default. Switching to SHA-256 is allowed by the RFC, but some apps silently ignore that parameter and show wrong codes.</p><h3>The codes are the easy part. The hardening is the job.</h3><p>Writing it myself meant I could not assume a library had handled the dangerous edges. I worked through the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html">OWASP Multifactor Authentication Cheat Sheet</a> line by line. This is what made it into the build.</p><p><strong>Encrypt the secret at rest.</strong> A TOTP secret is password-equivalent: anyone holding it can mint valid codes forever. Unlike a password it cannot be hashed, because the server needs the original bytes to compute the expected code. I encrypt it with AES-256-GCM using a key from the environment, and decrypt only at the moment of verification.</p><pre>function encrypt(plain: Buffer, key: Buffer): Buffer {<br>  const iv = randomBytes(12);                       // fresh nonce every time<br>  const cipher = createCipheriv(&quot;aes-256-gcm&quot;, key, iv);<br>  const ct = Buffer.concat([cipher.update(plain), cipher.final()]);<br>  return Buffer.concat([iv, cipher.getAuthTag(), ct]);<br>}</pre><p>GCM’s auth tag means a tampered row fails to decrypt instead of quietly producing a different secret.</p><p><strong>Compare in constant time.</strong> === on strings can return as soon as it finds a mismatch, and that timing difference is a signal. I use timingSafeEqual and check every candidate step without returning early.</p><p><strong>Keep the time window narrow.</strong> I accept the previous, current and next 30-second step, which covers clock drift and slow typing. OWASP’s guidance is stricter still: the current step and at most one previous. Every extra step you accept is one more valid code an attacker can hit.</p><p><strong>Rate-limit the codes.</strong> Six digits is 1,000,000 possibilities. With three steps accepted, each guess has a 3-in-a-million chance. I reuse the password lockout: 5 wrong attempts, then a 15-minute lock. Without a limit, a script walks the whole space in minutes.</p><p>Be honest about what a lockout buys. At 5 tries per 15 minutes, an attacker who already has the password gets 480 guesses a day, roughly a 0.14% daily chance. A lockout slows the attack. Alerting the user after repeated lockouts is what ends it.</p><p><strong>Turn 2FA on only after the first code verifies.</strong> A user who scans the QR badly, or closes the tab halfway, must not end up locked out by a secret their phone never stored.</p><p><strong>Single-use backup codes, stored as hashes.</strong> These cover the lost-phone case. Each one works once.</p><p><strong>Step up to disable.</strong> Turning 2FA off requires a fresh code. An active session is not enough, because a session can be hijacked.</p><p><strong>Never log secrets or codes.</strong> Not in request logs, not in error traces, not in analytics.</p><h3>The rule a stateless verifier breaks: one code, one use</h3><p>A TOTP code stays mathematically valid for its whole window. If the server only recomputes and compares, a code that worked once will work again 10 seconds later, for anyone who saw it over a shoulder or in a proxy log.</p><p><a href="https://datatracker.ietf.org/doc/html/rfc6238#section-5.2">RFC 6238, section 5.2</a> closes this: once a code has been accepted, the verifier must not accept it a second time. A pure function cannot enforce that, because it remembers nothing between calls. This is a common gap in hand-rolled and library-based setups alike.</p><p>The fix is one column. Store the last accepted time step per user and reject anything at or below it.</p><pre>import { timingSafeEqual } from &quot;node:crypto&quot;;</pre><pre>function verifyTotp(secret: Buffer, input: string, lastUsedStep: number): number | null {<br>  if (!/^\d{6}$/.test(input)) return null;</pre><pre>  const current = Math.floor(Date.now() / 1000 / 30);<br>  let matched: number | null = null;</pre><pre>  for (const step of [current - 1, current, current + 1]) {<br>    const expected = Buffer.from(hotp(secret, step));<br>    if (timingSafeEqual(expected, Buffer.from(input))) matched = step; // no early return<br>  }</pre><pre>  if (matched === null || matched &lt;= lastUsedStep) return null;         // wrong, or replayed<br>  return matched;                                                       // persist as lastUsedStep<br>}</pre><p>Save the returned step in the same atomic update that completes the login, so two parallel requests cannot both win with one code.</p><h3>The login flow: a “pending” session</h3><p>A clean pattern fell out of code that already existed. The app had a gate for “you logged in with a temporary password, change it before doing anything else.” I mirrored it for 2FA.</p><ol><li>The password is correct, so a session is created, but marked pending.</li><li>While pending, every route is blocked except “submit your code.”</li><li>A valid code upgrades the session to a full one.</li></ol><p>No new session machinery. One more gate on a mechanism that was already proven in production. The important property: a correct password alone never yields a session that can touch payroll data.</p><h3>How do you test security code you wrote yourself?</h3><p>You do not trust yourself. You trust the spec’s own answers.</p><p>RFC 6238 publishes known-answer test vectors: a fixed secret and the exact code it must produce at specific timestamps. With the secret 12345678901234567890 and SHA-1:</p><p>Unix time Expected 8-digit code</p><p>59 94287082</p><p>1111111109 07081804</p><p>1234567890 89005924</p><p>2000000000 69279037</p><p>20000000000 65353130</p><p>If your function reproduces these, it computes the same math as Google Authenticator, Authy and 1Password. Mine does. The last row matters more than it looks: that timestamp does not fit in 32 bits, so it catches code that handles time as a 32-bit integer, a bug that would otherwise surface in 2038.</p><p>Vectors prove the generator. They say nothing about the lockout, the replay check or the pending session. For those I wrote a browser-level end-to-end test that drives the real UI against a real server: enrol, compute a code from the secret, enter it, get in. Then the negative cases: wrong code, reused code, sixth attempt.</p><h3>What TOTP will not save you from</h3><p>Building it also showed me where it ends.</p><p><strong>Phishing.</strong> TOTP proves someone knows the current code. It does not prove they are typing it into the real site. A reverse-proxy phishing page can relay a live code within its window. OWASP describes TOTP as susceptible to phishing for this reason, and points to passkeys, which bind the login to the genuine origin.</p><p><strong>A stolen database plus a stolen key.</strong> Encryption at rest only helps if the key lives somewhere the database dump does not. A KMS or HSM is the stronger version of my environment variable.</p><p><strong>Weak recovery.</strong> Every “I lost my phone” path is also a path for an attacker. Backup codes and admin resets deserve the same scrutiny as the login itself.</p><p>And a fair warning on the title. “No library” was right here because the spec is small and stable, the primitives come from the standard library, and the RFC ships test vectors. If any of those were missing, I would have installed the library.</p><h3>What I took away</h3><ul><li><strong>TOTP is smaller than it looks.</strong> A shared secret, a shared clock and one HMAC. The generator fits on a phone screen.</li><li><strong>The codes are 10% of the work.</strong> Encryption at rest, constant-time comparison, replay protection, rate limits and recovery are the other 90%, and they are where implementations differ.</li><li><strong>“No library” is sometimes the senior choice.</strong> When the spec is small, the code is security-critical and the codebase values explicitness, owning 40 lines beats trusting 4,000.</li><li><strong>Test against the spec, not against yourself.</strong> Known-answer vectors turn “I think it works” into “it matches the standard.”</li></ul><p>If you have only ever used 2FA, implement it once, even in a throwaway project. You will not look at those six digits the same way again.</p><p>Have you hand-rolled a piece of auth, or do you think that is always a mistake? Tell me in the comments. I read all of them.</p><p><em>Built with Node.js, TypeScript and a lot of respect for RFC 6238.</em></p><h3>Sources</h3><ul><li><a href="https://datatracker.ietf.org/doc/html/rfc6238">RFC 6238: TOTP, Time-Based One-Time Password Algorithm</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc4226">RFC 4226: HOTP, An HMAC-Based One-Time Password Algorithm</a></li><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html">OWASP Multifactor Authentication Cheat Sheet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40026a93982a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG in Production: The Gap Between a Working Demo and a System You Can Ship.]]></title>
            <link>https://medium.com/@hamzaaliics/rag-in-production-the-gap-between-a-working-demo-and-a-system-you-can-ship-431cec0f15a2?source=rss-d4839cebae07------2</link>
            <guid isPermaLink="false">https://medium.com/p/431cec0f15a2</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hamzaaliics]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 10:57:49 GMT</pubDate>
            <atom:updated>2026-11-13T10:57:49.591Z</atom:updated>
            <content:encoded><![CDATA[<h3><em>Naive retrieval gets you a working demo in an afternoon. Making it reliable enough to put in front of real users is a different problem entirely. Here’s what the gap actually looks like — and how I’ve learned to close it building RAG chatbots for clients.</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUrUmJyjQyGklz3E6fzk3g.png" /></figure><h3>The pipeline everyone starts with</h3><p>The first RAG system you build is almost always the same four steps, and it feels like magic because it works on the first try.</p><p>You take your documents and split them into chunks. You run each chunk through an embedding model and get back a vector — a list of numbers that captures roughly what the text means. You store those vectors in a vector database. That is the whole offline half of the system, and you only do it once (or whenever your data changes).</p><p>Then at query time you mirror it: embed the user’s question with the same model, find the chunks whose vectors sit closest to the question’s vector, paste those chunks into the prompt as context, and let the model answer using them.</p><p>That is it. Embed, retrieve, generate. In an afternoon you have a chatbot that answers questions about your own documents, and the first few questions you throw at it come back looking great. This is the moment most tutorials end, and it is exactly why so many RAG projects stall — because the demo is the easy 20%, and nobody warns you about the other 80%.</p><p>I have shipped versions of this pipeline for client chatbots more times than I can count. It is a genuinely good starting point. The problem is never getting it to work once. The problem is getting it to keep working when real users ask real questions.</p><h3>Where it breaks</h3><p>The failures are not random. They come from three structural weaknesses baked into the naive pipeline, and once you know what to look for you see them everywhere.</p><p><strong>Chunking throws away context.</strong> When you split documents at a fixed token count, you slice straight through the middle of a thought. A definition ends up in one chunk and the thing it defines in the next. A table gets severed from its heading. The embedding of a half-sentence is a poor representation of anything, so retrieval quietly degrades — and because the demo questions happened to land on clean chunks, you never saw it coming.</p><p><strong>Embedding similarity is not relevance.</strong> Two pieces of text can sit close together in vector space while having nothing to do with the user’s actual question. Vector search is good at “this is about the same topic” and bad at “this is the specific answer.” It also tends to miss exact keyword matches — a product code, an error string, a person’s name — because those carry meaning that semantic similarity flattens out.</p><p><strong>One shot, no feedback.</strong> Naive RAG retrieves once and commits. If the user’s question is vague, or phrased differently from how your documents phrase the answer, you get bad context — and the model never finds out. There is no step that asks “is what I just retrieved actually good enough to answer this?” before it starts generating. So the model does what models do with weak context: it fills the gaps confidently, and now you have a hallucination wearing the costume of a grounded answer.</p><p>The trap here is that all three of these are invisible in a demo and obvious in production. Most teams respond by fiddling with the knobs — a different chunk size, a new embedding model, a higher top-k. It helps a little. It never fixes the actual problem, because the problem is the shape of the pipeline, not its settings.</p><h3>The upgrades that actually moved the needle</h3><p>These are not exotic research techniques. They are the handful of changes that reliably take a RAG system from “works sometimes” to “works.” I reach for them in roughly this order.</p><p><strong>Hybrid retrieval.</strong> Instead of relying on vector search alone, run a keyword search (BM25, the algorithm behind classic search engines) in parallel and fuse the two result lists. Vector search catches meaning; keyword search catches the exact terms that vectors blur — codes, names, acronyms. Together they recover documents that either method alone would miss. Most vector databases and search engines support this out of the box, and it is the single highest-leverage change you can make for the least effort. If you only do one thing on this list, do this.</p><p><strong>Reranking.</strong> Hybrid retrieval gives you a bigger, noisier candidate set. A cross-encoder reranker then reads each candidate <em>together with</em> the query and scores how well it actually answers — real attention, not just vector distance. The pattern that works: retrieve a wide net of candidates, rerank, keep only the top few for the prompt. It is more expensive per query, so you run it on a small set, but it consistently lifts answer quality and it is the standard second stage in any serious pipeline.</p><p><strong>Query transformation.</strong> The user’s raw question is often a bad search key — too short, too vague, or worded nothing like your documents. Two fixes I use constantly: rewriting the question into a better retrieval query, and for multi-part questions, decomposing it into sub-questions that each retrieve their own context. A technique worth knowing is HyDE (Hypothetical Document Embeddings, from Gao et al.): instead of embedding the short question, you ask the model to draft a hypothetical answer first, then embed <em>that</em> — because a full fake answer sits closer in vector space to the real answer than a terse query does.</p><p><strong>Smarter chunking.</strong> Since fixed-size chunking caused half the pain in the first place, fixing it pays off directly. Parent-child chunking retrieves small precise chunks but hands the model the larger surrounding section for context. Semantic chunking splits on natural boundaries — headings, paragraph breaks, topic shifts — instead of blind token counts. Overlapping windows stop information from falling through the cracks between chunks. The right choice depends on your corpus: clean docs like semantic splitting, dense manuals like parent-child, messy conversational data likes overlap.</p><p>None of these is a rewrite. Each is a bolt-on to the pipeline you already have, and you can add them one at a time while measuring the effect — which, as the next section argues, is the part most people skip.</p><h3>When retrieval becomes a loop</h3><p>Everything so far — even the advanced version — is still a fixed pipeline. Transform, retrieve, rerank, generate, in that order, every time. Agentic RAG breaks that line.</p><p>The idea is to stop treating retrieval as a fixed step and start treating it as a <em>tool</em> the model can choose to use. Instead of a pipeline, you give an agent a loop: it reads the question, decides whether and what to retrieve, looks at what came back, and decides what to do next — retrieve again with a better query, search a different source, or go ahead and answer. Reasoning and retrieval interleave instead of running in a fixed sequence.</p><p>Three things this unlocks that a straight pipeline cannot:</p><p><strong>Self-correction.</strong> The agent can judge its own retrieved context — using the model itself as a grader — and if it is weak, retry with a different query before generating. This closes the feedback gap that naive RAG leaves wide open, and it is the core idea behind approaches like Self-RAG and Corrective RAG. In practice it is the biggest single lever on hallucination rate.</p><p><strong>Multi-source routing.</strong> If your knowledge lives in different places — product docs, support tickets, an API reference — you do not have to dump it all into one index. You keep them separate and let the agent pick. A question about rate limits goes to the API docs; a question about a specific customer goes to the CRM. The routing decision becomes part of the reasoning.</p><p><strong>Multi-hop questions.</strong> Questions that need several facts chained together — retrieve A, use it to figure out what to retrieve next — are exactly what a loop handles and a single-shot pipeline cannot.</p><p>The honest tradeoff: every one of those decisions is another model call. Agentic RAG is slower and more expensive than a pipeline, and it is harder to debug because the path changes per question. I do not reach for it by default. I reach for it when the questions are genuinely complex or the knowledge is genuinely scattered — and for a simple FAQ bot, it is overkill you will regret paying for.</p><h3>Evaluate retrieval and generation separately</h3><p>This is the thing I wish someone had told me before my first production build, so I will put it plainly: a RAG system has two halves that fail for different reasons, and if you measure them together you will spend days fixing the wrong one.</p><p><strong>Retrieval quality</strong> asks: did we fetch the right documents? You measure it with metrics like recall at k (what fraction of the genuinely relevant chunks showed up in the top results) and how high the first good result ranked. This has nothing to do with the language model — it is purely about whether your search found the right material.</p><p><strong>Generation quality</strong> asks: given the documents we fetched, did the model use them well? The key one is faithfulness — is every claim in the answer actually supported by the retrieved context, or did the model wander off and invent things? The other is relevance — did it actually answer what was asked?</p><p>Why the split matters is entirely practical. If retrieval recall is high but faithfulness is low, your search is fine and your <em>prompt</em> is the problem — the model has good context and is ignoring it. If faithfulness is high but recall is low, your generation is solid and your <em>retrieval</em> needs work — the model is doing its best with bad material. Same bad answer on the surface, opposite fixes underneath. Tools like RAGAS and DeepEval will compute both sets of metrics for you, but the mindset matters more than the tool: build a small evaluation set of real questions with known good answers, and score the two halves independently before you touch anything.</p><p>Most “RAG isn’t working” problems I have been called in to debug were really “nobody knows which half is broken” problems.</p><h3>When not to reach for RAG</h3><p>RAG has become the reflex answer to “my model doesn’t know X,” and sometimes that reflex is wrong. Three cases where I have seen teams build a retrieval pipeline they did not need:</p><p><strong>When the problem is behavior, not knowledge — fine-tune.</strong> If the model knows the facts but gets the <em>format</em> wrong, the <em>tone</em> wrong, or the classification inconsistent, retrieval will not help. That is a behavioral problem, and fine-tuning is the right tool — it teaches style, policy, and decision patterns. The flip side is also true: do not fine-tune for facts that change weekly. Fine-tuning bakes knowledge into weights; updating it means retraining. Fine-tune for <em>how</em> the model behaves, use RAG for <em>what</em> it knows.</p><p><strong>When everything fits in the context window — just prompt it.</strong> If your entire knowledge base is small — a product manual, a policy doc, a handful of pages — you may not need retrieval infrastructure at all. Put the whole thing in the prompt and cache it. It is simpler, often cheaper, and frequently more accurate than a retrieval pipeline, because there is no retrieval step to get wrong. One caveat worth knowing: models are weaker at using information buried in the <em>middle</em> of a long context than at the start or end, so this stops being reliable as the corpus grows.</p><p><strong>When the questions are relational — reach for a graph.</strong> Vector similarity cannot answer “which customers in this region use product X and also filed a support ticket last month.” That is a relationship query, and it needs structured data. Knowledge graphs — and GraphRAG, which Microsoft open-sourced — handle multi-hop relational reasoning that pure vector search fundamentally cannot. The cost is the upfront modeling work to build the graph, so it is worth it only when your questions are genuinely relational.</p><p>The meta-point: RAG is one tool, not the whole toolbox. Knowing when to walk past it is a sign you understand it, not a sign you are avoiding it.</p><h3>What I’d tell myself before the first build</h3><p>If I could hand my earlier self a short list before the first production RAG project, it would be this:</p><p>The demo is the easy part, and it is lying to you about how close you are to done. Budget most of your effort for the gap between “works on my test questions” and “works on whatever users type.”</p><p>Add hybrid retrieval and a reranker before you touch anything fancy — they are the cheapest, biggest wins, and most pipelines are quietly broken without them.</p><p>Fix chunking early, because bad chunks poison everything downstream and no amount of clever retrieval saves a corpus that was sliced through the middle of every idea.</p><p>Reach for agentic RAG when the questions actually demand it, not because it is the interesting thing to build. A loop you do not need is just latency and cost.</p><p>Measure retrieval and generation separately, from day one, on a small set of real questions. It is the difference between debugging with a flashlight and debugging in the dark.</p><p>And know when not to use RAG at all. Half the maturity in this field is recognizing the problem in front of you is actually a fine-tuning problem, a long-context problem, or a graph problem wearing a RAG costume.</p><p>None of this is about chasing the newest technique. It is about understanding where a retrieval system loses information at each step and closing those gaps one at a time. Do that, and the jump from a demo that impresses to a system you can actually ship stops feeling like luck.</p><p><em>I build production-ready AI chatbots for a living — RAG systems on OpenAI and LangChain, grounded in your own data instead of hallucinating around it. If that’s something you need, this is exactly what I do on Fiverr:</em> <strong>“</strong><a href="https://www.fiverr.com/s/9dGoGlD">https://www.fiverr.com/s/9dGoGlD</a><strong>”</strong> <em>Happy to talk through your use case.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=431cec0f15a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Stopped Trusting Our LLM’s Memory. Our AI Product Got Better.]]></title>
            <link>https://medium.com/@hamzaaliics/we-stopped-trusting-our-llms-memory-our-ai-product-got-better-565a70090338?source=rss-d4839cebae07------2</link>
            <guid isPermaLink="false">https://medium.com/p/565a70090338</guid>
            <category><![CDATA[llm-memory]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[why-x-fails-in-production]]></category>
            <category><![CDATA[production-rag]]></category>
            <dc:creator><![CDATA[Hamzaaliics]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 11:52:45 GMT</pubDate>
            <atom:updated>2026-11-10T11:58:57.617Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The most important code in our AI product isn’t the AI code.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ZNSyNY5uLwIbWmeIMzGkQ.png" /></figure><p>For three weeks, our AI assistant kept suggesting meditation to a user who had disliked it four times.</p><p>Not a bug. Not a prompt issue. The LLM just… forgot. Each night it synthesized a “fresh” memory summary that quietly dropped the dislike, and then generated a task from a clean slate.</p><p>That was the moment we realized something that doesn’t get talked about enough in LLM-powered products:</p><p><strong>You cannot trust an LLM to be the source of truth for anything that must stay true.</strong></p><p>This is a post about the architecture we built to work around that — and why the most valuable code in our AI engine isn’t the AI code.</p><h3>The Product That Broke Our Architecture</h3><p>PersonAI is a life-organization assistant. Users pick the areas of their life they care about — Work, Wellness, Family, Finances — and the app generates personalized daily tasks, nudges, and a morning notification, based on their actual behavior.</p><p>The key word is <em>personalized</em>. If you complete “10-minute walk” three days in a row, the AI should notice. If you dismiss “journal before bed” twice, it should stop suggesting it. If you <em>dislike</em> “meditate,” it should never suggest it again. Ever.</p><p>Simple promise. Hard engineering.</p><h3>The Naive Version (That Kinda Worked, Until It Didn’t)</h3><p>Our first version was what you’d expect: a daily cron job, a GPT-4o call with the user’s feedback shoved into the prompt, and a parsed list of tasks coming back.</p><p>It worked in demos. It worked for users with a week of data. It fell apart when a user had two months of history.</p><p>Three things broke:</p><ol><li><strong>Context bloat.</strong> Months of feedback in every prompt exploded token costs and hit model limits.</li><li><strong>Memory drift.</strong> Compressing history into a running summary meant the LLM “helpfully” rewrote it each night — sometimes dropping facts that mattered.</li><li><strong>Repetition.</strong> Same suggestions came back over and over, even when the user had explicitly rejected them.</li></ol><p>The last one was the worst. Nothing kills trust in an AI product faster than it ignoring what you told it.</p><h3>The Architectural Shift: Two Services, One Database</h3><p>The first real decision was to split the AI logic out of the main backend entirely.</p><ul><li><strong>NestJS backend</strong> — system of record. Auth, billing, DB writes, scheduling.</li><li><strong>Python FastAPI engine</strong> — the “brain.” All LLM calls, CrewAI multi-agent orchestration, behavioral memory.</li></ul><p>Both services share the same PostgreSQL database, but with strict ownership: NestJS owns the task table, the engine owns the behavioral profile table. Neither writes to the other’s domain.</p><p>Sounds like premature complexity. It’s not. <strong>Your AI logic iterates 10× faster than your business logic.</strong> Keeping them in separate deployable services means a prompt tweak doesn’t risk breaking auth, and a billing fix doesn’t require touching the engine.</p><p>Shared DB, split ownership. One of the best decisions we made.</p><h3>Three Layers of Memory, Held Together by Python</h3><p>Here’s where the real learning happened.</p><p>We used to have one behavioral summary — a single blob of text the LLM maintained. It drifted. Badly.</p><p>We split it into three structured sections:</p><ul><li><strong>lifestyle_context</strong> — factual diary of daily routine</li><li><strong>likes_engagement</strong> — what the user enjoys, with time-of-day context</li><li><strong>dislikes_avoidance</strong> — what to avoid, tagged with intensity</li></ul><p>Each section gets its own LLM crew with its own prompt and guardrails. And every line is tagged:</p><ul><li><strong>[stable]</strong> — seen ≥3 times over ≥2 weeks, engaged with</li><li><strong>[recent]</strong> — observed but not yet confirmed</li><li><strong>[fading]</strong> — was stable, now absent</li></ul><p>The tags matter because when the LLM writes the next summary, it can see which patterns are proven vs. provisional. It stops over-fitting to a single day.</p><p>But tags alone didn’t fix the drift. That took something else entirely.</p><h3>The Insight That Took Longest to Internalize</h3><p><strong>LLMs are great at synthesis. They are terrible at invariants.</strong></p><p>A rule like “if the user dislikes X, never suggest X again” is an invariant. It’s not creative. It doesn’t need interpretation. And yet, every single time we trusted the LLM to respect it, it eventually didn’t.</p><p>The fix: deterministic Python post-processing on top of every LLM memory write.</p><p>python</p><pre>def _carry_forward_dislikes(previous_memory: str, new_memory: str) -&gt; str:<br>    &quot;&quot;&quot;LLMs forget. Dislikes must not.&quot;&quot;&quot;<br>    prev_dislikes = extract_dislikes(previous_memory)<br>    new_dislikes = extract_dislikes(new_memory)</pre><pre>    # Union — never a diff. Dislikes only leave when the user says so.<br>    merged = dedupe(prev_dislikes + new_dislikes)</pre><pre>    return replace_dislikes_section(new_memory, merged)<br></pre><pre>def _enforce_stable_gate(memory: str, counts: dict[str, int]) -&gt; str:<br>    &quot;&quot;&quot;LLM can suggest [stable]. Python decides if it actually is.&quot;&quot;&quot;<br>    for line in extract_tagged_lines(memory, tag=&quot;stable&quot;):<br>        habit = parse_habit(line)<br>        if counts.get(habit, 0) &lt; STABLE_THRESHOLD:<br>            memory = downgrade_tag(memory, line, to=&quot;recent&quot;)<br>    return memory</pre><p>The LLM can <em>suggest</em> that something is stable. Only Python decides if it actually is. The LLM can <em>propose</em> a new memory. Only Python decides whether a dislike gets to be forgotten (it doesn’t).</p><p>The pattern generalizes:</p><blockquote>LLMs for creativity and synthesis. Code for anything that must stay true.</blockquote><p>If you’re building any AI product with a memory layer, write this on a sticky note.</p><p>Result: <strong>memory drift incidents dropped to zero.</strong> A dislike recorded in January is still in the prompt in November.</p><h3>Three Layers of Dedup (Because One Doesn’t Work)</h3><p>Memory alone wasn’t enough. Even with dislikes locked down, the LLM would generate near-duplicates — “Go for a morning walk” vs. “Take a brisk walk in the AM.”</p><p>So we built three dedup layers. Each catches what the one before misses:</p><p>python</p><pre>async def dedupe_candidates(candidates: list[Task], blocked: list[Task]) -&gt; list[Task]:<br>    survivors = []<br>    for task in candidates:<br>        # Layer 1 — exact title ban list (free, instant)<br>        if task.title.lower() in {b.title.lower() for b in blocked}:<br>            continue</pre><pre>        # Layer 2 — semantic dedup via embeddings<br>        sim = max_similarity(task.embedding, [b.embedding for b in blocked])<br>        if sim &gt;= 0.62:<br>            continue</pre><pre>        # Layer 3 — LLM topic judge (only for the grey band)<br>        if 0.30 &lt;= sim &lt; 0.62:<br>            if await llm_same_habit_judge(task, closest_blocked(task, blocked)):<br>                continue</pre><pre>        survivors.append(task)<br>    return survivors</pre><p>Three layers sounds like over-engineering. It isn’t. The grey band (0.30–0.62 similarity) is where humans would disagree too — and it’s exactly where embeddings alone get it wrong.</p><p>The LLM judge only runs on ~10–15% of candidates, so cost stays low. Duplicate suggestions in production dropped from <strong>23% to under 2%.</strong></p><h3>One More Thing: Parallelism Is Not Optional</h3><p>The main pipeline does a lot: read memory, fetch feedback, check reminders, generate tasks, generate nudges, dedup, save.</p><p>Done sequentially, it took <strong>32 seconds</strong>. With asyncio.gather wrapping the blocking calls and parallel phase orchestration, it dropped to <strong>under 9 seconds</strong> — a 70% reduction in generation latency and the difference between a system that scales and one that doesn’t.</p><p>Four phases:</p><ol><li><strong>Parallel DB reads</strong> — profile, feedback, existing tasks, blocked list</li><li><strong>Memory refresh + recurring tasks</strong> — conditional, parallel</li><li><strong>Task + nudge generation</strong> — two parallel LLM calls</li><li><strong>Dedup + save</strong> — parallel HTTP back to NestJS</li></ol><p>If you’re doing anything non-trivial with LLMs, parallel orchestration isn’t optimization. It’s architecture.</p><h3>Four Things I’d Build First Next Time</h3><ol><li><strong>The ban list before the generator.</strong> We built generation first. Retrofitting dedup was painful. If the AI will learn from feedback, model “what not to do” before “what to do.”</li><li><strong>Structured outputs from day one.</strong> Pydantic-validated LLM responses killed an entire category of parse-error bugs. Use response_format from the first call.</li><li><strong>Tagged memory from the start.</strong> [stable] / [recent] / [fading] is easy to add early and almost impossible to retrofit cleanly.</li><li><strong>Python gates on every LLM invariant.</strong> If a rule must hold, don’t ask the LLM to hold it. Hold it yourself.</li></ol><h3>The Bigger Lesson</h3><p>The hardest part of building an LLM-powered product isn’t the LLM. It’s figuring out where to stop trusting it.</p><p>The parts of our system users notice — suggestions that feel right, memory that feels like it “gets” them — are all outputs of GPT-4o. But the reason they feel right is the deterministic scaffolding around GPT-4o we spent months building.</p><p><strong>The AI is the feature. The code around it is the product.</strong></p><h3>If You’re Building Something Similar</h3><p>This is the kind of system I build as a freelance AI developer. If you’re working on a RAG pipeline, multi-agent system, or behavioral AI feature, my main Fiverr gig covers it:</p><p>🤖 <strong>Custom RAG Chatbot</strong> (trained on your docs or website) → <a href="https://www.fiverr.com/hamzapb31/build-a-custom-rag-chatbot-trained-on-your-documents-or-private-data">https://www.fiverr.com/hamzapb31/build-a-custom-rag-chatbot-trained-on-your-documents-or-private-data</a></p><p>I also offer OpenAI/LangChain chatbots, AI voice agents (VAPI/Retell), and clinic/appointment bots — all on the <a href="https://www.fiverr.com/hamzapb31">profile</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=565a70090338" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React from Scratch: Build a Tiny Renderer in Plain JavaScript]]></title>
            <link>https://medium.com/@hamzaaliics/understanding-react-from-scratch-build-a-tiny-renderer-in-plain-javascript-574e6d26b3c5?source=rss-d4839cebae07------2</link>
            <guid isPermaLink="false">https://medium.com/p/574e6d26b3c5</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Hamzaaliics]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 09:46:49 GMT</pubDate>
            <atom:updated>2025-12-13T09:46:49.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUrze8NVZx5DAVi4dtBh4g.png" /></figure><p>Many developers use React every day without understanding <em>why</em> it exists or <em>how</em> it works under the hood. In this article, we’ll start with <strong>plain JavaScript</strong>, explore the browser rendering pipeline, and then build a “React-like” system from scratch. By the end, React won’t feel magical — you’ll understand it conceptually.</p><h3>STEP 1 — The Browser Rendering Pipeline</h3><p>Before React, browsers already have a <strong>complex rendering process</strong>:</p><ol><li><strong>DOM creation:</strong> Browser parses HTML → builds <strong>DOM tree</strong></li><li><strong>CSSOM creation:</strong> Browser parses CSS → builds <strong>CSSOM tree</strong></li><li><strong>Render tree:</strong> DOM + CSSOM → visible elements with styles</li><li><strong>Layout (Reflow):</strong> Calculate position &amp; size of elements (expensive)</li><li><strong>Paint:</strong> Fill pixels, draw text, borders, shadows</li><li><strong>Composite (GPU):</strong> Combine layers, display final pixels</li></ol><p><strong>Key takeaway:</strong> JavaScript does <strong>not paint pixels</strong>; it changes DOM/CSSOM, which triggers browser re-rendering.</p><h3>Example — Text Change vs Layout Change vs GPU</h3><pre>&lt;h1 id=&quot;title&quot;&gt;Hello&lt;/h1&gt;<br>&lt;script&gt;<br>  const title = document.getElementById(&quot;title&quot;);<br>  title.textContent = &quot;Hi&quot;;                 // Text change → paint + composite<br>  title.style.fontSize = &quot;40px&quot;;            // Layout change → reflow + paint + composite<br>  title.style.transform = &quot;translateX(100px)&quot;; // GPU-only → fast<br>&lt;/script&gt;</pre><h3>STEP 2 — Why Plain JS Can Be Painful</h3><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  document.getElementById(&quot;count&quot;).textContent++;<br>  document.getElementById(&quot;total&quot;).textContent++;<br>  document.getElementById(&quot;status&quot;).textContent = &quot;Updated&quot;;<br>});</pre><ul><li>3 DOM writes → possibly 3 paints → multiple layouts</li><li>No batching, no awareness of minimal updates</li></ul><p><strong>Big realization:</strong> JS is fast, browser is fast, but <strong>DOM writes are the bottleneck</strong>.</p><h3>STEP 3 — Build a Tiny “React-Like” Renderer</h3><p><strong>Goal:</strong> Describe <strong>what the UI should look like</strong>, not update DOM manually.</p><h3>1️⃣ UI as a Function of State</h3><p>Instead of:</p><pre>countEl.textContent = count;<br>statusEl.textContent = &quot;Updated&quot;;</pre><p>We write:</p><pre>function render(state) {<br>  return `<br>    &lt;h1&gt;${state.count}&lt;/h1&gt;<br>    &lt;p&gt;${state.status}&lt;/p&gt;<br>  `;<br>}</pre><blockquote><em>UI = function(state)</em></blockquote><p>This is the <strong>conceptual foundation of React</strong>.</p><h3>2️⃣ Naive Re-render</h3><pre>let state = { count: 0, status: &quot;Idle&quot; };</pre><pre>function render(state) {<br>  document.getElementById(&quot;app&quot;).innerHTML = `<br>    &lt;h1&gt;${state.count}&lt;/h1&gt;<br>    &lt;p&gt;${state.status}&lt;/p&gt;<br>  `;<br>}</pre><pre>render(state);</pre><pre>// Update<br>state.count++;<br>state.status = &quot;Updated&quot;;<br>render(state);</pre><p><strong>Problem:</strong> Entire DOM is destroyed and recreated → wasteful.</p><h3>3️⃣ Virtual DOM — Represent UI in Memory</h3><pre>function h(type, props, children) {<br>  return { type, props, children };<br>}</pre><pre>function renderVDOM(state) {<br>  return h(&quot;div&quot;, {}, [<br>    h(&quot;h1&quot;, {}, state.count),<br>    h(&quot;p&quot;, {}, state.status)<br>  ]);<br>}</pre><ul><li>Just JS objects</li><li>Cheap to create</li><li>No browser updates yet</li></ul><h3>4️⃣ Initial Mount</h3><pre>function mount(vnode, container) {<br>  const el = document.createElement(vnode.type);<br>  el.textContent = vnode.children;<br>  container.appendChild(el);<br>}</pre><blockquote><em>Creates real DOM </em><strong><em>once</em></strong><em>.</em></blockquote><h3>5️⃣ Update Phase — Diffing</h3><pre>function diff(oldNode, newNode, domNode) {<br>  if (oldNode.children !== newNode.children) {<br>    domNode.textContent = newNode.children;<br>  }<br>}</pre><blockquote><em>Only changed nodes are updated → minimal paint. This is </em><strong><em>reconciliation</em></strong><em>.</em></blockquote><h3>6️⃣ Mental Model: React Conceptually</h3><p>ConceptMeaningStateDataRenderProduce virtual treeVirtual DOMUI in memoryDiffingCompare old vs newCommitMinimal DOM writes</p><blockquote><em>You just built </em><strong><em>React conceptually</em></strong><em>.</em></blockquote><h3>STEP 4 — Compare Old UI vs New UI</h3><pre>// State 1<br>let state = { count: 0, status: &quot;Idle&quot; };<br>// State 2<br>state.count = 1;<br>state.status = &quot;Idle&quot;;</pre><ul><li>Only &lt;h1&gt; changed → only update that</li><li>&lt;p&gt; unchanged → skip</li></ul><blockquote><em>Without diffing → full repaint<br>With diffing → minimal updates → smooth, scalable</em></blockquote><h3>STEP 5 — Render → Commit Phases in React</h3><p><strong>Render Phase:</strong> JS only, produces Virtual DOM → cheap.<br><strong>Commit Phase:</strong> Minimal DOM writes → expensive.</p><p><strong>Example — Counter Component</strong></p><pre>function Counter({ count }) {<br>  return &lt;h1&gt;{count}&lt;/h1&gt;;<br>}</pre><ol><li>Render Phase: Counter(1) → virtual DOM {type:&quot;h1&quot;, children:1}</li><li>Diffing → compare with old {type:&quot;h1&quot;, children:0}</li><li>Commit Phase → update text node only</li></ol><blockquote><em>Browser layout/paint occurs </em><strong><em>only for the changed nodes</em></strong><em>.</em></blockquote><h3>Full Pipeline (Browser + React)</h3><pre>[State / Props Change]<br>         ↓<br>   Render Phase (JS only, Virtual DOM)<br>         ↓<br>   Diffing / Reconciliation<br>         ↓<br>   Commit Phase (minimal real DOM updates)<br>         ↓<br>Browser: Layout → Paint → Composite → Pixels on screen</pre><h3>Key Takeaways</h3><ol><li>Render Phase = JS only → cheap, safe</li><li>Diffing = compare snapshots → minimal DOM updates</li><li>Commit Phase = real DOM updates → expensive</li><li>Browser pipeline = layout → paint → composite</li><li>React = scheduler + diff engine → optimal rendering</li><li>Hooks, memo, keys → control rendering and commit efficiently</li></ol><h3>Visual Memory Trick</h3><p>Think of React as a <strong>designer + assistant + printer</strong>:</p><ul><li>Designer = Render Phase (draw in memory)</li><li>Assistant = Diffing (decides what changed)</li><li>Printer = Commit Phase → DOM → pixels</li><li>GPU = displays final poster</li></ul><p>This article lays the <strong>foundation</strong>. You now understand React <strong>conceptually</strong>, without magic. Hooks, keys, memo, Fiber — all are optimizations on top of this simple idea.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=574e6d26b3c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>